checkauthlogic.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package logic
  2. import (
  3. "context"
  4. "github.com/golang-jwt/jwt/v4"
  5. "github.com/pkg/errors"
  6. "ylink/comm/globalkey"
  7. "ylink/comm/jwtkey"
  8. "ylink/comm/result"
  9. "ylink/core/auth/rpc/internal/svc"
  10. "ylink/core/auth/rpc/pb"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. )
  13. type CheckAuthLogic struct {
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. logx.Logger
  17. }
  18. func NewCheckAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckAuthLogic {
  19. return &CheckAuthLogic{
  20. ctx: ctx,
  21. svcCtx: svcCtx,
  22. Logger: logx.WithContext(ctx),
  23. }
  24. }
  25. func (l *CheckAuthLogic) CheckAuth(in *pb.CheckAuthReq) (*pb.CheckAuthResp, error) {
  26. token, err := jwt.Parse(in.AccessToken, func(token *jwt.Token) (i interface{}, err error) {
  27. return []byte(l.svcCtx.Config.JwtAuth.AccessSecret), nil
  28. })
  29. if token.Valid {
  30. //将获取的token中的Claims强转为MapClaims
  31. claims, _ := token.Claims.(jwt.MapClaims)
  32. var uid string
  33. if in.Type == globalkey.CONNECT_TYPE_PLAYER {
  34. uid = claims[jwtkey.PlayerId].(string)
  35. } else {
  36. uid = claims[jwtkey.CsId].(string)
  37. }
  38. return &pb.CheckAuthResp{
  39. Uid: uid,
  40. }, nil
  41. } else if ve, ok := err.(*jwt.ValidationError); ok {
  42. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  43. return nil, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  44. } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
  45. // Token is either expired or not active yet
  46. return nil, errors.Wrap(result.NewErrCode(result.TokenExpireError), "")
  47. } else {
  48. return nil, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  49. }
  50. } else {
  51. return nil, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  52. }
  53. }