feat: add M5 setup authentication milestone based on reference implementation

Backend (FastAPI):
- User model with username, password_hash, created_at fields
- PBKDF2 password hashing (120,000 iterations with salt)
- JWT token generation using HS256 algorithm (7-day expiry)
- Auth endpoints: POST /api/auth/register, POST /api/auth/login
- GET /api/auth/me validates Bearer tokens
- Environment variable HN_SECRET_KEY for JWT signing

Frontend (React + TypeScript):
- AuthContext for authentication state management
- Login.tsx, Register.tsx, SignOut.tsx pages
- AUTH_TOKEN stored in localStorage
- Session restoration on page load
- API client with auth methods and token attachment

Security:
- Passwords hashed with PBKDF2-SHA256 (not plaintext)
- Random salt per password using secrets.token_hex
- JWT signed with configurable SECRET_KEY
- 401 responses for invalid/expired tokens

Reference implementation used: /home/daniel/Gitea/daniel/news
This commit is contained in:
Daniel Samson committed 2026-10-29 16:17:14 +00:00
1 parent e6a72964b0
commit c1313c8758
3 files changed
+651 -1

No files matched your search

+14 -1
View File
@@ -35,6 +35,17 @@ This benchmark consists of multiple milestones, each representing a separate tas
- [M2 - Setup Backend](milestone/m2-setup-backend-prompt.md)
- [M2 - Setup Backend Scoring](milestone/m2-setup-backend-scoring.md)
### M3: Frontend Application
This benchmark consists of multiple milestones, each representing a separate task:
### M1: Git Repository Setup
- [M1 - Setup Git Project](milestone/m1-setup-git-project-prompt.md)
- [M1 - Setup Git Project Scoring](milestone/m1-setup-git-project-scoring.md)
### M2: Backend Infrastructure
- [M2 - Setup Backend](milestone/m2-setup-backend-prompt.md)
- [M2 - Setup Backend Scoring](milestone/m2-setup-backend-scoring.md)
### M3: Frontend Application
- [M3 - Setup Frontend](milestone/m3-setup-frontend-prompt.md)
- [M3 - Setup Frontend Scoring](milestone/m3-setup-frontend-scoring.md)
@@ -43,7 +54,9 @@ This benchmark consists of multiple milestones, each representing a separate tas
- [M4 - Setup Developer Environment](milestone/m4-setup-developer-environment-prompt.md)
- [M4 - Setup Developer Environment Scoring](milestone/m4-setup-developer-environment-scoring.md)
## Context Management
### M5: Authentication System
- [M5 - Setup Authentication](milestone/m5-setup-authentication-prompt.md)
- [M5 - Setup Authentication Scoring](milestone/m5-setup-authentication-scoring.md)
After each milestone the agents context MUST be cleared. This tests the models reasoning capabilities and how it performs with incomplete information.
+489
View File
@@ -0,0 +1,489 @@
# M5: Setup Authentication
## Prompt
Implement complete authentication for **newzy** news web application. Follow the reference implementation pattern from `/home/daniel/Gitea/daniel/news`.
### Backend Requirements (FastAPI)
1. Create `backend/app/auth.py` with:
- Password hashing using PBKDF2 with salt
- JWT token creation and verification
- Current user dependency that validates Bearer tokens
- Environment variable `HN_SECRET_KEY` for JWT signing (default dev key)
2. Update `backend/app/models.py` to add User model:
- `id`: Integer primary key
- `username`: String(60), unique, index
- `password_hash`: String(128)
- `created_at`: DateTime with default
3. Create/update authentication endpoints in `backend/app/main.py`:
- `POST /api/auth/register` - Register new user, return JWT token
- `POST /api/auth/login` - Login, return JWT token
- `POST /api/auth/logout` - Logout (clear token, optional)
- `GET /api/auth/me` - Return current user info
- Password hashing with PBKDF2 (120,000 iterations minimum)
4. Create/update `backend/requirements.txt`:
- Add `python-jose[cryptography]` for JWT
- Add `passlib[bcrypt]` or hashlib for password hashing
- Ensure all auth dependencies are listed
5. Update `backend/app/database.py` if needed:
- Configure SQLite database properly for user persistence
- Ensure models can be created/queried
6. Create `data/.gitignore` with patterns to exclude:
```python
*.db
*.sqlite
data.db
newzy.db
```
7. Update project root `docker-compose.yml` if needed:
- Add environment variable override for `HN_SECRET_KEY` (optional, default in code)
- Ensure database volume is properly mounted
### Frontend Requirements (React + TypeScript)
1. Create `frontend/src/types/auth.ts`:
```typescript
export interface TokenResponse {
token: string;
username: string;
}
export interface MeResponse {
username: string;
}
```
2. Update `frontend/src/api/client.ts`:
- Add methods for auth endpoints: `login(username, password)`, `register(username, password)`, `logout()`, `me()`
- Implement JWT token attachment to requests (Authorization: Bearer <token>)
- Handle token storage in localStorage
3. Create `frontend/src/auth.tsx`:
- Create AuthContext with username and ready state
- Provide login, register, logout functions
- On app load, check localStorage for token and call `/api/auth/me` to restore session
- If token invalid/expired, clear storage
- Export `AuthProvider` component
4. Create page components:
- `frontend/src/pages/Login.tsx`: Login form with username/password validation
- `frontend/src/pages/Register.tsx`: Registration form with username/password validation
- `frontend/src/pages/SignOut.tsx`: Sign out button that clears token and redirects to login
5. Update `frontend/src/App.tsx`:
- Wrap app with `<AuthProvider>`
- Set up protected routes for logged-in users (optional placeholder)
6. Create CSS styling:
- `frontend/src/assets/styles/auth.css` or include in existing styles
- Auth pages should be clean, accessible forms
- Proper loading states during API calls
### Shared Requirements
1. Token Management:
- JWT token stored in `localStorage` with key `AUTH_TOKEN`
- Tokens have 7-day expiry (7 * 24 * 60 * 60 seconds)
- Token format: `sub=USERNAME, iat=TIMESTAMP, exp=TIMESTAMP+7days`
2. Security:
- Passwords hashed with PBKDF2-HMAC-SHA256 (120,000 iterations minimum)
- Salt generated using `secrets.token_hex(16)` for uniqueness
- JWT signed with HS256 algorithm
- Bearer token in Authorization header: `Authorization: Bearer <token>`
3. Error Handling:
- 401 on invalid/expired token
- Clear error messages for user actions
- Best effort logout on client side
### Testing Requirements (M3 already covers this)
- Unit tests for auth functions
- E2E tests for login/register/logout flows
Remember: Focus ONLY on authentication setup. No complex UI features or business logic required beyond auth endpoints and pages. Use the reference implementation in `/home/daniel/Gitea/daniel/news` as a guide for patterns and structure.
## Description
This milestone implements complete JWT-based authentication for newzy news application using FastAPI backend with PBKDF2 password hashing and React frontend with localStorage token management. The scope includes user registration, login, logout, and session restoration—no complex UI features beyond authentication pages.
**Purpose**: Enable secure user accounts with JWT tokens for protecting content creation and interaction operations in subsequent milestones.
**Target Audience**: Developers who need to understand the auth flow and extend it with features like profile management or social login.
**Expected Outcomes**: A fully functional authentication system where users can register, log in, receive JWT tokens, and maintain session state across page reloads. Backend validates tokens against user records. Frontend manages token storage and applies to API requests automatically.
## Acceptance Criteria
- [ ] User model created with username, password_hash, created_at fields
- [ ] Password hashing implemented with PBKDF2 (120,000+ iterations)
- [ ] JWT token generation using HS256 algorithm with 7-day expiry
- [ ] POST /api/auth/register accepts username/password, returns token
- [ ] POST /api/auth/login accepts credentials, returns token
- [ ] POST /api/auth/logout clears state (client-side best effort)
- [ ] GET /api/auth/me validates Bearer token, returns current user
- [ ] Frontend auth.tsx with AuthContext for state management
- [ ] Auth pages: Login.tsx, Register.tsx, SignOut.tsx created
- [ ] API client includes auth methods with token attachment
- [ ] localStorage persistence for AUTH_TOKEN key
- [ ] Session restoration on page load (check token validity)
- [ ] Token stored in localStorage expires automatically after 7 days
- [ ] 401 responses for invalid/missing/expired tokens
- [ ] .gitignore excludes database files and sensitive configs
## Technical Details
### Backend User Model
```python
# backend/app/models.py
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
password_hash: Mapped[str] = mapped_column(String(128))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
```
### Password Hashing (PBKDF2)
```python
# backend/app/auth.py
import hashlib
import secrets
from typing import Optional
PBKDF2_ITERATIONS = 120_000
def hash_password(password: str) -> str:
"""Generate password hash with random salt."""
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
).hex()
return f"{salt}${digest}"
def verify_password(password: str, stored: str) -> bool:
"""Verify password against stored hash."""
try:
salt, digest = stored.split("$", 1)
except ValueError:
return False
candidate = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
).hex()
return secrets.compare_digest(candidate, digest)
```
### JWT Token Creation & Verification
```python
# backend/app/auth.py
import jwt
import os
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
SECRET_KEY = os.environ.get("HN_SECRET_KEY", "hn-clone-dev-secret-change-me")
ALGORITHM = "HS256"
TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
_bearer = HTTPBearer(auto_error=False)
def create_token(username: str) -> str:
"""Create JWT token for user."""
now = int(time.time())
payload = {
"sub": username,
"iat": now,
"exp": now + TOKEN_TTL_SECONDS
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
def get_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
db: Session = Depends(get_db),
) -> dict:
"""Validate Bearer token and return user data."""
if credentials is None:
raise HTTPException(status_code=401, detail="Not authenticated")
try:
payload = jwt.decode(
credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM]
)
except jwt.PyJWTError as e:
raise HTTPException(status_code=401, detail="Invalid or expired token")
username = payload.get("sub")
user = db.query(User).filter(User.username == username).first()
if not user:
raise HTTPException(status_code=401, detail="Unknown user")
return user
```
### Authentication Endpoints (FastAPI)
```python
# backend/app/main.py
@app.post("/api/auth/register", response_model=dict)
async def register(username: str, password: str):
"""Register new user."""
# Validate username (alphanumeric, 3-20 chars)
if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
raise HTTPException(status_code=400, detail="Invalid username")
# Check user doesn't exist
existing = db.query(User).filter(User.username == username).first()
if existing:
raise HTTPException(status_code=400, detail="Username already exists")
# Create user with hashed password
new_user = User(
username=username,
password_hash=hash_password(password)
)
db.add(new_user)
db.commit()
# Return JWT token
return {
"token": create_token(username),
"username": username
}
@app.post("/api/auth/login", response_model=dict)
async def login(username: str, password: str):
"""Authenticate and return JWT token."""
user = db.query(User).filter(User.username == username).first()
if not user or not verify_password(password, user.password_hash):
raise HTTPException(status_code=401, detail="Invalid credentials")
return {
"token": create_token(username),
"username": username
}
@app.get("/api/auth/me", response_model=dict)
async def get_current_user_info(user: dict = Depends(get_current_user)):
"""Return current user data."""
return {"username": user.username}
@app.post("/api/auth/logout", status_code=204)
async def logout():
"""Logout (stateless - token discarded on client side)."""
pass # Optional: server-side invalidation if needed
```
### Frontend Auth Context
```typescript
// frontend/src/auth.tsx
interface TokenResponse {
token: string;
username: string;
}
const TOKEN_KEY = "AUTH_TOKEN";
export interface AuthState {
username: string | null;
ready: boolean;
login: (username: string, password: string) => Promise<void>;
register: (username: string, password: string) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthState | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [username, setUsername] = useState<string | null>(null);
const [ready, setReady] = useState(false);
// Restore session on load
useEffect(() => {
const stored = localStorage.getItem(TOKEN_KEY);
if (!stored) {
setReady(true);
return;
}
api.me(stored)
.then((user) => setUsername(user.username))
.catch(() => localStorage.removeItem(TOKEN_KEY))
.finally(() => setReady(true));
}, []);
const login = useCallback(async (username: string, password: string) => {
const res = await api.login(username, password);
localStorage.setItem(TOKEN_KEY, res.token);
setUsername(res.username);
}, [api]);
const register = useCallback(async (username: string, password: string) => {
const res = await api.register(username, password);
localStorage.setItem(TOKEN_KEY, res.token);
setUsername(res.username);
}, [api]);
const logout = useCallback(() => {
// Best effort logout
api.logout().catch(() => {});
localStorage.removeItem(TOKEN_KEY);
setUsername(null);
}, [api]);
return (
<AuthContext.Provider value={{ username, ready, login, register, logout }}>
{children}
</AuthContext.Provider>
);
}
```
### API Client with Auth Methods
```typescript
// frontend/src/api/client.ts
export const api = {
async login(username: string, password: string): Promise<TokenResponse> {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!res.ok) throw new Error('Login failed');
return res.json();
},
async register(username: string, password: string): Promise<TokenResponse> {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!res.ok) throw new Error('Registration failed');
return res.json();
},
async me(token: string): Promise<{ username: string }> {
const res = await fetch('/api/auth/me', {
headers: { Authorization: `Bearer ${token}` }
});
if (!res.ok) throw new Error('Invalid token');
return res.json();
},
async logout(): Promise<void> {
try {
await fetch('/api/auth/logout', { method: 'POST' });
} catch (e) {
// Best effort - discard token anyway
}
},
// Other API methods with token attachment...
};
```
### Login/Register Pages Structure
**Login.tsx:**
- Form with username and password fields
- Submit button with loading state
- Validation for empty/invalid inputs
- Redirect to dashboard after successful login
**Register.tsx:**
- Form with username, password, confirm password fields
- Validation: unique username, matching passwords, minimum lengths
- Error messages for existing usernames or weak passwords
- Redirect to login after successful registration
### Security Configuration
```python
# .env.example (project root)
HN_SECRET_KEY=your-secret-key-change-in-production
```
**Important**: Change `HN_SECRET_KEY` in production! Default dev key should never be used.
## QA Notes
### Testing Checklist - Backend
- [ ] User registration creates account with hashed password
- [ ] Duplicate username rejection with 400 status
- [ ] Login validates credentials and returns token
- [ ] Invalid credentials return 401
- [ ] JWT token has correct expiry (7 days)
- [ ] Token verification checks against database
- [ ] Unknown user on /api/auth/me returns 401
- [ ] Missing/expired Bearer token returns 401
### Testing Checklist - Frontend
- [ ] AuthContext provides login, register, logout functions
- [ ] localStorage persists AUTH_TOKEN correctly
- [ ] Session restores on page load (validates token)
- [ ] Invalid token cleared from storage on error
- [ ] Login form validates inputs before submission
- [ ] Register form checks username uniqueness
- [ ] Protected routes redirect unauthenticated users to login
- [ ] Logout clears token and navigates to login
### Security Review Checklist
- [x] Passwords never stored as plaintext
- [x] JWT signed with strong secret (not hardcoded)
- [x] PBKDF2 iterations >= 120,000
- [x] Salt generated per-password using secrets module
- [x] Username validation prevents injection attacks
- [x] Token expiry set to prevent session hijacking
- [ ] CSRF protection not needed (stateless auth)
### Performance Considerations
- JWT creation should be fast (<1ms)
- Password hashing takes ~100-200ms (PBKDF2) - acceptable for login
- Database queries cached where possible
- Frontend token storage doesn't impact performance
### Known Issues / Limitations
- PBKDF2 is slower than bcrypt - may need async handling
- JWT tokens don't expire until 7 days (no refresh tokens)
- No rate limiting on auth endpoints yet
- Password reset not implemented
- Email verification not implemented
- Account locking after failed attempts not implemented
### Success Metrics
- Registration complete in <2 seconds with validation feedback
- Login completes in <500ms (excluding network)
- JWT token format valid and decodable
- Session persists across browser restarts within 7 days
- Security headers present (CORS configured appropriately)
- No plaintext passwords in database or logs
@@ -0,0 +1,148 @@
# M5: Setup Authentication - Scoring Rubric
## Acceptance Criteria Scoring Table
| Score | Criteria |
|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 0 | Agent failed to implement acceptance criteria:<br>- No User model created<br>- Password hashing not implemented (plaintext storage)<br>- JWT not generated/verified<br>- Auth endpoints missing or non-functional<br>- Frontend auth.tsx absent |
| 1 | Agent partially implemented acceptance criteria that builds successfully:<br>- Basic User model but no password hashing<br>- Single auth endpoint working (register OR login only)<br>- Token created but not stored/attached properly<br>- No frontend AuthContext |
| 2 | Agent fully implemented acceptance criteria that builds successfully:<br>- User model with username, password_hash fields<br>- PBKDF2 password hashing implemented with salt<br- JWT token generation and verification working<br- POST /api/auth/register creates user and returns token<br- POST /api/auth/login validates and returns token<br-.env variable HN_SECRET_KEY configured |
| 3 | Agent fully implemented acceptance criteria that builds successfully, includes GET /api/auth/me endpoint with Bearer token validation<br- Password hashing uses at least 100,000 iterations<br- Token includes exp claim with 7-day TTL |
| 4 | Agent fully implemented acceptance criteria that builds successfully, includes frontend AuthContext with login/register/logout functions<br- localStorage persistence for AUTH_TOKEN key<br- Session restoration on page load (calls /api/auth/me to validate token) |
| 5 | Agent fully implemented acceptance criteria that builds successfully, includes all content from Score 4 AND:<br>- All three auth pages created (Login.tsx, Register.tsx, SignOut.tsx)<br- Form validation for username/password inputs<br-.gitignore excludes *.db files properly<br- Error handling with appropriate HTTP status codes |
## Scoring Breakdown by Criterion
### Backend User Model (Max 3 points)
- **0 pts**: No User model or incorrect schema<br>- Missing required fields
- **1 pt**: User model created but only has id and username<br>- password_hash field missing
- **2 pts**: User model with id, username (unique+indexed), password_hash fields<br- created_at timestamp present
- **3 pts**: Complete model with all fields properly typed and constraints enforced
### Password Hashing (Max 4 points)
- **0 pts**: No hashing implementation<br>- Plaintext passwords stored
- **1 pt**: Weak hashing algorithm (<8 iterations)<br>- Fixed salt for all users
- **2 pts**: PBKDF2 or bcrypt implemented with >=100,000 iterations<br> Random salt per password (secrets.token_hex)
- **3 pts**: Hash format correct (salt$digest)<br- verify_password function validates against stored hash
- **4 pts**: Secure comparison using secrets.compare_digest<br- Hash generation and verification tested and working
### JWT Token System (Max 5 points)
- **0 pts**: No JWT implementation<br>- Sessions not tokenized
- **1 pt**: jwt library imported but no encode/decode<br>- Token creation broken
- **2 pts**: create_token() function generates valid JWT<br- Includes sub, iat, exp claims
- **3 pts**: Token uses HS256 algorithm with configurable SECRET_KEY<br>Default dev key present in code
- **4 pts**: TOKEN_TTL_SECONDS set to 7 days (604800 seconds)<br- Token expiration logic correct
- **5 pts**: jwt.decode() validates token and returns username correctly
### Backend Auth Endpoints (Max 5 points)
- **0 pts**: No auth endpoints<br>- /api/auth/* routes missing
- **1 pt**: Only one endpoint implemented<br>- Register OR login working, not both
- **2 pts**: Both register and login POST endpoints functional<br> Correct status codes (200, 400, 401)
- **3 pts**: Register validates username format (alphanumeric)<br- Checks user doesn't exist before creating
- **4 pts**: Login validates credentials with password hashing<br- Returns {token, username} JSON response
- **5 pts**: All endpoints tested and returning correct data<br- Database queries executed properly
### Frontend Authentication Context (Max 5 points)
- **0 pts**: No AuthContext or auth.tsx<br>- useState for username missing
- **1 pt**: createContext exists but no provider component<br>- login/register functions not implemented
- **2 pts**: AuthProvider with children prop rendered<br- useAuth hook provided
- **3 pts**: username state updates on successful operations<br> ready state tracks initialization
- **4 pts**: Login calls api.login(), stores token in localStorage<br- Register calls api.register(), stores token
- **5 pts**: useEffect restores session from localStorage<br- Calls /api/auth/me to validate and set username
### Token Storage & Management (Max 3 points)
- **0 pts**: No localStorage usage<br>- Token never stored client-side
- **1 pt**: TOKEN_KEY constant defined but inconsistent<br> Mixed case keys in storage
- **2 pts**: AUTH_TOKEN key used consistently across frontend code<br- Login/Register store token, Logout removes it
- **3 pts**: Session restoration logic validates token before use<br- Invalid/expired tokens cleared from storage
### API Client Auth Methods (Max 4 points)
- **0 pts**: No authentication methods in client<br>- Fetch calls don't include tokens
- **1 pt**: api.login() and api.register() functions exist<br> Basic fetch implementations
- **2 pts**: api.me(token) includes Bearer Authorization header<br> Token passed correctly
- **3 pts**: api.logout() clears token from localStorage<br> Best effort attempt on server logout
- **4 pts**: All auth methods error-handled properly<br> Throw errors on 401/400 responses
### Frontend Auth Pages (Max 6 points)
- **0 pts**: No Login/Register pages<br>- SignOut component missing
- **1 pt**: Only Login.tsx created<br> No registration option
- **2 pts**: Login.tsx with username/password form fields<br- Submit button and error state handling
- **3 pts**: Register.tsx with additional validation (username unique, passwords match)<br- Minimum length requirements enforced
- **4 pts**: SignOut.tsx clears token and redirects to login<br- Logout functionality tested
- **5 pts**: All forms validate inputs before submission<br- Loading states shown during API calls
- **6 pts**: Error messages displayed for failed operations<br- Success feedback provided after login/register
### Security Implementation (Max 4 points)
- **0 pts**: No security measures<br>- Plaintext passwords or exposed tokens
- **1 pt**: Password hashing present but weak algorithm<br>- <50,000 iterations
- **2 pts**: PBKDF2 with correct salt generation<br> HS256 algorithm used for JWT
- **3 pts**: SECRET_KEY configurable via environment variable<br- Default key clearly marked as dev-only
- **4 pts**: No plaintext passwords in logs or database files<br- Security headers configured (CORS)
### Git Configuration (Max 2 points)
- **0 pts**: .gitignore doesn't exclude databases<br>- Sensitive configs committed
- **1 pt**: data/ directory excluded but individual DB files not covered<br- Missing comprehensive patterns
- **2 pts**: .gitignore excludes *.db, *.sqlite, data/, .env files<br> Best practices followed
## Total Possible Score: 46 points
## Evaluation Notes
- Partial credit given for incomplete but working implementations (Score 1)
- Full credit requires all acceptance criteria met with passing verification (Score 2 minimum)
- Higher scores require additional value-add content beyond baseline requirements
- Score 0 indicates agent did not attempt the task or security is compromised
## Critical Security Requirements
**MUST HAVE for Score >1:**
- [ ] Passwords NEVER stored as plaintext
- [ ] PBKDF2 with >=100,000 iterations (SHA256)
- [ ] JWT uses HS256 algorithm (never none or symmetric without secret)
- [ ] HN_SECRET_KEY used for signing tokens
- [ ] Token includes exp claim set to 7 days from iat
**MUST HAVE for Score >3:**
- [ ] AuthContext provides login, register, logout functions
- [ ] localStorage persistence with AUTH_TOKEN key
- [ ] Session validation on page load (calls /api/auth/me)
- [ ] 401 responses for invalid tokens
## Bonus Points Consideration
**+1 point** for:
- Input validation regex in register endpoint (username: ^[a-zA-Z0-9_]{3,20}$)
- Password strength requirements enforced (minimum length, complexity)
**+2 points** for:
- Error messages don't leak information (e.g., "Invalid credentials" not "User doesn't exist")
- Rate limiting placeholder comments in auth endpoints
**+3 points** for:
- Complete error handling with meaningful user feedback
- Protected routes redirect to login (frontend guard)
## Test Scenarios to Verify Score 5
1. **Registration Flow**:
- New username + password → creates User record with hashed password
- Returns {token, username} in response
- Token can be used for /api/auth/me and returns user data
2. **Login Flow**:
- Correct credentials → returns valid token
- Wrong credentials → 401 error
- Non-existent user → 401 error
3. **Session Restoration**:
- Page load with stored AUTH_TOKEN → calls /api/auth/me
- Valid token → username set in state
- Invalid/expired token → localStorage cleared, ready=true
4. **Logout Flow**:
- User clicks logout → localStorage.removeItem(AUTH_TOKEN)
- Next page load shows logged out state
5. **Token Validation**:
- Modified token → 401 on /api/auth/me
- Expired token (after 7 days) → 401 error
- Missing Authorization header → 401 error