admin.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. // Find 获取管理员信息
  242. func (a *Admin) Find(ctx context.Context, req entity.AdminFindReq) (*entity.AdminListResp, *code.Result) {
  243. // 日志记录
  244. mhayaLogger.Warnf("Find req: %#v", req)
  245. // 验证参数
  246. page := req.Page
  247. if req.Page <= 0 {
  248. page = 1
  249. }
  250. pageSize := req.Size
  251. if req.Size <= 0 {
  252. pageSize = 10
  253. }
  254. // 构建查询条件
  255. filter := bson.M{}
  256. if req.Username != "" {
  257. filter["username"] = bson.M{"$regex": escapeRegex(req.Username), "$options": "i"}
  258. }
  259. // 查询总数
  260. count, err := mdb.MDB.Collection("admin").CountDocuments(ctx, filter)
  261. if err != nil {
  262. mhayaLogger.Warnf("Find CountDocuments error:", err)
  263. return nil, common.NewResult(code.InternalError)
  264. }
  265. // 设置分页选项
  266. skip := (page - 1) * pageSize
  267. limit := pageSize
  268. findOptions := options.Find().SetSkip(int64(skip)).SetLimit(int64(limit))
  269. // 执行查询
  270. cursor, err := mdb.MDB.Collection("admin").Find(ctx, filter, findOptions)
  271. if err != nil {
  272. mhayaLogger.Warnf("Find Find error:", err)
  273. return nil, common.NewResult(code.InternalError)
  274. }
  275. defer func() {
  276. if closeErr := cursor.Close(ctx); closeErr != nil {
  277. mhayaLogger.Warnf("Error closing cursor: %v", closeErr)
  278. }
  279. }()
  280. // 解析结果
  281. admins := make([]*model.Admin, 0)
  282. for cursor.Next(ctx) {
  283. var admin model.Admin
  284. err := cursor.Decode(&admin)
  285. if err != nil {
  286. mhayaLogger.Warnf("Find Decode error:", err)
  287. return nil, common.NewResult(code.InternalError)
  288. }
  289. admins = append(admins, &admin)
  290. }
  291. if err := cursor.Err(); err != nil {
  292. mhayaLogger.Warnf("Find cursor error:", err)
  293. return nil, common.NewResult(code.InternalError)
  294. }
  295. var details []*entity.AdminListDetail
  296. for _, admin := range admins {
  297. roleName := ""
  298. roleName, _ = a.GetRoleName(admin.RoleId)
  299. details = append(details, &entity.AdminListDetail{
  300. Id: admin.GetID(),
  301. Username: admin.Username,
  302. RealName: admin.RealName,
  303. RoleId: admin.RoleId,
  304. RoleName: roleName,
  305. Status: admin.Status,
  306. CreatedAt: admin.CreatedAt,
  307. UpdatedAt: admin.UpdatedAt,
  308. LastLoginIp: admin.LastLoginIp,
  309. LastLoginTime: admin.LastLoginTime,
  310. })
  311. }
  312. return &entity.AdminListResp{
  313. Details: details,
  314. Total: count,
  315. }, nil
  316. }
  317. // FindAll 查找所有管理员信息
  318. func (a *Admin) FindAll(ctx context.Context, req entity.AdminFindAllReq) (*entity.AdminListResp, *code.Result) {
  319. // 日志记录
  320. mhayaLogger.Warnf("FindAll req: %#v", req)
  321. // 验证参数
  322. page := req.Page
  323. if req.Page <= 0 {
  324. page = 1
  325. }
  326. pageSize := req.Size
  327. if req.Size <= 0 {
  328. pageSize = 10
  329. }
  330. // 构建查询条件
  331. // filter := bson.M{}
  332. // if req.Username != "" {
  333. // filter["username"] = bson.M{"$regex": escapeRegex(req.Username), "$options": "i"}
  334. // }
  335. // 查询总数
  336. // count, err := mdb.MDB.Collection("admin").CountDocuments(ctx, filter)
  337. count, err := mdb.MDB.Collection("admin").CountDocuments(ctx, map[string]interface{}{})
  338. if err != nil {
  339. mhayaLogger.Warnf("FindAll CountDocuments error:", err)
  340. return nil, common.NewResult(code.InternalError)
  341. }
  342. // 设置分页选项
  343. skip := (page - 1) * pageSize
  344. limit := pageSize
  345. findOptions := options.Find().SetSkip(int64(skip)).SetLimit(int64(limit))
  346. // 执行查询
  347. // cursor, err := mdb.MDB.Collection("admin").Find(ctx, filter, findOptions)
  348. cursor, err := mdb.MDB.Collection("admin").Find(ctx, map[string]interface{}{}, findOptions)
  349. if err != nil {
  350. mhayaLogger.Warnf("FindAll Find error:", err)
  351. return nil, common.NewResult(code.InternalError)
  352. }
  353. defer func() {
  354. if closeErr := cursor.Close(ctx); closeErr != nil {
  355. mhayaLogger.Warnf("Error closing cursor: %v", closeErr)
  356. }
  357. }()
  358. // 解析结果
  359. admins := make([]*model.Admin, 0)
  360. for cursor.Next(ctx) {
  361. var admin model.Admin
  362. err := cursor.Decode(&admin)
  363. if err != nil {
  364. mhayaLogger.Warnf("FindAll Decode error:", err)
  365. return nil, common.NewResult(code.InternalError)
  366. }
  367. admins = append(admins, &admin)
  368. }
  369. if err := cursor.Err(); err != nil {
  370. mhayaLogger.Warnf("FindAll cursor error:", err)
  371. return nil, common.NewResult(code.InternalError)
  372. }
  373. var details []*entity.AdminListDetail
  374. for _, admin := range admins {
  375. roleName := ""
  376. roleName, _ = a.GetRoleName(admin.RoleId)
  377. details = append(details, &entity.AdminListDetail{
  378. Id: admin.GetID(),
  379. Username: admin.Username,
  380. RealName: admin.RealName,
  381. RoleId: admin.RoleId,
  382. RoleName: roleName,
  383. Status: admin.Status,
  384. CreatedAt: admin.CreatedAt,
  385. UpdatedAt: admin.UpdatedAt,
  386. LastLoginIp: admin.LastLoginIp,
  387. LastLoginTime: admin.LastLoginTime,
  388. })
  389. }
  390. return &entity.AdminListResp{
  391. Details: details,
  392. Total: count,
  393. }, nil
  394. }
  395. func (a *Admin) GetRoleName(roleID string) (string, error) {
  396. objID, err := primitive.ObjectIDFromHex(roleID)
  397. if err != nil {
  398. return "", err
  399. }
  400. var role models.Roles
  401. err = mdb.MDB.Collection(role.TableName()).FindOne(context.Background(), bson.M{"_id": objID}).Decode(&role)
  402. return role.Name, err
  403. }
  404. // GetServerStatus 获取服务器状态
  405. func (a *Admin) GetServerStatus(ctx context.Context) ([]*models.PlayerServerLoadStat, *code.Result) {
  406. // 执行查询
  407. cursor, err := mdb.MDB.Collection(constant.CNameServerLoadStat).Find(ctx, bson.M{})
  408. if err != nil {
  409. mhayaLogger.Warnf("GetServerStatus Find error:", err)
  410. return nil, common.NewResult(code.InternalError)
  411. }
  412. defer func() {
  413. if closeErr := cursor.Close(ctx); closeErr != nil {
  414. mhayaLogger.Warnf("Error closing cursor: %v", closeErr)
  415. }
  416. }()
  417. // 解析结果
  418. admins := make([]*models.PlayerServerLoadStat, 0)
  419. for cursor.Next(ctx) {
  420. var admin models.PlayerServerLoadStat
  421. err := cursor.Decode(&admin)
  422. if err != nil {
  423. mhayaLogger.Warnf("GetServerStatus Decode error:", err)
  424. return nil, common.NewResult(code.InternalError)
  425. }
  426. admins = append(admins, &admin)
  427. }
  428. if err := cursor.Err(); err != nil {
  429. mhayaLogger.Warnf("GetServerStatus cursor error:", err)
  430. return nil, common.NewResult(code.InternalError)
  431. }
  432. return admins, nil
  433. }
  434. // 辅助函数:对 username 进行脱敏处理
  435. func maskUsername(username string) string {
  436. if username == "" {
  437. return ""
  438. }
  439. return strings.Repeat("*", len(username))
  440. }
  441. // 辅助函数:对正则表达式进行转义
  442. func escapeRegex(s string) string {
  443. return regexp.QuoteMeta(s)
  444. }