admin.go 12 KB

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