checkauthlogic.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package logic
  2. import (
  3. "context"
  4. "github.com/golang-jwt/jwt/v4"
  5. "github.com/pkg/errors"
  6. "ylink/ext/result"
  7. "ylink/core/auth/rpc/internal/svc"
  8. "ylink/core/auth/rpc/pb"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. )
  11. type CheckAuthLogic struct {
  12. ctx context.Context
  13. svcCtx *svc.ServiceContext
  14. logx.Logger
  15. }
  16. func NewCheckAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckAuthLogic {
  17. return &CheckAuthLogic{
  18. ctx: ctx,
  19. svcCtx: svcCtx,
  20. Logger: logx.WithContext(ctx),
  21. }
  22. }
  23. func (l *CheckAuthLogic) CheckAuth(in *pb.CheckAuthReq) (*pb.CheckAuthResp, error) {
  24. token, err := jwt.Parse(in.AccessToken, func(token *jwt.Token) (i interface{}, err error) {
  25. return []byte(l.svcCtx.Config.JwtAuth.AccessSecret), nil
  26. })
  27. if token.Valid {
  28. return &pb.CheckAuthResp{}, nil
  29. } else if ve, ok := err.(*jwt.ValidationError); ok {
  30. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  31. return nil, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  32. } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
  33. // Token is either expired or not active yet
  34. return nil, errors.Wrap(result.NewErrCode(result.TokenExpireError), "")
  35. } else {
  36. return nil, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  37. }
  38. } else {
  39. return nil, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  40. }
  41. }