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
16 KiB
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)
-
Create
backend/app/auth.pywith:- Password hashing using PBKDF2 with salt
- JWT token creation and verification
- Current user dependency that validates Bearer tokens
- Environment variable
HN_SECRET_KEYfor JWT signing (default dev key)
-
Update
backend/app/models.pyto add User model:id: Integer primary keyusername: String(60), unique, indexpassword_hash: String(128)created_at: DateTime with default
-
Create/update authentication endpoints in
backend/app/main.py:POST /api/auth/register- Register new user, return JWT tokenPOST /api/auth/login- Login, return JWT tokenPOST /api/auth/logout- Logout (clear token, optional)GET /api/auth/me- Return current user info- Password hashing with PBKDF2 (120,000 iterations minimum)
-
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
- Add
-
Update
backend/app/database.pyif needed:- Configure SQLite database properly for user persistence
- Ensure models can be created/queried
-
Create
data/.gitignorewith patterns to exclude:*.db *.sqlite data.db newzy.db -
Update project root
docker-compose.ymlif needed:- Add environment variable override for
HN_SECRET_KEY(optional, default in code) - Ensure database volume is properly mounted
- Add environment variable override for
Frontend Requirements (React + TypeScript)
-
Create
frontend/src/types/auth.ts:export interface TokenResponse { token: string; username: string; } export interface MeResponse { username: string; } -
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 )
- Handle token storage in localStorage
- Add methods for auth endpoints:
-
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/meto restore session - If token invalid/expired, clear storage
- Export
AuthProvidercomponent
-
Create page components:
frontend/src/pages/Login.tsx: Login form with username/password validationfrontend/src/pages/Register.tsx: Registration form with username/password validationfrontend/src/pages/SignOut.tsx: Sign out button that clears token and redirects to login
-
Update
frontend/src/App.tsx:- Wrap app with
<AuthProvider> - Set up protected routes for logged-in users (optional placeholder)
- Wrap app with
-
Create CSS styling:
frontend/src/assets/styles/auth.cssor include in existing styles- Auth pages should be clean, accessible forms
- Proper loading states during API calls
Shared Requirements
-
Token Management:
- JWT token stored in
localStoragewith keyAUTH_TOKEN - Tokens have 7-day expiry (7 * 24 * 60 * 60 seconds)
- Token format:
sub=USERNAME, iat=TIMESTAMP, exp=TIMESTAMP+7days
- JWT token stored in
-
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>
-
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
# 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)
# 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
# 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)
# 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
// 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
// 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
# .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
- Passwords never stored as plaintext
- JWT signed with strong secret (not hardcoded)
- PBKDF2 iterations >= 120,000
- Salt generated per-password using secrets module
- Username validation prevents injection attacks
- 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