Files
app/src/routes/admin/auth.ts
BOHA baceb88347 feat: NAS storage for invoices/offers, code cleanup, date/time fixes
- NAS storage for created invoices (PDF via puppeteer), received invoices,
  and offers with auto-save on create/edit
- Deterministic file paths derived from DB fields (no file_path column needed)
- Separate NAS mount points: NAS_FINANCIALS_PATH, NAS_OFFERS_PATH
- Invoice language field (cs/en) stored per invoice, replaces lang modal
- Invoices list filtered by month/year matching KPI card selection
- Centralized date helpers (src/utils/date.ts) replacing all .toISOString()
  calls that returned UTC instead of local time
- Attendance project switching uses exact time (not rounded)
- Comment cleanup: removed ~100 unnecessary/Czech comments
- Removed as-any casts in orders and attendance
- Prisma migrations: add invoice language, drop received_invoices BLOB columns

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 10:36:39 +01:00

248 lines
7.2 KiB
TypeScript

import { FastifyInstance } from "fastify";
import {
login,
refreshAccessToken,
logout,
verifyAccessToken,
} from "../../services/auth";
import { logAudit } from "../../services/audit";
import { success, error } from "../../utils/response";
import { config } from "../../config/env";
import { LoginRequest, TotpVerifyRequest } from "../../types";
import prisma from "../../config/database";
import crypto from "crypto";
import { OTPAuth } from "../../utils/totp";
import { parseBody } from "../../schemas/common";
import { LoginSchema, TotpVerifySchema } from "../../schemas/auth.schema";
function setRefreshCookie(
reply: import("fastify").FastifyReply,
token: string,
rememberMe: boolean,
) {
const maxAge = rememberMe
? config.jwt.refreshTokenRememberExpiry
: config.jwt.refreshTokenSessionExpiry;
reply.setCookie("refresh_token", token, {
httpOnly: true,
secure: config.isProduction,
sameSite: "strict",
path: "/api/admin",
maxAge,
});
}
export default async function authRoutes(
fastify: FastifyInstance,
): Promise<void> {
// POST /api/admin/login
fastify.post<{ Body: LoginRequest }>(
"/login",
{
config: {
rateLimit: {
max: 20,
timeWindow: "1 minute",
},
},
bodyLimit: 10240,
},
async (request, reply) => {
const parsed = parseBody(LoginSchema, request.body);
if ("error" in parsed) return error(reply, parsed.error, 400);
const { username, password, remember_me } = parsed.data;
const result = await login(username, password, remember_me, request);
if (result.type === "error") {
await logAudit({
request,
action: "login_failed",
entityType: "user",
description: `Neúspěšný pokus o přihlášení: ${username}`,
});
return error(reply, result.message, result.status);
}
if (result.type === "totp_required") {
return success(reply, {
totp_required: true,
login_token: result.loginToken,
});
}
await logAudit({
request,
authData: result.user,
action: "login",
entityType: "user",
entityId: result.user.userId,
description: `Přihlášení uživatele ${result.user.username}`,
});
setRefreshCookie(reply, result.refreshToken, remember_me);
return success(reply, {
access_token: result.accessToken,
user: result.user,
});
},
);
// POST /api/admin/login/totp
fastify.post<{ Body: TotpVerifyRequest }>(
"/login/totp",
{ bodyLimit: 10240 },
async (request, reply) => {
const parsed = parseBody(TotpVerifySchema, request.body);
if ("error" in parsed) return error(reply, parsed.error, 400);
const { login_token, totp_code } = parsed.data;
const rawBody = request.body as unknown as Record<string, unknown>;
const rememberMe =
rawBody.remember_me === true || rawBody.remember_me === "true";
const tokenHash = crypto
.createHash("sha256")
.update(login_token)
.digest("hex");
const storedToken = await prisma.totp_login_tokens.findFirst({
where: { token_hash: tokenHash },
});
if (!storedToken || new Date(storedToken.expires_at) < new Date()) {
return error(reply, "Neplatný nebo expirovaný login token", 401);
}
const user = await prisma.users.findUnique({
where: { id: storedToken.user_id },
include: { roles: true },
});
if (!user || !user.totp_secret) {
return error(reply, "Uživatel nenalezen", 401);
}
const isValid = OTPAuth.verify(user.totp_secret, totp_code);
if (!isValid) {
return error(reply, "Neplatný TOTP kód", 401);
}
await prisma.totp_login_tokens.delete({ where: { id: storedToken.id } });
// Reset failed attempts and update last login (TOTP verified = successful login)
await prisma.users.update({
where: { id: user.id },
data: {
failed_login_attempts: 0,
locked_until: null,
last_login: new Date(),
},
});
// Create tokens directly — password was already verified before TOTP was requested
const authData = await (
await import("../../services/auth")
).loadAuthData(user.id);
if (!authData) {
return error(reply, "Chyba načítání uživatele", 500);
}
const jwt = await import("jsonwebtoken");
const accessToken = jwt.default.sign(
{
sub: user.id,
username: user.username,
role: user.roles?.name ?? null,
},
config.jwt.secret,
{ expiresIn: config.jwt.accessTokenExpiry },
);
const refreshTokenRaw = crypto.randomBytes(32).toString("hex");
const refreshTokenHash = crypto
.createHash("sha256")
.update(refreshTokenRaw)
.digest("hex");
const expiresIn = rememberMe
? config.jwt.refreshTokenRememberExpiry
: config.jwt.refreshTokenSessionExpiry;
await prisma.refresh_tokens.create({
data: {
user_id: user.id,
token_hash: refreshTokenHash,
expires_at: new Date(Date.now() + expiresIn * 1000),
remember_me: rememberMe,
ip_address: request.ip,
user_agent: request.headers["user-agent"] ?? null,
},
});
setRefreshCookie(reply, refreshTokenRaw, rememberMe);
return success(reply, { access_token: accessToken, user: authData });
},
);
// POST /api/admin/refresh
fastify.post("/refresh", { bodyLimit: 10240 }, async (request, reply) => {
const refreshTokenRaw = request.cookies.refresh_token;
if (!refreshTokenRaw) {
return error(reply, "Refresh token chybí", 401);
}
const result = await refreshAccessToken(refreshTokenRaw, request);
if (result.type === "error") {
reply.clearCookie("refresh_token", {
path: "/api/admin",
httpOnly: true,
secure: config.isProduction,
sameSite: "strict",
});
return error(reply, result.message, result.status);
}
// Preserve the original remember_me flag so long-lived sessions stay long-lived after rotation
setRefreshCookie(reply, result.refreshToken, result.rememberMe);
return success(reply, {
access_token: result.accessToken,
user: result.user,
});
});
// POST /api/admin/logout
fastify.post("/logout", async (request, reply) => {
const refreshTokenRaw = request.cookies.refresh_token;
if (refreshTokenRaw) {
await logout(refreshTokenRaw);
}
reply.clearCookie("refresh_token", {
path: "/api/admin",
httpOnly: true,
secure: config.isProduction,
sameSite: "strict",
});
return success(reply, null, 200, "Odhlášení úspěšné");
});
// GET /api/admin/session
fastify.get("/session", async (request, reply) => {
const authHeader = request.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
return error(reply, "Vyžadována autentizace", 401);
}
const token = authHeader.slice(7);
const authData = await verifyAccessToken(token);
if (!authData) {
return error(reply, "Neplatný token", 401);
}
return success(reply, { user: authData });
});
}