Baseline: stan przed refaktoryzacja struktury

This commit is contained in:
tisachi
2026-09-04 19:06:19 +02:00
commit 1c8594ad96
369 changed files with 71407 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
import type { NextFunction, Request, Response } from 'express';
import type { PrismaClient } from '@prisma/client';
import { verifyAccessToken } from '../lib/jwt.js';
import { AppError, forbidden, unauthorized } from '../lib/errors.js';
declare global {
namespace Express {
interface Request {
user?: { id: string; isAdmin: boolean; tokenVersion: number };
}
}
}
export function authenticate(prisma: PrismaClient) {
return async (req: Request, _res: Response, next: NextFunction) => {
try {
const header = req.headers.authorization;
if (!header || !header.startsWith('Bearer ')) throw unauthorized('Missing access token');
const payload = verifyAccessToken(header.slice(7));
const user = await prisma.user.findUnique({ where: { id: payload.sub } });
if (!user || user.tokenVersion !== payload.tv) throw unauthorized('Token revoked');
req.user = { id: user.id, isAdmin: user.isAdmin, tokenVersion: user.tokenVersion };
next();
} catch (e) {
next(e instanceof AppError ? e : unauthorized('Invalid or expired token'));
}
};
}
export function requireAdmin(req: Request, _res: Response, next: NextFunction) {
if (!req.user?.isAdmin) return next(forbidden('Admin access required'));
next();
}
/** The user must hold the TRAINER role in at least one gym. */
export function requireTrainer(prisma: PrismaClient) {
return async (req: Request, _res: Response, next: NextFunction) => {
try {
const membership = await prisma.gymMembership.findFirst({
where: { userId: req.user!.id, roles: { has: 'TRAINER' } },
});
if (!membership) return next(forbidden('Trainer role required'));
next();
} catch (e) {
next(e);
}
};
}

View File

@@ -0,0 +1,23 @@
import { NextFunction, Request, Response } from 'express';
import { ZodError } from 'zod';
import { AppError } from '../lib/errors.js';
import { logger } from '../lib/logger.js';
export function errorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) {
if (err instanceof AppError) {
return res.status(err.status).json({
error: { code: err.code, message: err.message, details: err.details },
});
}
if (err instanceof ZodError) {
return res.status(400).json({
error: { code: 'VALIDATION_ERROR', message: 'Validation failed', details: err.flatten() },
});
}
logger.error({ err, path: req.path }, 'Unhandled error');
res.status(500).json({ error: { code: 'INTERNAL_ERROR', message: 'Internal server error' } });
}
export function notFoundHandler(_req: Request, res: Response) {
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Route not found' } });
}

View File

@@ -0,0 +1,20 @@
import rateLimit from 'express-rate-limit';
/** Standard error body — spójny z resztą API (JSON, nie plain text). */
export const RATE_LIMIT_BODY = { error: { code: 'RATE_LIMITED', message: 'Too many requests, try later' } };
export const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: RATE_LIMIT_BODY,
});
export const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 20,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: { error: { code: 'RATE_LIMITED', message: 'Too many attempts, try later' } },
});

View File

@@ -0,0 +1,14 @@
import { NextFunction, Request, Response } from 'express';
import { ZodType } from 'zod';
import { badRequest } from '../lib/errors.js';
export function validate(schema: ZodType, source: 'body' | 'query' | 'params' = 'body') {
return (req: Request, _res: Response, next: NextFunction) => {
const result = schema.safeParse(req[source]);
if (!result.success) {
return next(badRequest('Validation failed', result.error.flatten()));
}
(req as unknown as Record<string, unknown>)[source] = result.data;
next();
};
}