errors.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Package auth provides authentication functionality
  2. package auth
  3. import (
  4. "errors"
  5. "fmt"
  6. )
  7. // Common auth error types
  8. var (
  9. // ErrInvalidToken indicates the JWT token is invalid or malformed
  10. ErrInvalidToken = errors.New("invalid token")
  11. // ErrExpiredToken indicates the JWT token has expired
  12. ErrExpiredToken = errors.New("token expired")
  13. // ErrInvalidSigningMethod indicates an unsupported signing method was used
  14. ErrInvalidSigningMethod = errors.New("invalid signing method")
  15. // ErrInvalidClaims indicates the token claims are invalid or missing
  16. ErrInvalidClaims = errors.New("invalid token claims")
  17. // ErrEmptyToken indicates an empty token was provided
  18. ErrEmptyToken = errors.New("empty token")
  19. // ErrInvalidConfig indicates invalid JWT configuration
  20. ErrInvalidConfig = errors.New("invalid JWT configuration")
  21. )
  22. // Error represents an authentication-specific error with detailed context
  23. type Error struct {
  24. // Op is the operation that failed (e.g., "generate", "validate", "parse")
  25. Op string
  26. // Err is the underlying error
  27. Err error
  28. // Details contains additional error context
  29. Details string
  30. }
  31. // Error returns a string representation of the error
  32. func (e *Error) Error() string {
  33. msg := fmt.Sprintf("auth %s failed", e.Op)
  34. if e.Details != "" {
  35. msg = fmt.Sprintf("%s: %s", msg, e.Details)
  36. }
  37. if e.Err != nil {
  38. msg = fmt.Sprintf("%s: %v", msg, e.Err)
  39. }
  40. return msg
  41. }
  42. // Unwrap returns the underlying error
  43. func (e *Error) Unwrap() error {
  44. return e.Err
  45. }
  46. // Is reports whether target matches this error
  47. func (e *Error) Is(target error) bool {
  48. return errors.Is(e.Err, target)
  49. }
  50. // NewError creates a new auth error
  51. func NewError(op string, err error, details string) *Error {
  52. return &Error{
  53. Op: op,
  54. Err: err,
  55. Details: details,
  56. }
  57. }
  58. // IsExpiredTokenError returns true if the error indicates an expired token
  59. func IsExpiredTokenError(err error) bool {
  60. var e *Error
  61. return errors.As(err, &e) && errors.Is(e.Err, ErrExpiredToken)
  62. }
  63. // IsInvalidTokenError returns true if the error indicates an invalid token
  64. func IsInvalidTokenError(err error) bool {
  65. var e *Error
  66. return errors.As(err, &e) && (errors.Is(e.Err, ErrInvalidToken) ||
  67. errors.Is(e.Err, ErrInvalidSigningMethod) ||
  68. errors.Is(e.Err, ErrInvalidClaims))
  69. }