package hdl import ( "applet/app/e" "applet/app/md" "applet/app/utils" "applet/app/utils/cache" "errors" "time" "github.com/gin-gonic/gin" ) func GetAuthorizationCode(c *gin.Context) { masterId := c.Query("master_id") cacheKey := md.ZhimengAuthorizationCodeCacheKey authorizationCode := utils.RandString(32) _, err := cache.HSet(cacheKey, authorizationCode, masterId) if err != nil { e.OutErr(c, e.ERR, err.Error()) return } //设置过期日期 _, err = cache.Expire(cacheKey, md.ZhimengAuthorizationCodeCacheTime*30) if err != nil { e.OutErr(c, e.ERR, err.Error()) return } e.OutSuc(c, map[string]interface{}{ "authorization_code": authorizationCode, }, nil) } func GetToken(c *gin.Context) { authorizationCode := c.Query("authorization_code") cacheKey := md.ZhimengAuthorizationCodeCacheKey get, err := cache.HGetString(cacheKey, authorizationCode) if err != nil { e.OutErr(c, e.ERR, err.Error()) return } if get == "" { e.OutErr(c, e.ERR, errors.New("授权码有误")) return } token, refreshToken, err := utils.GenToken(get) if err != nil { e.OutErr(c, e.ERR, err.Error()) return } e.OutSuc(c, map[string]interface{}{ "token": token, "refresh_token": refreshToken, "master_id": get, }, nil) } func RefreshToken(c *gin.Context) { var args struct { RefreshToken string `json:"refresh_token"` } if err := c.ShouldBindJSON(&args); err != nil { e.OutErr(c, e.ERR_INVALID_ARGS, err) return } //1、验证refresh_token正确性 //验证token字符串 claim, err := utils.ParseRToken(args.RefreshToken) if err != nil { e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("refresh_token 验证失败")) return } //过期判断 if time.Now().Unix() > claim.ExpiresAt { e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("refresh_token 过期已失效")) return } //2、生成新的token && refresh_token token, refreshToken, err := utils.GenToken(claim.MasterId) e.OutSuc(c, map[string]interface{}{ "token": token, "refresh_token": refreshToken, "master_id": claim.MasterId, }, nil) }