智盟项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.0 KiB

  1. package hdl
  2. import (
  3. "applet/app/e"
  4. "applet/app/md"
  5. "applet/app/utils"
  6. "applet/app/utils/cache"
  7. "errors"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. )
  11. func GetAuthorizationCode(c *gin.Context) {
  12. masterId := c.Query("master_id")
  13. cacheKey := md.ZhimengAuthorizationCodeCacheKey
  14. authorizationCode := utils.RandString(32)
  15. _, err := cache.HSet(cacheKey, authorizationCode, masterId)
  16. if err != nil {
  17. e.OutErr(c, e.ERR, err.Error())
  18. return
  19. }
  20. //设置过期日期
  21. _, err = cache.Expire(cacheKey, md.ZhimengAuthorizationCodeCacheTime*30)
  22. if err != nil {
  23. e.OutErr(c, e.ERR, err.Error())
  24. return
  25. }
  26. e.OutSuc(c, map[string]interface{}{
  27. "authorization_code": authorizationCode,
  28. }, nil)
  29. }
  30. func GetToken(c *gin.Context) {
  31. authorizationCode := c.Query("authorization_code")
  32. cacheKey := md.ZhimengAuthorizationCodeCacheKey
  33. get, err := cache.HGetString(cacheKey, authorizationCode)
  34. if err != nil {
  35. e.OutErr(c, e.ERR, err.Error())
  36. return
  37. }
  38. if get == "" {
  39. e.OutErr(c, e.ERR, errors.New("授权码有误"))
  40. return
  41. }
  42. token, refreshToken, err := utils.GenToken(get)
  43. if err != nil {
  44. e.OutErr(c, e.ERR, err.Error())
  45. return
  46. }
  47. e.OutSuc(c, map[string]interface{}{
  48. "token": token,
  49. "refresh_token": refreshToken,
  50. "master_id": get,
  51. }, nil)
  52. }
  53. func RefreshToken(c *gin.Context) {
  54. var args struct {
  55. RefreshToken string `json:"refresh_token"`
  56. }
  57. if err := c.ShouldBindJSON(&args); err != nil {
  58. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  59. return
  60. }
  61. //1、验证refresh_token正确性
  62. //验证token字符串
  63. claim, err := utils.ParseRToken(args.RefreshToken)
  64. if err != nil {
  65. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("refresh_token 验证失败"))
  66. return
  67. }
  68. //过期判断
  69. if time.Now().Unix() > claim.ExpiresAt {
  70. e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("refresh_token 过期已失效"))
  71. return
  72. }
  73. //2、生成新的token && refresh_token
  74. token, refreshToken, err := utils.GenToken(claim.MasterId)
  75. e.OutSuc(c, map[string]interface{}{
  76. "token": token,
  77. "refresh_token": refreshToken,
  78. "master_id": claim.MasterId,
  79. }, nil)
  80. }