admin.go 12 KB

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