Files
TicketingSystem/server/src/middleware/auth.ts
T
josh 27d2ab0f0d Add ESLint + Prettier + EditorConfig tooling at repo root
v1.0 Phase 1.1 — repo-wide lint/format baseline.

- eslint.config.mjs (flat config) lints server, client, shared
- .prettierrc.json, .prettierignore, .editorconfig, .nvmrc
- Root package.json holds shared devDeps; per-package scripts keep
  their typecheck + test runners
- Fix 7 lint issues surfaced by the baseline run:
  - TicketDetail.tsx: replace ternary-with-side-effects with if/else
  - admin/Users.tsx: escape apostrophe in JSX
  - errorHandler.ts: typed err as unknown with ErrorLike refinement
  - users.ts: Prisma.UserUpdateInput instead of Record<string, any>
  - seed.ts: drop unused goddard binding
- Run prettier across tracked sources for a clean formatting baseline
2026-04-18 14:47:34 -04:00

58 lines
1.6 KiB
TypeScript

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import prisma from '../lib/prisma';
export interface AuthRequest extends Request {
user?: {
id: string;
role: string;
username: string;
};
}
export const authenticate = async (req: AuthRequest, res: Response, next: NextFunction) => {
const apiKey = req.headers['x-api-key'] as string | undefined;
if (apiKey) {
const user = await prisma.user.findUnique({ where: { apiKey } });
if (!user || user.role !== 'SERVICE') {
return res.status(401).json({ error: 'Invalid API key' });
}
req.user = { id: user.id, role: user.role, username: user.username };
return next();
}
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = authHeader.split(' ')[1];
try {
const payload = jwt.verify(token, process.env.JWT_SECRET!) as {
id: string;
role: string;
username: string;
};
req.user = payload;
next();
} catch {
return res.status(401).json({ error: 'Invalid or expired token' });
}
};
export const requireAdmin = (req: AuthRequest, res: Response, next: NextFunction) => {
if (req.user?.role !== 'ADMIN') {
return res.status(403).json({ error: 'Admin access required' });
}
next();
};
// Blocks USER role — allows ADMIN, AGENT, SERVICE
export const requireAgent = (req: AuthRequest, res: Response, next: NextFunction) => {
if (req.user?.role === 'USER') {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};