12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- // Package auth provides authentication functionality
- package auth
- import (
- "errors"
- "fmt"
- )
- // Common auth error types
- var (
- // ErrInvalidToken indicates the JWT token is invalid or malformed
- ErrInvalidToken = errors.New("invalid token")
- // ErrExpiredToken indicates the JWT token has expired
- ErrExpiredToken = errors.New("token expired")
- // ErrInvalidSigningMethod indicates an unsupported signing method was used
- ErrInvalidSigningMethod = errors.New("invalid signing method")
- // ErrInvalidClaims indicates the token claims are invalid or missing
- ErrInvalidClaims = errors.New("invalid token claims")
- // ErrEmptyToken indicates an empty token was provided
- ErrEmptyToken = errors.New("empty token")
- // ErrInvalidConfig indicates invalid JWT configuration
- ErrInvalidConfig = errors.New("invalid JWT configuration")
- )
- // Error represents an authentication-specific error with detailed context
- type Error struct {
- // Op is the operation that failed (e.g., "generate", "validate", "parse")
- Op string
- // Err is the underlying error
- Err error
- // Details contains additional error context
- Details string
- }
- // Error returns a string representation of the error
- func (e *Error) Error() string {
- msg := fmt.Sprintf("auth %s failed", e.Op)
- if e.Details != "" {
- msg = fmt.Sprintf("%s: %s", msg, e.Details)
- }
- if e.Err != nil {
- msg = fmt.Sprintf("%s: %v", msg, e.Err)
- }
- return msg
- }
- // Unwrap returns the underlying error
- func (e *Error) Unwrap() error {
- return e.Err
- }
- // Is reports whether target matches this error
- func (e *Error) Is(target error) bool {
- return errors.Is(e.Err, target)
- }
- // NewError creates a new auth error
- func NewError(op string, err error, details string) *Error {
- return &Error{
- Op: op,
- Err: err,
- Details: details,
- }
- }
- // IsExpiredTokenError returns true if the error indicates an expired token
- func IsExpiredTokenError(err error) bool {
- var e *Error
- return errors.As(err, &e) && errors.Is(e.Err, ErrExpiredToken)
- }
- // IsInvalidTokenError returns true if the error indicates an invalid token
- func IsInvalidTokenError(err error) bool {
- var e *Error
- return errors.As(err, &e) && (errors.Is(e.Err, ErrInvalidToken) ||
- errors.Is(e.Err, ErrInvalidSigningMethod) ||
- errors.Is(e.Err, ErrInvalidClaims))
- }
|