# Story 2.1: JWT Authentication System

## Metadata
- **Story ID**: 2.1
- **Title**: JWT Authentication System
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 6-8 hours
- **Dependencies**: 1.2, 1.5

## Goal
Implement a complete JWT-based authentication system with access tokens, refresh tokens, and secure token management.

## Description
This story implements the complete JWT authentication system including token generation, verification, authentication middleware, and login/refresh endpoints. The system supports short-lived access tokens and long-lived refresh tokens for secure authentication.

## Deliverables

### 1. Authentication Interfaces (`pkg/auth/auth.go`)
- `Authenticator` interface for token generation and verification
- `TokenClaims` struct with user ID, roles, tenant ID, expiration
- Token validation utilities

### 2. JWT Implementation (`internal/auth/jwt_auth.go`)
- Generate short-lived access tokens (15 minutes default)
- Generate long-lived refresh tokens (7 days default)
- Token signature verification using HMAC or RSA
- Token expiration validation
- Claims extraction and validation

### 3. Authentication Middleware (`internal/auth/middleware.go`)
- Extract JWT from `Authorization: Bearer <token>` header
- Verify token validity (signature and expiration)
- Inject authenticated user into request context
- Helper function: `auth.FromContext(ctx) *User`
- Handle authentication errors appropriately

### 4. Authentication Endpoints
- `POST /api/v1/auth/login` - Authenticate user and return tokens
  - Validate email and password
  - Return access + refresh tokens
  - Log login attempts
- `POST /api/v1/auth/refresh` - Refresh access token using refresh token
  - Validate refresh token
  - Issue new access token
  - Optionally rotate refresh token

### 5. gRPC Server (Microservices)
- Expose gRPC server for authentication service
- gRPC service definition in `api/proto/auth.proto`
- gRPC server implementation in `internal/auth/grpc/server.go`
- Service registration in service registry

### 6. Integration
- Integration with DI container
- Use `IdentityServiceClient` for user operations (if Identity service is separate)
- Integration with HTTP server
- Integration with user repository
- Integration with audit logging

## Implementation Steps

1. **Install Dependencies**
   ```bash
   go get github.com/golang-jwt/jwt/v5
   ```

2. **Create Authentication Interfaces**
   - Create `pkg/auth/auth.go`
   - Define Authenticator interface
   - Define TokenClaims struct

3. **Implement JWT Authentication**
   - Create `internal/auth/jwt_auth.go`
   - Implement token generation
   - Implement token verification
   - Handle token expiration

4. **Create Authentication Middleware**
   - Create `internal/auth/middleware.go`
   - Implement token extraction
   - Implement token verification
   - Inject user into context

5. **Create Authentication Endpoints**
   - Create login handler
   - Create refresh handler
   - Add routes to HTTP server

6. **Integrate with DI**
   - Create provider function
   - Register in container

## Acceptance Criteria
- [ ] Users can login and receive access and refresh tokens
- [ ] Access tokens expire after configured duration
- [ ] Refresh tokens can be used to obtain new access tokens
- [ ] Invalid tokens are rejected with appropriate errors
- [ ] Authenticated user is available in request context
- [ ] Login attempts are logged (success and failure)
- [ ] Token secrets are configurable
- [ ] Token claims include user ID, roles, and tenant ID

## Related ADRs
- [ADR-0017: JWT Token Strategy](../../adr/0017-jwt-token-strategy.md)
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)

## Implementation Notes
- Use JWT v5 library
- Support both HMAC and RSA signing
- Token secrets should be configurable
- Consider token blacklisting for logout (future enhancement)
- Refresh tokens should be stored securely (database or cache)

## Testing
```bash
# Test authentication
go test ./internal/auth/...

# Test login endpoint
curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"password"}'

# Test refresh endpoint
curl -X POST http://localhost:8080/api/v1/auth/refresh \
  -H "Authorization: Bearer <refresh_token>"
```

## Files to Create/Modify
- `pkg/auth/auth.go` - Authentication interfaces
- `internal/auth/jwt_auth.go` - JWT implementation
- `internal/auth/middleware.go` - Authentication middleware
- `internal/auth/handler.go` - Authentication handlers
- `internal/di/providers.go` - Add auth provider
- `config/default.yaml` - Add JWT configuration

