123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package middleware
- import (
- "context"
- "encoding/json"
- "fmt"
- "github.com/gin-gonic/gin"
- "hongze/hrms_api/controller/resp"
- "hongze/hrms_api/global"
- "hongze/hrms_api/models/system"
- "hongze/hrms_api/utils"
- "time"
- )
- func Token() gin.HandlerFunc {
- return func(c *gin.Context) {
- token := c.Request.Header.Get("Authorization")
- if token == "" {
- token = c.DefaultQuery("authorization", "")
- if token == "" {
- token = c.DefaultQuery("Authorization", "")
- }
- }
- if token == "" {
- resp.TokenError(nil, "未登录或非法访问", "未登录或非法访问", c)
- c.Abort()
- return
- }
- sessionInfo := new(system.LoginTokenContent)
- content, _ := global.Redis.Get(context.TODO(), utils.HRSYSTEM_LOGIN_TOKEN+token).Result()
- if content == "" {
- resp.TokenError(nil, "信息已变更,请重新登陆!", "找不到对应session", c)
- c.Abort()
- return
- }
- err := json.Unmarshal([]byte(content), &sessionInfo)
- if sessionInfo == nil {
- resp.TokenError(nil, "信息已变更,请重新登陆!", "session解析失败", c)
- c.Abort()
- return
- }
- admin := new(system.SysAdmin)
- admin, err = admin.GetAdminByAdminId(sessionInfo.AdminId)
- if err != nil {
- if err == utils.ErrNoRow {
- resp.TokenError(nil, "信息已变更,请重新登陆!", "找不到对应账号", c)
- c.Abort()
- return
- }
- resp.TokenError(nil, "网络异常,请稍后重试!", err.Error(), c)
- c.Abort()
- return
- }
- if admin.Enabled == 0 {
- resp.SpecificFail(resp.HASFORBIDDEN_CODE, nil, "您的账号已被禁用,如需登录,请联系管理员", c)
- c.Abort()
- return
- }
- /*if admin.Password != sessionInfo.Password {
- resp.SpecificFail(resp.PASSWORDCHANGE_CODE, nil, "信息已变更,请重新登陆!", c)
- c.Abort()
- return
- }*/
- //更新token的有效期,重置为30秒
- global.Redis.SetEX(context.TODO(), utils.HRSYSTEM_LOGIN_TOKEN+token, content, 120*time.Minute)
- // 不信任名单也同步更新
- if !sessionInfo.IsRemember {
- noTrustLoginKey := fmt.Sprint(utils.HRSYSTEM_LOGIN_TOKEN_NO_TRUST, admin.AdminId)
- tokenContent, _ := global.Redis.Get(context.TODO(), noTrustLoginKey).Result()
- if tokenContent != "" {
- global.Redis.SetEX(context.TODO(), noTrustLoginKey, tokenContent, 120*time.Minute)
- }
- }
- c.Set("adminInfo", admin)
- c.Next()
- }
- }
|