style: run prettier on entire codebase
This commit is contained in:
@@ -1,164 +1,208 @@
|
||||
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';
|
||||
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) {
|
||||
function setRefreshCookie(
|
||||
reply: import("fastify").FastifyReply,
|
||||
token: string,
|
||||
rememberMe: boolean,
|
||||
) {
|
||||
const maxAge = rememberMe
|
||||
? config.jwt.refreshTokenRememberExpiry
|
||||
: config.jwt.refreshTokenSessionExpiry;
|
||||
|
||||
reply.setCookie('refresh_token', token, {
|
||||
reply.setCookie("refresh_token", token, {
|
||||
httpOnly: true,
|
||||
secure: config.isProduction,
|
||||
sameSite: 'strict',
|
||||
path: '/api/admin',
|
||||
sameSite: "strict",
|
||||
path: "/api/admin",
|
||||
maxAge,
|
||||
});
|
||||
}
|
||||
|
||||
export default async function authRoutes(fastify: FastifyInstance): Promise<void> {
|
||||
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',
|
||||
fastify.post<{ Body: LoginRequest }>(
|
||||
"/login",
|
||||
{
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: 20,
|
||||
timeWindow: "1 minute",
|
||||
},
|
||||
},
|
||||
bodyLimit: 10240,
|
||||
},
|
||||
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;
|
||||
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);
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
if (result.type === 'error') {
|
||||
await logAudit({
|
||||
request,
|
||||
action: 'login_failed',
|
||||
entityType: 'user',
|
||||
description: `Neúspěšný pokus o přihlášení: ${username}`,
|
||||
authData: result.user,
|
||||
action: "login",
|
||||
entityType: "user",
|
||||
entityId: result.user.userId,
|
||||
description: `Přihlášení uživatele ${result.user.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,
|
||||
});
|
||||
});
|
||||
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';
|
||||
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 tokenHash = crypto
|
||||
.createHash("sha256")
|
||||
.update(login_token)
|
||||
.digest("hex");
|
||||
|
||||
const storedToken = await prisma.totp_login_tokens.findFirst({
|
||||
where: { token_hash: tokenHash },
|
||||
});
|
||||
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);
|
||||
}
|
||||
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 },
|
||||
});
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
const isValid = OTPAuth.verify(user.totp_secret, totp_code);
|
||||
if (!isValid) {
|
||||
return error(reply, "Neplatný TOTP kód", 401);
|
||||
}
|
||||
|
||||
// Delete used login token
|
||||
await prisma.totp_login_tokens.delete({ where: { id: storedToken.id } });
|
||||
// Delete used login token
|
||||
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() },
|
||||
});
|
||||
// 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);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
// Create tokens manually since password was already verified
|
||||
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 },
|
||||
);
|
||||
// Create tokens manually since password was already verified
|
||||
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 refreshTokenRaw = crypto.randomBytes(32).toString("hex");
|
||||
const refreshTokenHash = crypto
|
||||
.createHash("sha256")
|
||||
.update(refreshTokenRaw)
|
||||
.digest("hex");
|
||||
|
||||
const expiresIn = rememberMe
|
||||
? config.jwt.refreshTokenRememberExpiry
|
||||
: config.jwt.refreshTokenSessionExpiry;
|
||||
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,
|
||||
},
|
||||
});
|
||||
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 });
|
||||
});
|
||||
setRefreshCookie(reply, refreshTokenRaw, rememberMe);
|
||||
return success(reply, { access_token: accessToken, user: authData });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /api/admin/refresh
|
||||
fastify.post('/refresh', { bodyLimit: 10240 }, async (request, reply) => {
|
||||
fastify.post("/refresh", { bodyLimit: 10240 }, async (request, reply) => {
|
||||
const refreshTokenRaw = request.cookies.refresh_token;
|
||||
if (!refreshTokenRaw) {
|
||||
return error(reply, 'Refresh token chybí', 401);
|
||||
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' });
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -171,28 +215,33 @@ export default async function authRoutes(fastify: FastifyInstance): Promise<void
|
||||
});
|
||||
|
||||
// POST /api/admin/logout
|
||||
fastify.post('/logout', async (request, reply) => {
|
||||
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é');
|
||||
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) => {
|
||||
fastify.get("/session", async (request, reply) => {
|
||||
const authHeader = request.headers.authorization;
|
||||
if (!authHeader?.startsWith('Bearer ')) {
|
||||
return error(reply, 'Vyžadována autentizace', 401);
|
||||
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 error(reply, "Neplatný token", 401);
|
||||
}
|
||||
|
||||
return success(reply, { user: authData });
|
||||
|
||||
Reference in New Issue
Block a user