get_auth_logic.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package chat
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. "wechat-api/internal/svc"
  8. "wechat-api/internal/types"
  9. myjwt "github.com/golang-jwt/jwt/v4"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. )
  12. type GetAuthLogic struct {
  13. logx.Logger
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. }
  17. func NewGetAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAuthLogic {
  18. return &GetAuthLogic{
  19. Logger: logx.WithContext(ctx),
  20. ctx: ctx,
  21. svcCtx: svcCtx}
  22. }
  23. func (l *GetAuthLogic) GetAuth() (resp *types.BaseMsgResp, err error) {
  24. // todo: add your logic here and delete this line
  25. nowSec := time.Now().Unix()
  26. accessExpire := l.svcCtx.Config.Auth.AccessExpire
  27. accessSecret := l.svcCtx.Config.Auth.AccessSecret
  28. Id := RangeRandom(1, 99999)
  29. accessToken, err := getToken(accessSecret, nowSec, accessExpire, Id)
  30. if err != nil {
  31. accessToken = ""
  32. }
  33. msg := fmt.Sprintf("gen Token:'%s' by Id:%d and unixtime:%d \n", accessToken, Id, nowSec)
  34. return &types.BaseMsgResp{
  35. Code: 100,
  36. Msg: msg,
  37. }, err
  38. }
  39. func getToken(secretKey string, iat, seconds, uid int64) (string, error) {
  40. claims := make(myjwt.MapClaims)
  41. claims["exp"] = iat + seconds
  42. claims["iat"] = iat
  43. claims["uid"] = uid
  44. token := myjwt.New(myjwt.SigningMethodHS256)
  45. token.Claims = claims
  46. return token.SignedString([]byte(secretKey))
  47. }
  48. // RangeRandom 返回指定范围内的随机整数。[min,max),不包含max
  49. func RangeRandom(min, max int64) (number int64) {
  50. //创建随机种子
  51. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  52. number = r.Int63n(max-min) + min
  53. return number
  54. }