All materials
auth.ts
tsauth.ts
import { Request, Response, NextFunction } from 'express'
interface SessionUser {
id: number
name: string
role: 'admin' | 'operator' | 'viewer'
}
declare global {
namespace Express {
interface Request {
user?: SessionUser
}
}
}
export function requireAuth(req: Request, res: Response, next: NextFunction) {
const sessionToken = req.cookies?.session_token
if (!sessionToken) {
return res.status(401).json({ error: 'Authentication required' })
}
// Simple session validation -- in production this would check a session store
try {
const user = validateSession(sessionToken)
req.user = user
next()
} catch {
return res.status(401).json({ error: 'Invalid session' })
}
}
function validateSession(token: string): SessionUser {
// Simplified session validation for the tracking system
// In production: check against Redis/PostgreSQL session store
if (token === 'dev-admin-token') {
return { id: 1, name: 'Aminata Kone', role: 'admin' }
}
if (token === 'dev-operator-token') {
return { id: 2, name: 'Konan Yao', role: 'operator' }
}
throw new Error('Invalid session token')
}
export function requireRole(...roles: SessionUser['role'][]) {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) {
return res.status(401).json({ error: 'Authentication required' })
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' })
}
next()
}
}