# Auth Specification

> Generated by openlore v1.0.0 on 2025-06-15
> Source files: src/auth/auth-service.ts, src/auth/auth-middleware.ts, src/auth/auth-routes.ts

## Purpose

Handles user authentication (login, registration, JWT management) and request-level
authorization via middleware.

## Requirements

### Requirement: UserLogin

The system SHALL authenticate users by email and password, returning a signed JWT on success.

#### Scenario: SuccessfulLogin
- **GIVEN** a registered user with email "alice@test.com" and a valid password
- **WHEN** POST /api/auth/login is called with those credentials
- **THEN** the system returns a JWT token, expiry time, and userId with status 200

#### Scenario: InvalidCredentials
- **GIVEN** an incorrect password
- **WHEN** POST /api/auth/login is called
- **THEN** the system returns status 401 with error "Invalid credentials"

#### Scenario: MissingFields
- **GIVEN** a request body without email or password
- **WHEN** POST /api/auth/login is called
- **THEN** the system returns status 400 with error "Email and password required"

### Requirement: UserRegistration

The system SHALL register new users with email, password, and name, hashing the password with bcrypt (cost factor 12).

#### Scenario: SuccessfulRegistration
- **GIVEN** a unique email "bob@test.com"
- **WHEN** POST /api/auth/register is called
- **THEN** the system creates the user and returns a JWT with status 201

#### Scenario: DuplicateEmail
- **GIVEN** an email that already exists
- **WHEN** POST /api/auth/register is called
- **THEN** the system returns status 409 with error "Email already registered"

### Requirement: JWTTokenManagement

The system SHALL sign tokens with a configurable secret (JWT_SECRET env var, defaulting to "dev-secret") and 24-hour expiry.

### Requirement: RequestAuthorization

The system SHALL protect routes via `requireAuth` middleware that validates Bearer tokens and injects `userId` and `userRole` into the request.

#### Scenario: MissingToken
- **GIVEN** a request without an Authorization header
- **WHEN** the request reaches a protected route
- **THEN** the system returns status 401 with error "Missing authorization header"

#### Scenario: ExpiredToken
- **GIVEN** a request with an expired JWT
- **WHEN** the request reaches a protected route
- **THEN** the system returns status 401 with error "Invalid or expired token"

### Requirement: RoleBasedAccess

The system SHALL support role-based access control via `requireRole` middleware that checks `userRole` against a required role.

## Technical Notes

- **Implementation**: `src/auth/auth-service.ts`, `src/auth/auth-middleware.ts`, `src/auth/auth-routes.ts`
- **Dependencies**: jsonwebtoken, bcrypt
