auth

package
v0.0.0-...-37e4f78 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrEmailNotVerified = errors.New("email not verified")
View Source
var ErrInvalidCredentials = errors.New("invalid credentials")

Functions

func AuthMiddleware

func AuthMiddleware(service *Service, responseHandler ResponseHandler) gin.HandlerFunc

AuthMiddleware creates a middleware for authentication

func OptionalAuthMiddleware

func OptionalAuthMiddleware(service *Service) gin.HandlerFunc

OptionalAuthMiddleware creates a middleware that attempts to authenticate but doesn't require it

Types

type App

type App struct {
	Config          *Config
	Logger          Logger
	Auth            AuthService
	Token           TokenService
	ResponseHandler ResponseHandler
}

App represents the application context needed by auth handlers

type AuthService

type AuthService interface {
	Login(identifier, password string) (*LoginResponse, error)
	Logout(userID uuid.UUID, refreshToken string) error
	RefreshToken(refreshToken string) (*LoginResponse, error)
	ValidateToken(token string) (*TokenClaims, error)
	MarkEmailVerified(userID uuid.UUID) error
}

AuthService handles authentication operations

type Config

type Config struct {
	JWT struct {
		Secret          string
		AccessTokenTTL  time.Duration
		RefreshTokenTTL time.Duration
	}
	Password struct {
		MinLength  int
		MaxLength  int
		MinDigits  int
		MinSymbols int
	}
}

Config represents authentication configuration

func NewConfigFromAuthConfig

func NewConfigFromAuthConfig(cfg *config.AuthConfig) *Config

NewConfigFromAuthConfig creates an auth.Config from config.AuthConfig

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler handles HTTP requests for auth endpoints

func NewHandler

func NewHandler(service *Service, responseHandler ResponseHandler) *Handler

NewHandler creates a new auth handler instance

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(router *gin.Engine)

RegisterRoutes registers all auth routes

type JWTService

type JWTService struct {
	// contains filtered or unexported fields
}

JWTService implements the TokenService interface using JWT tokens

func (*JWTService) GenerateAccessToken

func (s *JWTService) GenerateAccessToken(user *User) (string, error)

GenerateAccessToken generates a new JWT access token for a user

func (*JWTService) GenerateRefreshToken

func (s *JWTService) GenerateRefreshToken(user *User) (string, error)

GenerateRefreshToken generates a new JWT refresh token for a user

func (*JWTService) ValidateAccessToken

func (s *JWTService) ValidateAccessToken(tokenString string) (*TokenClaims, error)

ValidateAccessToken validates a JWT access token and returns its claims

func (*JWTService) ValidateRefreshToken

func (s *JWTService) ValidateRefreshToken(tokenString string) (*TokenClaims, error)

ValidateRefreshToken validates a JWT refresh token and returns its claims

type Logger

type Logger interface {
	LogInfo(msg string, fields map[string]interface{})
	LogError(err error, msg string) error
}

Logger interface for logging operations

type LoginRequest

type LoginRequest struct {
	// User email address
	Email string `json:"email" binding:"required,email" example:"user@example.com"`
	// User password
	Password string `json:"password" binding:"required,min=8" example:"Pass123!"`
}

LoginRequest represents the login request payload @Description Login request payload

type LoginResponse

type LoginResponse struct {
	// User information
	User User `json:"user"`
	// JWT access token
	AccessToken string `json:"accessToken" example:"eyJhbGciOiJIUzI1NiIs..."`
	// JWT refresh token
	RefreshToken string `json:"refreshToken" example:"eyJhbGciOiJIUzI1NiIs..."`
	// Token type (always "Bearer")
	TokenType string `json:"tokenType" example:"Bearer"`
	// Token expiration time in seconds
	ExpiresIn int `json:"expiresIn" example:"3600"`
}

LoginResponse represents the login response @Description Login response payload

type RefreshToken

type RefreshToken struct {
	ID        uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	UserID    uuid.UUID  `gorm:"type:uuid;not null" json:"userId"`
	Token     string     `gorm:"unique;not null" json:"token"`
	ExpiresAt time.Time  `json:"expiresAt"`
	CreatedAt time.Time  `json:"createdAt"`
	RevokedAt *time.Time `json:"revokedAt,omitempty"`
}

RefreshToken model for storing refresh tokens

type RefreshTokenRepository

type RefreshTokenRepository struct {
	// contains filtered or unexported fields
}

RefreshTokenRepository handles refresh token storage and retrieval

func NewRefreshTokenRepository

func NewRefreshTokenRepository(db *gorm.DB, logger logger.Logger) *RefreshTokenRepository

NewRefreshTokenRepository creates a new refresh token repository

func (*RefreshTokenRepository) Create

func (r *RefreshTokenRepository) Create(userID uuid.UUID, token string, expiresAt time.Time) error

Create stores a new refresh token

func (*RefreshTokenRepository) DeleteExpired

func (r *RefreshTokenRepository) DeleteExpired() error

DeleteExpired deletes all expired refresh tokens

func (*RefreshTokenRepository) GetByToken

func (r *RefreshTokenRepository) GetByToken(token string) (*RefreshToken, error)

GetByToken retrieves a refresh token by its token string

func (*RefreshTokenRepository) RevokeAllUserTokens

func (r *RefreshTokenRepository) RevokeAllUserTokens(userID uuid.UUID) error

RevokeAllUserTokens revokes all refresh tokens for a user

func (*RefreshTokenRepository) RevokeByToken

func (r *RefreshTokenRepository) RevokeByToken(token string) error

RevokeByToken revokes a refresh token

type RefreshTokenRequest

type RefreshTokenRequest struct {
	// Valid refresh token
	RefreshToken string `json:"refreshToken" binding:"required" example:"eyJhbGciOiJIUzI1NiIs..."`
}

RefreshTokenRequest represents the refresh token request payload @Description Refresh token request payload

type RefreshTokenService

type RefreshTokenService interface {
	Create(userID uuid.UUID, token string, expiresAt time.Time) error
	GetByToken(token string) (*RefreshToken, error)
	RevokeByToken(token string) error
	RevokeAllUserTokens(userID uuid.UUID) error
	DeleteExpired() error
}

RefreshTokenService handles refresh token operations

type RegisterRequest

type RegisterRequest struct {
	// Unique username
	Username string `json:"username" binding:"required" example:"johndoe"`
	// User email address
	Email string `json:"email" binding:"required,email" example:"user@example.com"`
	// User password (min 8 characters)
	Password string `json:"password" binding:"required,min=6" example:"Pass123!"`
	// User's full name
	Name string `json:"name" example:"John Doe"`
}

RegisterRequest represents the registration request payload @Description Registration request payload

type ResponseHandler

type ResponseHandler interface {
	SuccessResponse(c *gin.Context, data interface{}, message string)
	ErrorResponse(c *gin.Context, status int, code, message string, err error)
	ValidationErrorResponse(c *gin.Context, field, message string)
	UnauthorizedResponse(c *gin.Context, message string)
	ForbiddenResponse(c *gin.Context, message string)
	NotFoundResponse(c *gin.Context, message string)
	InternalErrorResponse(c *gin.Context, message string, err error)
}

ResponseHandler handles HTTP responses

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service handles authentication-related business logic

func NewService

func NewService(db *gorm.DB, ts TokenService, rt RefreshTokenService, config *Config, logger logger.Logger) *Service

NewService creates a new auth service instance

func (*Service) Login

func (s *Service) Login(identifier, password string) (*LoginResponse, error)

Login handles user authentication

func (*Service) Logout

func (s *Service) Logout(userID uuid.UUID, refreshToken string) error

Logout invalidates the provided refresh token and ends the session for the user.

func (*Service) MarkEmailVerified

func (s *Service) MarkEmailVerified(userID uuid.UUID) error

MarkEmailVerified marks a user's email as verified

func (*Service) RefreshToken

func (s *Service) RefreshToken(refreshToken string) (*LoginResponse, error)

RefreshToken generates a new access token using the provided refresh token.

func (*Service) Register

func (s *Service) Register(req RegisterRequest) (*User, error)

func (*Service) ValidateToken

func (s *Service) ValidateToken(token string) (*TokenClaims, error)

ValidateToken validates the provided token and returns its claims if valid.

type TokenClaims

type TokenClaims struct {
	// User ID
	UserID string `json:"userId" example:"550e8400-e29b-41d4-a716-446655440000"`
	// User email
	Email string `json:"email" example:"user@example.com"`
	jwt.RegisteredClaims
}

TokenClaims represents the JWT claims @Description JWT claims structure

type TokenService

type TokenService interface {
	GenerateAccessToken(user *User) (string, error)
	GenerateRefreshToken(user *User) (string, error)
	ValidateAccessToken(token string) (*TokenClaims, error)
	ValidateRefreshToken(token string) (*TokenClaims, error)
}

TokenService handles JWT operations

func NewJWTService

func NewJWTService(config *Config) TokenService

NewJWTService creates a new JWT token service

type User

type User struct {
	// Unique user ID
	ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id" example:"550e8400-e29b-41d4-a716-446655440000"`
	// Unique username
	Username string `gorm:"unique;not null" json:"username" example:"johndoe"`
	// User email address
	Email string `gorm:"unique;not null" json:"email" example:"user@example.com"`
	// Password hash (not exposed in JSON)
	Password string `gorm:"not null" json:"-"`
	// User's full name
	Name string `json:"name" example:"John Doe"`
	// Whether email is verified
	EmailVerified bool `gorm:"default:false" json:"emailVerified" example:"true"`
	// Last login timestamp
	LastLoginAt time.Time `json:"lastLoginAt,omitempty"`
	// Whether account is active
	Active bool `gorm:"default:true" json:"active" example:"true"`
	// Account creation timestamp
	CreatedAt time.Time `json:"createdAt"`
	// Last update timestamp
	UpdatedAt time.Time `json:"updatedAt"`
	// Refresh tokens (not exposed in JSON)
	RefreshTokens []RefreshToken `gorm:"foreignKey:UserID" json:"-"`
}

User model definition with authentication fields @Description User model

func (*User) BeforeCreate

func (u *User) BeforeCreate(tx *gorm.DB) error

BeforeCreate hook for User model

func (*User) BeforeUpdate

func (u *User) BeforeUpdate(tx *gorm.DB) error

BeforeUpdate hook for User model

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL