get_auth_logic.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package chat
  2. import (
  3. "context"
  4. "time"
  5. "wechat-api/internal/svc"
  6. "wechat-api/internal/types"
  7. myjwt "github.com/golang-jwt/jwt/v4"
  8. "github.com/zeromicro/go-zero/core/logx"
  9. )
  10. type GetAuthLogic struct {
  11. logx.Logger
  12. ctx context.Context
  13. svcCtx *svc.ServiceContext
  14. }
  15. func NewGetAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAuthLogic {
  16. return &GetAuthLogic{
  17. Logger: logx.WithContext(ctx),
  18. ctx: ctx,
  19. svcCtx: svcCtx}
  20. }
  21. func (l *GetAuthLogic) GetAuth() (resp *types.BaseMsgResp, err error) {
  22. // todo: add your logic here and delete this line
  23. now := time.Now().Unix()
  24. accessExpire := l.svcCtx.Config.Auth.AccessExpire
  25. accessSecret := l.svcCtx.Config.Auth.AccessSecret
  26. Id := now
  27. accessToken, err := getToken(accessSecret, now, accessExpire, Id)
  28. if err != nil {
  29. accessToken = ""
  30. }
  31. return &types.BaseMsgResp{
  32. Code: 100,
  33. Msg: accessToken,
  34. }, err
  35. }
  36. func getToken(secretKey string, iat, seconds, uid int64) (string, error) {
  37. claims := make(myjwt.MapClaims)
  38. claims["exp"] = iat + seconds
  39. claims["iat"] = iat
  40. claims["uid"] = uid
  41. token := myjwt.New(myjwt.SigningMethodHS256)
  42. token.Claims = claims
  43. return token.SignedString([]byte(secretKey))
  44. }