sys_admin.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package system
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "hongze/fms_api/global"
  8. "hongze/fms_api/models/system"
  9. "hongze/fms_api/utils"
  10. "strconv"
  11. "time"
  12. )
  13. func Login(adminName, password string, isRemember bool) (ret system.LoginResp, err error, errMsg string) {
  14. //查询管理员账号是否存在
  15. admin := new(system.SysAdmin)
  16. adminInfo, err := admin.GetAdminByAdminName(adminName)
  17. if err != nil {
  18. if err == utils.ErrNoRow {
  19. errMsg = "登录失败,账号错误"
  20. err = errors.New(errMsg + "Err:" + err.Error())
  21. return
  22. }
  23. errMsg = "登录失败,查询账号出错"
  24. err = errors.New(errMsg + "Err:" + err.Error())
  25. return
  26. }
  27. //查询密码是否匹配
  28. if adminInfo.Password != password {
  29. errMsg = "登录失败,密码错误"
  30. err = errors.New(errMsg)
  31. return
  32. }
  33. //查询账号是否有效
  34. if adminInfo.Enabled == 0 {
  35. errMsg = "您的账号已被禁用,如需登录,请联系管理员"
  36. err = errors.New(errMsg + "已禁用账号:" + adminInfo.AdminName + " " + adminInfo.RealName)
  37. return
  38. }
  39. //生成token
  40. token, err := utils.GenToken(strconv.Itoa(int(adminInfo.AdminId)) + adminInfo.AdminName)
  41. if err != nil {
  42. errMsg = "登录失败,生成token出错"
  43. err = errors.New(errMsg + "Err:" + err.Error())
  44. return
  45. }
  46. //新增session记录
  47. sysSession := new(system.LoginTokenContent)
  48. sysSession.AdminId = adminInfo.AdminId
  49. sysSession.Password = adminInfo.Password
  50. sysSession.IsRemember = isRemember
  51. tokenStr, _ := json.Marshal(sysSession)
  52. //将session保存到redis当中
  53. global.Redis.SetEX(context.TODO(), utils.SYSTEM_LOGIN_TOKEN+token, tokenStr, 120*time.Minute)
  54. // 获取不可信的登录态,并将该登录态重置掉,不允许多次登录
  55. noTrustLoginKey := fmt.Sprint(utils.SYSTEM_LOGIN_TOKEN_NO_TRUST, adminInfo.AdminId)
  56. noTrustLoginToken, _ := global.Redis.Get(context.TODO(), noTrustLoginKey).Result()
  57. if noTrustLoginToken != `` { // 如果存在不可信设备,那么将其下架
  58. global.Redis.Del(context.TODO(), utils.SYSTEM_LOGIN_TOKEN+noTrustLoginToken)
  59. }
  60. // 如果当前是不可信设备,那么将其加入到不可信名单
  61. if !isRemember {
  62. noTrustLoginKey := fmt.Sprint(utils.SYSTEM_LOGIN_TOKEN_NO_TRUST, adminInfo.AdminId)
  63. global.Redis.Set(context.TODO(), noTrustLoginKey, token, 120*time.Minute)
  64. }
  65. //更新用户的最新登录时间
  66. adminInfo.LastLoginTime = time.Now()
  67. err = adminInfo.Update([]string{"last_login_time"})
  68. if err != nil {
  69. errMsg = "更新登录信息失败"
  70. err = errors.New(errMsg + "Err:" + err.Error())
  71. return
  72. }
  73. ret.AdminName = adminInfo.AdminName
  74. ret.RealName = adminInfo.RealName
  75. ret.AdminId = adminInfo.AdminId
  76. ret.Token = token
  77. if password == utils.DefaultPwd {
  78. ret.ChangePwd = true
  79. }
  80. return
  81. }