admin.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "regexp"
  6. "strings"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/mhaya/game/game_cluster/internal/code"
  10. "github.com/mhaya/game/game_cluster/internal/constant"
  11. "github.com/mhaya/game/game_cluster/internal/mdb"
  12. "github.com/mhaya/game/game_cluster/internal/mdb/models"
  13. "github.com/mhaya/game/game_cluster/nodes/webadmin/common"
  14. "github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
  15. "github.com/mhaya/game/game_cluster/nodes/webadmin/model"
  16. mhayaLogger "github.com/mhaya/logger"
  17. "go.mongodb.org/mongo-driver/bson"
  18. "go.mongodb.org/mongo-driver/bson/primitive"
  19. "go.mongodb.org/mongo-driver/mongo"
  20. "go.mongodb.org/mongo-driver/mongo/options"
  21. "golang.org/x/crypto/bcrypt"
  22. )
  23. type Admin struct {
  24. db *mongo.Database
  25. }
  26. func NewAdmin() *Admin {
  27. return &Admin{
  28. db: mdb.MDB,
  29. }
  30. }
  31. func (a *Admin) GetDB() *mongo.Database {
  32. return a.db
  33. }
  34. func (a *Admin) GetDBName() string {
  35. return "admin"
  36. }
  37. func CheckPasswordHash(password, hash string) bool {
  38. err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
  39. return err == nil
  40. }
  41. // HashPassword 加密密码
  42. func HashPassword(password string) (string, error) {
  43. bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
  44. return string(bytes), err
  45. }
  46. // Login 登录
  47. func (a *Admin) Login(ctx *gin.Context, username string, password string) (*entity.AdminResp, *code.Result) {
  48. user, err := a.QueryUserByUsername(ctx, username)
  49. if err != nil {
  50. mhayaLogger.Warnf("Login QueryUserByUsername error:", err)
  51. return nil, common.NewResult(code.InternalError)
  52. }
  53. // 判断用户状态
  54. if user.Status != 1 {
  55. return nil, common.NewResult(code.DisabledUserError)
  56. }
  57. // 判断密码
  58. if !CheckPasswordHash(password, user.Password) {
  59. return nil, common.NewResult(code.UserNameOrPasswordError)
  60. }
  61. // 创建token
  62. generateToken, err := user.GenerateToken()
  63. if err != nil {
  64. mhayaLogger.Warnf("Login GenerateToken error:", err)
  65. return nil, common.NewResult(code.InternalError)
  66. }
  67. // 保存token 到 redis 中 过期时间为1天
  68. err = mdb.RDB.Set(ctx, generateToken, user.Username, 24*time.Hour).Err()
  69. if err != nil {
  70. mhayaLogger.Warnf("Login Set error:", err)
  71. return nil, common.NewResult(code.InternalError)
  72. }
  73. err = a.loginAuthSetRoleRedis(user.RoleId, generateToken)
  74. if err != nil {
  75. mhayaLogger.Warnf("Login loginAuthSetRoleRedis error:", err)
  76. return nil, common.NewResult(code.InternalError)
  77. }
  78. // 更新用户登录时间
  79. _, err = mdb.MDB.Collection(a.GetDBName()).UpdateOne(ctx, bson.M{"username": username}, bson.M{"$set": bson.M{"last_login_time": time.Now().Unix()}})
  80. if err != nil {
  81. mhayaLogger.Warnf("Login UpdateOne last_login_time error:", err)
  82. return nil, common.NewResult(code.InternalError)
  83. }
  84. // 更新用户IP
  85. ip := ctx.ClientIP()
  86. _, err = mdb.MDB.Collection(a.GetDBName()).UpdateOne(ctx, bson.M{"username": username}, bson.M{"$set": bson.M{"last_login_ip": ip}})
  87. if err != nil {
  88. mhayaLogger.Warnf("Login UpdateOne ip error:", err)
  89. return nil, common.NewResult(code.InternalError)
  90. }
  91. // 返回用户信息
  92. resp := &entity.AdminResp{
  93. ToKen: generateToken,
  94. RoleID: user.RoleId,
  95. }
  96. mhayaLogger.Debugf("Login result:", resp)
  97. return resp, nil
  98. }
  99. // LoginAuthSetRoleRedis 登录时写入该用户的权限
  100. func (a *Admin) loginAuthSetRoleRedis(roleID, generateToken string) error {
  101. if roleID == constant.AdminAccess {
  102. mdb.RDB.HSet(context.Background(), "admin::token::"+generateToken, constant.AdminAccess, 1)
  103. mdb.RDB.Expire(context.Background(), "admin::token::"+generateToken, 24*time.Hour).Err()
  104. return nil
  105. }
  106. // 写入redis
  107. role := models.Roles{}
  108. collection := mdb.MDB.Collection(role.TableName())
  109. roleIdObj, _ := primitive.ObjectIDFromHex(roleID)
  110. filter := bson.M{"_id": roleIdObj, "status": 1}
  111. err := collection.FindOne(context.TODO(), filter).Decode(&role)
  112. if err != nil {
  113. return err
  114. }
  115. roleAccess := models.RoleAccess{}
  116. collection = mdb.MDB.Collection(roleAccess.TableName())
  117. roleAccessFilter := bson.M{"role_id": roleID}
  118. err = collection.FindOne(context.TODO(), roleAccessFilter).Decode(&roleAccess)
  119. if err != nil {
  120. return err
  121. }
  122. // 写入redis
  123. var accessIDS []primitive.ObjectID
  124. for _, v := range roleAccess.AccessID {
  125. accessIdObj, _ := primitive.ObjectIDFromHex(v)
  126. accessIDS = append(accessIDS, accessIdObj)
  127. }
  128. access := models.Access{}
  129. var accessList []models.Access
  130. collection = mdb.MDB.Collection(access.TableName())
  131. accessFilter := bson.M{"_id": bson.M{"$in": accessIDS}}
  132. cursor, err := collection.Find(context.Background(), accessFilter)
  133. if err != nil {
  134. return err
  135. }
  136. if err = cursor.All(context.Background(), &accessList); err != nil {
  137. return err
  138. }
  139. for _, v := range accessList {
  140. mdb.RDB.HSet(context.Background(), "admin::token::"+generateToken, v.URL, 1)
  141. }
  142. mdb.RDB.Expire(context.Background(), "admin::token::"+generateToken, 24*time.Hour).Err()
  143. return nil
  144. }
  145. // QueryUserByUsername 根据用户名查询用户
  146. func (a *Admin) QueryUserByUsername(ctx context.Context, username string) (*model.Admin, error) {
  147. admin := &model.Admin{}
  148. err := mdb.MDB.Collection(a.GetDBName()).FindOne(ctx, bson.M{"username": username}).Decode(&admin)
  149. if errors.Is(err, mongo.ErrNoDocuments) && username == "admin" {
  150. // 如果是admin 登录的话 创建一个初始的admin并且存入数据库
  151. pwd, err := HashPassword("123456")
  152. if err != nil {
  153. return nil, err
  154. }
  155. admin = &model.Admin{
  156. Username: constant.AdminAccess,
  157. Password: pwd,
  158. RealName: constant.AdminAccess,
  159. Pid: "0",
  160. RoleId: constant.AdminAccess,
  161. ManagerAuth: 0,
  162. Status: 1,
  163. CreatedAt: 0,
  164. UpdatedAt: 0,
  165. DeletedAt: 0,
  166. LastLoginIp: "",
  167. LastLoginTime: 0,
  168. }
  169. _, err = mdb.MDB.Collection(a.GetDBName()).InsertOne(ctx, bson.M{
  170. "username": constant.AdminAccess,
  171. "password": pwd,
  172. "real_name": constant.AdminAccess,
  173. "pid": "0",
  174. "role_id": constant.AdminAccess,
  175. "status": 1,
  176. })
  177. if err != nil {
  178. return nil, err
  179. }
  180. return admin, nil
  181. }
  182. if err != nil {
  183. return nil, err
  184. }
  185. return admin, nil
  186. }
  187. // ChangePassword 修改管理员密码
  188. func (a *Admin) ChangePassword(ctx context.Context, username string, password string) *code.Result {
  189. // 更新密码
  190. password, _ = HashPassword(password)
  191. _, err := mdb.MDB.Collection(a.GetDBName()).UpdateOne(ctx, bson.M{"username": username}, bson.M{"$set": bson.M{"password": password}})
  192. if err != nil {
  193. mhayaLogger.Warnf("ChangePassword UpdateOne error:", err)
  194. return common.NewResult(code.InternalError)
  195. }
  196. return nil
  197. }
  198. // Add 添加管理员
  199. func (a *Admin) Add(ctx context.Context, username string, password string, realName string, pid string, roleId string, status int) *code.Result {
  200. // 判断账号是否重复
  201. admin := model.Admin{}
  202. err := mdb.MDB.Collection(a.GetDBName()).FindOne(ctx, bson.M{"username": username}).Decode(&admin)
  203. if errors.Is(err, mongo.ErrNoDocuments) {
  204. password, _ = HashPassword(password)
  205. _, err := mdb.MDB.Collection(a.GetDBName()).InsertOne(ctx, bson.M{
  206. "username": username,
  207. "password": password,
  208. "real_name": realName,
  209. "pid": pid,
  210. "role_id": roleId,
  211. "status": status,
  212. "created_at": time.Now().Unix(),
  213. "updated_at": time.Now().Unix(),
  214. })
  215. if err != nil {
  216. mhayaLogger.Warnf("Add InsertOne error:", err)
  217. return common.NewResult(code.InternalError)
  218. }
  219. return nil
  220. }
  221. return common.NewResult(code.AccountExistError)
  222. }
  223. // Delete 删除管理员
  224. func (a *Admin) Delete(ctx context.Context, username string) *code.Result {
  225. _, err := mdb.MDB.Collection(a.GetDBName()).DeleteOne(ctx, bson.M{"username": username})
  226. if err != nil {
  227. mhayaLogger.Warnf("Delete DeleteOne error:", err)
  228. return common.NewResult(code.InternalError)
  229. }
  230. return nil
  231. }
  232. // UpdateStatus updateStatus
  233. func (a *Admin) UpdateStatus(ctx context.Context, username string, status int) *code.Result {
  234. _, err := mdb.MDB.Collection(a.GetDBName()).UpdateOne(ctx, bson.M{"username": username}, bson.M{"$set": bson.M{"status": status}})
  235. if err != nil {
  236. mhayaLogger.Warnf("Delete UpdateOne error:", err)
  237. return common.NewResult(code.InternalError)
  238. }
  239. return nil
  240. }
  241. // FindAll 查找所有管理员信息
  242. func (a *Admin) FindAll(ctx context.Context, page int, pageSize int, username string) (*entity.AdminListResp, *code.Result) {
  243. // 日志记录
  244. mhayaLogger.Warnf("Finding admins with page %d and page size %d, username: %s", page, pageSize, maskUsername(username))
  245. // 验证参数
  246. if page <= 0 {
  247. page = 1
  248. }
  249. if pageSize <= 0 {
  250. pageSize = 10
  251. }
  252. // 构建查询条件
  253. filter := bson.M{}
  254. if username != "" {
  255. filter["username"] = bson.M{"$regex": escapeRegex(username), "$options": "i"}
  256. }
  257. // 查询总数
  258. count, err := mdb.MDB.Collection("admin").CountDocuments(ctx, filter)
  259. if err != nil {
  260. mhayaLogger.Warnf("FindAll CountDocuments error:", err)
  261. return nil, common.NewResult(code.InternalError)
  262. }
  263. // 设置分页选项
  264. skip := (page - 1) * pageSize
  265. limit := pageSize
  266. findOptions := options.Find().SetSkip(int64(skip)).SetLimit(int64(limit))
  267. // 执行查询
  268. cursor, err := mdb.MDB.Collection("admin").Find(ctx, filter, findOptions)
  269. if err != nil {
  270. mhayaLogger.Warnf("FindAll Find error:", err)
  271. return nil, common.NewResult(code.InternalError)
  272. }
  273. defer func() {
  274. if closeErr := cursor.Close(ctx); closeErr != nil {
  275. mhayaLogger.Warnf("Error closing cursor: %v", closeErr)
  276. }
  277. }()
  278. // 解析结果
  279. admins := make([]*model.Admin, 0)
  280. for cursor.Next(ctx) {
  281. var admin model.Admin
  282. err := cursor.Decode(&admin)
  283. if err != nil {
  284. mhayaLogger.Warnf("FindAll Decode error:", err)
  285. return nil, common.NewResult(code.InternalError)
  286. }
  287. admins = append(admins, &admin)
  288. }
  289. if err := cursor.Err(); err != nil {
  290. mhayaLogger.Warnf("FindAll cursor error:", err)
  291. return nil, common.NewResult(code.InternalError)
  292. }
  293. var details []*entity.AdminListDetail
  294. for _, admin := range admins {
  295. roleName := ""
  296. roleName, _ = a.GetRoleName(admin.RoleId)
  297. details = append(details, &entity.AdminListDetail{
  298. Id: admin.GetID(),
  299. Username: admin.Username,
  300. RealName: admin.RealName,
  301. RoleId: admin.RoleId,
  302. RoleName: roleName,
  303. Status: admin.Status,
  304. CreatedAt: admin.CreatedAt,
  305. UpdatedAt: admin.UpdatedAt,
  306. LastLoginIp: admin.LastLoginIp,
  307. LastLoginTime: admin.LastLoginTime,
  308. })
  309. }
  310. return &entity.AdminListResp{
  311. Details: details,
  312. Total: count,
  313. }, nil
  314. }
  315. func (a *Admin) GetRoleName(roleID string) (string, error) {
  316. objID, err := primitive.ObjectIDFromHex(roleID)
  317. if err != nil {
  318. return "", err
  319. }
  320. var role models.Roles
  321. err = mdb.MDB.Collection(role.TableName()).FindOne(context.Background(), bson.M{"_id": objID}).Decode(&role)
  322. return role.Name, err
  323. }
  324. // GetServerStatus 获取服务器状态
  325. func (a *Admin) GetServerStatus(ctx context.Context) ([]*models.PlayerServerLoadStat, *code.Result) {
  326. // 执行查询
  327. cursor, err := mdb.MDB.Collection(constant.CNameServerLoadStat).Find(ctx, bson.M{})
  328. if err != nil {
  329. mhayaLogger.Warnf("GetServerStatus Find error:", err)
  330. return nil, common.NewResult(code.InternalError)
  331. }
  332. defer func() {
  333. if closeErr := cursor.Close(ctx); closeErr != nil {
  334. mhayaLogger.Warnf("Error closing cursor: %v", closeErr)
  335. }
  336. }()
  337. // 解析结果
  338. admins := make([]*models.PlayerServerLoadStat, 0)
  339. for cursor.Next(ctx) {
  340. var admin models.PlayerServerLoadStat
  341. err := cursor.Decode(&admin)
  342. if err != nil {
  343. mhayaLogger.Warnf("GetServerStatus Decode error:", err)
  344. return nil, common.NewResult(code.InternalError)
  345. }
  346. admins = append(admins, &admin)
  347. }
  348. if err := cursor.Err(); err != nil {
  349. mhayaLogger.Warnf("GetServerStatus cursor error:", err)
  350. return nil, common.NewResult(code.InternalError)
  351. }
  352. return admins, nil
  353. }
  354. // 辅助函数:对 username 进行脱敏处理
  355. func maskUsername(username string) string {
  356. if username == "" {
  357. return ""
  358. }
  359. return strings.Repeat("*", len(username))
  360. }
  361. // 辅助函数:对正则表达式进行转义
  362. func escapeRegex(s string) string {
  363. return regexp.QuoteMeta(s)
  364. }