tercul-backend/internal/app/auth/commands.go
google-labs-jules[bot] 781b313bf1 feat: Complete all pending tasks from TASKS.md
This commit addresses all the high-priority tasks outlined in the TASKS.md file, significantly improving the application's observability, completing key features, and refactoring critical parts of the codebase.

### Observability

- **Centralized Logging:** Implemented a new structured, context-aware logging system using `zerolog`. A new logging middleware injects request-specific information (request ID, user ID, trace ID) into the logger, and all application logging has been refactored to use this new system.
- **Prometheus Metrics:** Added Prometheus metrics for database query performance by creating a GORM plugin that automatically records query latency and totals.
- **OpenTelemetry Tracing:** Fully instrumented all application services in `internal/app` and data repositories in `internal/data/sql` with OpenTelemetry tracing, providing deep visibility into application performance.

### Features

- **Analytics:** Implemented like, comment, and bookmark counting. The respective command handlers now call the analytics service to increment counters when these actions are performed.
- **Enrichment Tool:** Built a new, extensible `enrich` command-line tool to fetch data from external sources. The initial implementation enriches author data using the Open Library API.

### Refactoring & Fixes

- **Decoupled Testing:** Refactored the testing utilities in `internal/testutil` to be database-agnostic, promoting the use of mock-based unit tests and improving test speed and reliability.
- **Build Fixes:** Resolved numerous build errors, including a critical import cycle between the logging, observability, and authentication packages.
- **Search Service:** Fixed the search service integration by implementing the `GetWorkContent` method in the localization service, allowing the search indexer to correctly fetch and index work content.
2025-10-05 05:26:27 +00:00

203 lines
6.0 KiB
Go

package auth
import (
"context"
"errors"
"fmt"
"strings"
"tercul/internal/domain"
"tercul/internal/platform/auth"
"tercul/internal/platform/log"
"time"
"github.com/asaskevich/govalidator"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)
var (
ErrInvalidCredentials = errors.New("invalid credentials")
ErrUserAlreadyExists = errors.New("user already exists")
ErrInvalidInput = errors.New("invalid input")
)
// LoginInput represents login request data
type LoginInput struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=6"`
}
// RegisterInput represents registration request data
type RegisterInput struct {
Username string `json:"username" validate:"required,min=3,max=50"`
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=6"`
FirstName string `json:"first_name" validate:"required,min=1,max=50"`
LastName string `json:"last_name" validate:"required,min=1,max=50"`
}
// AuthResponse represents authentication response
type AuthResponse struct {
Token string `json:"token"`
User *domain.User `json:"user"`
ExpiresAt time.Time `json:"expires_at"`
}
// AuthCommands contains the command handlers for authentication.
type AuthCommands struct {
userRepo domain.UserRepository
jwtManager auth.JWTManagement
tracer trace.Tracer
}
// NewAuthCommands creates a new AuthCommands handler.
func NewAuthCommands(userRepo domain.UserRepository, jwtManager auth.JWTManagement) *AuthCommands {
return &AuthCommands{
userRepo: userRepo,
jwtManager: jwtManager,
tracer: otel.Tracer("auth.commands"),
}
}
// Login authenticates a user and returns a JWT token
func (c *AuthCommands) Login(ctx context.Context, input LoginInput) (*AuthResponse, error) {
ctx, span := c.tracer.Start(ctx, "Login")
defer span.End()
logger := log.FromContext(ctx).With("email", input.Email)
if err := validateLoginInput(input); err != nil {
logger.Warn("Login validation failed")
return nil, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
email := strings.TrimSpace(input.Email)
logger.Debug("Attempting to log in user")
user, err := c.userRepo.FindByEmail(ctx, email)
if err != nil {
logger.Warn("Login failed - user not found")
return nil, ErrInvalidCredentials
}
logger = logger.With("user_id", user.ID)
if !user.Active {
logger.Warn("Login failed - user inactive")
return nil, ErrInvalidCredentials
}
if !user.CheckPassword(input.Password) {
logger.Warn("Login failed - invalid password")
return nil, ErrInvalidCredentials
}
token, err := c.jwtManager.GenerateToken(user)
if err != nil {
logger.Error(err, "Failed to generate JWT token")
return nil, fmt.Errorf("failed to generate token: %w", err)
}
now := time.Now()
user.LastLoginAt = &now
if err := c.userRepo.Update(ctx, user); err != nil {
logger.Error(err, "Failed to update last login time")
// Do not fail the login if this update fails
}
logger.Info("User logged in successfully")
return &AuthResponse{
Token: token,
User: user,
ExpiresAt: time.Now().Add(24 * time.Hour), // This should be configurable
}, nil
}
// Register creates a new user account
func (c *AuthCommands) Register(ctx context.Context, input RegisterInput) (*AuthResponse, error) {
ctx, span := c.tracer.Start(ctx, "Register")
defer span.End()
logger := log.FromContext(ctx).With("email", input.Email).With("username", input.Username)
if err := validateRegisterInput(input); err != nil {
logger.Warn("Registration validation failed")
return nil, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
email := strings.TrimSpace(input.Email)
username := strings.TrimSpace(input.Username)
logger.Debug("Attempting to register new user")
existingUser, _ := c.userRepo.FindByEmail(ctx, email)
if existingUser != nil {
logger.Warn("Registration failed - email already exists")
return nil, ErrUserAlreadyExists
}
existingUser, _ = c.userRepo.FindByUsername(ctx, username)
if existingUser != nil {
logger.Warn("Registration failed - username already exists")
return nil, ErrUserAlreadyExists
}
user := &domain.User{
Username: username,
Email: email,
Password: input.Password,
FirstName: strings.TrimSpace(input.FirstName),
LastName: strings.TrimSpace(input.LastName),
DisplayName: fmt.Sprintf("%s %s", strings.TrimSpace(input.FirstName), strings.TrimSpace(input.LastName)),
Role: domain.UserRoleReader,
Active: true,
Verified: false, // Should be false until email verification
}
if err := c.userRepo.Create(ctx, user); err != nil {
logger.Error(err, "Failed to create user")
return nil, fmt.Errorf("failed to create user: %w", err)
}
logger = logger.With("user_id", user.ID)
token, err := c.jwtManager.GenerateToken(user)
if err != nil {
logger.Error(err, "Failed to generate JWT token for new user")
return nil, fmt.Errorf("failed to generate token: %w", err)
}
logger.Info("User registered successfully")
return &AuthResponse{
Token: token,
User: user,
ExpiresAt: time.Now().Add(24 * time.Hour), // This should be configurable
}, nil
}
func validateLoginInput(input LoginInput) error {
if input.Email == "" {
return errors.New("email is required")
}
if !govalidator.IsEmail(strings.TrimSpace(input.Email)) {
return errors.New("invalid email format")
}
if len(input.Password) < 6 {
return errors.New("password must be at least 6 characters")
}
return nil
}
func validateRegisterInput(input RegisterInput) error {
if !govalidator.IsEmail(strings.TrimSpace(input.Email)) {
return errors.New("invalid email format")
}
if len(input.Password) < 6 {
return errors.New("password must be at least 6 characters")
}
username := strings.TrimSpace(input.Username)
if len(username) < 3 || len(username) > 50 {
return errors.New("username must be between 3 and 50 characters")
}
if !govalidator.Matches(username, `^[a-zA-Z0-9_-]+$`) {
return errors.New("username can only contain letters, numbers, underscores, and hyphens")
}
return nil
}