admin.go 12 KB

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