210 lines
7.4 KiB
TypeScript
210 lines
7.4 KiB
TypeScript
import { Router } from 'express';
|
|
import type { Request, Response } from 'express';
|
|
import { z } from 'zod';
|
|
import type { AppDeps } from '../deps.js';
|
|
import { config } from '../config.js';
|
|
import { REFRESH_COOKIE, REFRESH_COOKIE_ADMIN, verifyRefreshToken } from '../lib/jwt.js';
|
|
import { validate } from '../middleware/validate.js';
|
|
import { authLimiter } from '../middleware/rateLimit.js';
|
|
import { AppError, unauthorized } from '../lib/errors.js';
|
|
import { logger } from '../lib/logger.js';
|
|
import { asyncHandler } from '../lib/asyncHandler.js';
|
|
import { login, register, refresh } from '../services/auth.js';
|
|
import { logActivity } from '../services/audit.js';
|
|
|
|
const registerSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string().min(8),
|
|
firstName: z.string().min(1).max(100).optional(),
|
|
lastName: z.string().min(1).max(100).optional(),
|
|
});
|
|
|
|
const loginSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string(),
|
|
});
|
|
|
|
/**
|
|
* Admin i SPA serwują z tej samej domeny (różne porty), a ciastka portów nie
|
|
* rozróżniają. Klient panelu admina wysyła nagłówek `X-Client: admin` przy
|
|
* login/refresh/logout — wtedy ciastko wystawiamy/odczytujemy/czyszczymy pod
|
|
* oddzielną nazwą. Bez nagłówka — domyślna nazwa aplikacji użytkownika.
|
|
*/
|
|
function isAdminClient(req: Request): boolean {
|
|
return req.get('x-client')?.toLowerCase() === 'admin';
|
|
}
|
|
|
|
function cookieName(req: Request): string {
|
|
return isAdminClient(req) ? REFRESH_COOKIE_ADMIN : REFRESH_COOKIE;
|
|
}
|
|
|
|
function setRefreshCookie(res: Response, token: string, admin: boolean) {
|
|
res.cookie(admin ? REFRESH_COOKIE_ADMIN : REFRESH_COOKIE, token, {
|
|
httpOnly: true,
|
|
sameSite: 'lax',
|
|
secure: config.cookieSecure,
|
|
maxAge: 7 * 24 * 3600 * 1000,
|
|
path: '/',
|
|
});
|
|
}
|
|
|
|
function clearRefreshCookies(res: Response) {
|
|
res.clearCookie(REFRESH_COOKIE, { path: '/' });
|
|
res.clearCookie(REFRESH_COOKIE_ADMIN, { path: '/' });
|
|
}
|
|
|
|
export function createAuthRoutes({ prisma }: AppDeps) {
|
|
const router = Router();
|
|
|
|
/**
|
|
* @openapi
|
|
* /auth/register:
|
|
* post:
|
|
* summary: Self-registration (default role: member, no gym membership)
|
|
* tags: [Auth]
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* required: [email, password]
|
|
* properties:
|
|
* email: { type: string }
|
|
* password: { type: string }
|
|
* firstName: { type: string }
|
|
* lastName: { type: string }
|
|
* responses:
|
|
* 201: { description: Created, returns user + access token }
|
|
* 409: { description: Email already registered }
|
|
*/
|
|
router.post(
|
|
'/register',
|
|
authLimiter,
|
|
validate(registerSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof registerSchema>;
|
|
const result = await register(prisma, data);
|
|
await logActivity(prisma, {
|
|
actorId: result.user.id,
|
|
action: 'user.registered',
|
|
entityType: 'user',
|
|
entityId: result.user.id,
|
|
details: { email: result.user.email, ip: req.ip },
|
|
});
|
|
setRefreshCookie(res, result.refreshToken, isAdminClient(req));
|
|
res.status(201).json({ user: result.user, accessToken: result.accessToken });
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /auth/login:
|
|
* post:
|
|
* summary: Login with email + password
|
|
* tags: [Auth]
|
|
* responses:
|
|
* 200: { description: 'OK, returns user + access token; dla konta z isAdmin=true (login z aplikacji) wystawiamy tez ciastko fitos_admin_refresh — SSO panelu' }
|
|
* 401: { description: Invalid credentials }
|
|
*/
|
|
router.post(
|
|
'/login',
|
|
authLimiter,
|
|
validate(loginSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof loginSchema>;
|
|
const result = await login(prisma, data);
|
|
await logActivity(prisma, {
|
|
actorId: result.user.id,
|
|
action: 'user.logged_in',
|
|
entityType: 'user',
|
|
entityId: result.user.id,
|
|
details: { client: isAdminClient(req) ? 'admin' : 'app', ip: req.ip },
|
|
});
|
|
setRefreshCookie(res, result.refreshToken, isAdminClient(req));
|
|
// Administrator logujacy sie przez aplikacje dostaje dodatkowo ciastko
|
|
// panelu — link „Panel admina" otwiera admina juz zalogowanego (te same
|
|
// ciastka po tej samej domenie; rotacja nie uniewaznia starych wartosci).
|
|
if (!isAdminClient(req) && result.user.isAdmin) {
|
|
setRefreshCookie(res, result.refreshToken, true);
|
|
}
|
|
res.json({ user: result.user, accessToken: result.accessToken });
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /auth/refresh:
|
|
* post:
|
|
* summary: Refresh access token (refresh token from httpOnly cookie, rotated on success)
|
|
* tags: [Auth]
|
|
* parameters:
|
|
* - in: header
|
|
* name: X-Client
|
|
* schema: { type: string, enum: [admin] }
|
|
* description: Panel admina wysyła ten nagłówek, by odświeżać ciastko `fitos_admin_refresh` (app używa `fitos_refresh`).
|
|
* responses:
|
|
* 200: { description: OK, returns new access token (new refresh token in cookie) }
|
|
* 401: { description: Missing/invalid/revoked refresh token }
|
|
*/
|
|
// Bez authLimiter: odświeżanie jest normalną czynnością klienta (co ~15 min,
|
|
// na kartę); limit na loginie/rejestracji zostaje (guarda przed brute-force).
|
|
router.post(
|
|
'/refresh',
|
|
asyncHandler(async (req, res) => {
|
|
const admin = isAdminClient(req);
|
|
const token = (req.cookies as Record<string, string | undefined>)[cookieName(req)];
|
|
try {
|
|
if (!token) throw unauthorized('Missing refresh token');
|
|
const result = await refresh(prisma, token);
|
|
setRefreshCookie(res, result.refreshToken, admin);
|
|
res.json({ accessToken: result.accessToken });
|
|
} catch (e) {
|
|
clearRefreshCookies(res);
|
|
throw e instanceof AppError ? e : unauthorized('Invalid refresh token');
|
|
}
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /auth/logout:
|
|
* post:
|
|
* summary: Logout (clears refresh cookie and revokes all issued refresh tokens of the user)
|
|
* tags: [Auth]
|
|
* responses:
|
|
* 204: { description: No content }
|
|
*/
|
|
router.post(
|
|
'/logout',
|
|
asyncHandler(async (req, res) => {
|
|
// Unieważniamy tokeny przez podbicie tokenVersion (ważne access tokeny
|
|
// wygasną same — max 15 min). Przy błędnym/wygasłym ciastku tylko czyścimy.
|
|
const cookies = req.cookies as Record<string, string | undefined>;
|
|
const token =
|
|
cookies[cookieName(req)] ?? cookies[REFRESH_COOKIE] ?? cookies[REFRESH_COOKIE_ADMIN];
|
|
if (token) {
|
|
try {
|
|
const payload = verifyRefreshToken(token);
|
|
await prisma.user
|
|
.update({ where: { id: payload.sub }, data: { tokenVersion: { increment: 1 } } })
|
|
.catch((e: unknown) => logger.warn({ e }, 'logout tokenVersion bump failed'));
|
|
await logActivity(prisma, {
|
|
actorId: payload.sub,
|
|
action: 'user.logged_out',
|
|
entityType: 'user',
|
|
entityId: payload.sub,
|
|
details: { client: isAdminClient(req) ? 'admin' : 'app', ip: req.ip },
|
|
});
|
|
} catch {
|
|
// token nieważny — nie ma czego unieważniać
|
|
}
|
|
}
|
|
clearRefreshCookies(res);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
return router;
|
|
}
|