admin.go 12 KB

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