sys_admin.go 2.7 KB

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