feat: add 2FA, secure cookies and publishing tools
All checks were successful
CI / Validate frontend and API (push) Successful in 3m5s
CI / Build and publish Docker images (push) Successful in 1m42s

This commit is contained in:
Cauê Faleiros
2026-11-06 10:29:37 -03:00
parent fff63f5efa
commit 50905eefd7
40 changed files with 3493 additions and 215 deletions

View File

@@ -1,3 +1,4 @@
import cookie from '@fastify/cookie';
import cors from '@fastify/cors';
import Fastify from 'fastify';
import { ZodError } from 'zod';
@@ -53,8 +54,10 @@ export function buildApp() {
app.addContentTypeParser(contentType, { parseAs: 'buffer', bodyLimit: config.BUNNY_ASSET_MAX_UPLOAD_MB * 1024 * 1024 }, (_request, body, done) => done(null, body));
}
app.register(cookie);
app.register(cors, {
origin: config.FRONTEND_ORIGIN,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
});

View File

@@ -12,6 +12,7 @@ export interface AuthUser {
role: UserRole;
name: string;
tokenVersion: number;
impersonatedBy?: string;
}
declare module '@fastify/jwt' {
@@ -29,7 +30,11 @@ declare module 'fastify' {
}
const registerAuth: FastifyPluginAsync = async (app) => {
await app.register(fastifyJwt, { secret: config.JWT_SECRET });
await app.register(fastifyJwt, {
secret: config.JWT_SECRET,
cookie: { cookieName: 'compor_session', signed: false },
sign: { expiresIn: '7d' },
});
const verifyActiveUser = async (request: { jwtVerify: () => Promise<void>; user: AuthUser }, reply: { code: (status: number) => { send: (payload: object) => unknown } }) => {
try {
@@ -54,6 +59,11 @@ const registerAuth: FastifyPluginAsync = async (app) => {
return false;
}
if (request.user.impersonatedBy && account.role === 'admin') {
reply.code(403).send({ error: 'Encerre a impersonação para acessar esta área.' });
return false;
}
request.user.role = account.role;
request.user.name = account.display_name;
request.user.tokenVersion = account.token_version;

View File

@@ -0,0 +1,37 @@
import type { FastifyReply } from 'fastify';
import { config } from '../config.js';
export const SESSION_COOKIE = 'compor_session';
export const ADMIN_SESSION_COOKIE = 'compor_admin_session';
const SESSION_MAX_AGE_SECONDS = (() => {
const match = /^(\d+)([smhd])$/.exec(config.JWT_SESSION_TTL);
if (!match) return 60 * 60 * 24 * 7;
const value = Number(match[1]);
const unit = match[2];
return unit === 's' ? value : unit === 'm' ? value * 60 : unit === 'h' ? value * 3600 : value * 86400;
})();
const cookieOptions = {
httpOnly: true,
secure: config.APP_ENV === 'production',
sameSite: 'lax' as const,
path: '/',
maxAge: SESSION_MAX_AGE_SECONDS,
};
export const setSessionCookie = (reply: FastifyReply, token: string) => {
reply.setCookie(SESSION_COOKIE, token, cookieOptions);
};
export const clearSessionCookie = (reply: FastifyReply) => {
reply.clearCookie(SESSION_COOKIE, { path: '/' });
};
export const setAdminSessionCookie = (reply: FastifyReply, token: string) => {
reply.setCookie(ADMIN_SESSION_COOKIE, token, cookieOptions);
};
export const clearAdminSessionCookie = (reply: FastifyReply) => {
reply.clearCookie(ADMIN_SESSION_COOKIE, { path: '/' });
};

View File

@@ -1,12 +1,14 @@
import { buildApp } from './app.js';
import { config } from './config.js';
import { closePool } from './db/pool.js';
import { startScheduledPublisher } from './services/scheduler.js';
const app = buildApp();
async function start() {
try {
await app.listen({ host: '0.0.0.0', port: config.API_PORT });
startScheduledPublisher(app.log);
} catch (error) {
app.log.error(error);
await closePool();

View File

@@ -3,6 +3,8 @@ import type { PoolClient } from 'pg';
import { z } from 'zod';
import { pool } from '../db/pool.js';
import { createRawToken, hashToken } from '../auth/account-tokens.js';
import type { AuthUser } from '../auth/plugin.js';
import { setAdminSessionCookie, setSessionCookie } from '../auth/session-cookie.js';
import { config } from '../config.js';
import { recordAudit } from '../audit.js';
import { sendInvitationEmail, sendPasswordResetEmail } from '../services/email.js';
@@ -20,6 +22,13 @@ const updateUserSchema = z.object({
message: 'Informe pelo menos um campo para atualizar.',
});
const invitationSchema = z.object({ email: z.string().email().transform((email) => email.toLowerCase()), role: z.literal('instructor').default('instructor') });
const bulkInvitationSchema = z.object({
emails: z.array(z.string().email().transform((email) => email.toLowerCase())).min(1).max(100),
});
const bulkUserStatusSchema = z.object({
userIds: z.array(z.string().uuid()).min(1).max(200),
isActive: z.boolean(),
});
const categorySchema = z.object({ name: z.string().trim().min(1).max(120), isActive: z.boolean().optional(), position: z.number().int().min(0).max(10_000).optional() });
const categoryParamsSchema = z.object({ categoryId: z.string().uuid() });
const homeConfigurationSchema = z.object({
@@ -131,6 +140,29 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
return { data: result.rows };
});
app.patch('/users/bulk', adminAccess, async (request, reply) => {
const input = bulkUserStatusSchema.parse(request.body);
if (!input.isActive && input.userIds.includes(request.user.id)) {
return reply.code(400).send({ error: 'Você não pode desativar sua própria conta.' });
}
const result = await pool.query(
`update users
set is_active = $2
where id = any($1::uuid[])
returning id, email, display_name as name, role, is_active as "isActive", created_at as "createdAt",
(select max(lp.updated_at) from lesson_progress lp where lp.user_id = users.id) as "lastAccessAt"`,
[input.userIds, input.isActive],
);
await recordAudit({
actorId: request.user.id,
action: input.isActive ? 'user.bulk_activated' : 'user.bulk_deactivated',
subjectType: 'user',
metadata: { userIds: input.userIds },
ipAddress: request.ip,
});
return { data: result.rows };
});
app.get('/dashboard', adminAccess, async () => {
const result = await pool.query(
`select
@@ -351,6 +383,81 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
return { data: result.rows };
});
app.post('/invitations/bulk', adminAccess, async (request) => {
const input = bulkInvitationSchema.parse(request.body);
const emails = [...new Set(input.emails)];
const results: Array<{ email: string; inviteUrl?: string; error?: string }> = [];
for (const email of emails) {
const existing = await pool.query('select 1 from users where email = $1', [email]);
if (existing.rowCount) {
results.push({ email, error: 'Este e-mail já possui uma conta.' });
continue;
}
try {
const rawToken = createRawToken();
await pool.query(
`insert into account_access_tokens (email, role, purpose, token_hash, expires_at, created_by)
values ($1, 'instructor'::user_role, 'invitation', $2, now() + ($3::int * interval '1 hour'), $4)`,
[email, hashToken(rawToken), config.INVITATION_TTL_HOURS, request.user.id],
);
const inviteUrl = `${config.FRONTEND_ORIGIN}/invite?token=${rawToken}`;
try {
const sent = await sendInvitationEmail({ email, inviteUrl });
if (!sent && config.SMTP_HOST) request.log.warn({ email }, 'Bulk invitation email was rejected by the SMTP server');
} catch (error) {
request.log.error(error, 'Bulk invitation email could not be sent');
}
results.push({ email, inviteUrl });
} catch (error) {
request.log.error(error, 'Could not create bulk invitation');
results.push({ email, error: 'Não foi possível gerar o convite.' });
}
}
await recordAudit({
actorId: request.user.id,
action: 'invitation.bulk_created',
subjectType: 'invitation',
metadata: { emails, created: results.filter((result) => result.inviteUrl).length },
ipAddress: request.ip,
});
return { data: results };
});
app.post('/users/:userId/impersonate', adminAccess, async (request, reply) => {
const { userId } = userParamsSchema.parse(request.params);
if (userId === request.user.id) return reply.code(400).send({ error: 'Você já está usando sua própria conta.' });
const result = await pool.query<{ id: string; email: string; display_name: string; role: AuthUser['role']; token_version: number; is_active: boolean }>(
'select id, email, display_name, role, token_version, is_active from users where id = $1',
[userId],
);
const target = result.rows[0];
if (!target || !target.is_active) return reply.code(404).send({ error: 'Usuário não encontrado ou desativado.' });
if (target.role === 'admin') return reply.code(400).send({ error: 'Não é possível impersonar outra conta de administrador.' });
const targetUser: AuthUser = {
id: target.id,
email: target.email,
name: target.display_name,
role: target.role,
tokenVersion: target.token_version,
impersonatedBy: request.user.id,
};
setAdminSessionCookie(reply, await reply.jwtSign(request.user));
setSessionCookie(reply, await reply.jwtSign(targetUser));
await recordAudit({
actorId: request.user.id,
action: 'user.impersonated',
subjectType: 'user',
subjectId: target.id,
metadata: { email: target.email },
ipAddress: request.ip,
});
return { data: targetUser };
});
app.get('/users/:userId', adminAccess, async (request, reply) => {
const { userId } = userParamsSchema.parse(request.params);
const result = await pool.query(

View File

@@ -1,8 +1,18 @@
import type { FastifyPluginAsync } from 'fastify';
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
import * as OTPAuth from 'otpauth';
import QRCode from 'qrcode';
import { z } from 'zod';
import { hashPassword, verifyPassword } from '../auth/passwords.js';
import { createRawToken, hashToken } from '../auth/account-tokens.js';
import type { AuthUser } from '../auth/plugin.js';
import {
ADMIN_SESSION_COOKIE,
clearAdminSessionCookie,
clearSessionCookie,
setSessionCookie,
} from '../auth/session-cookie.js';
import { recordAudit } from '../audit.js';
import { pool } from '../db/pool.js';
import { config } from '../config.js';
import { sendPasswordResetEmail, sendWelcomeEmail } from '../services/email.js';
@@ -19,6 +29,14 @@ const tokenPasswordSchema = z.object({ token: z.string().min(20), password: z.st
const forgotPasswordSchema = z.object({
email: z.string().email().transform((email) => email.toLowerCase()),
});
const twoFactorCodeSchema = z.object({ code: z.string().trim().min(6).max(32) });
const twoFactorDisableSchema = twoFactorCodeSchema.extend({ password: z.string().min(8).max(200) });
const twoFactorVerifySchema = z.object({
challengeToken: z.string().min(20),
code: z.string().trim().min(6).max(32),
});
type UserRow = {
id: string;
@@ -28,6 +46,12 @@ type UserRow = {
password_hash: string;
is_active: boolean;
token_version: number;
two_factor_enabled: boolean;
};
type TwoFactorRow = UserRow & {
two_factor_secret: string | null;
two_factor_backup_codes: string[];
};
const serializeUser = (user: UserRow): AuthUser => ({
@@ -38,6 +62,40 @@ const serializeUser = (user: UserRow): AuthUser => ({
tokenVersion: user.token_version,
});
const createTotp = (secret: string, email: string) => new OTPAuth.TOTP({
issuer: 'Compor HUB',
label: email,
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: OTPAuth.Secret.fromBase32(secret),
});
const verifyTotp = (secret: string | null, email: string, code: string) => {
if (!secret) return false;
const token = code.replace(/\s+/g, '');
return createTotp(secret, email).validate({ token, window: 1 }) !== null;
};
const generateBackupCodes = () => Array.from({ length: 10 }, () => {
const raw = randomBytes(5).toString('hex').toUpperCase();
return `${raw.slice(0, 5)}-${raw.slice(5)}`;
});
const normalizeBackupCode = (code: string) => code.replace(/[\s-]/g, '').toUpperCase();
const backupCodeHash = (code: string) => createHmac('sha256', config.JWT_SECRET).update(normalizeBackupCode(code)).digest('hex');
const verifyBackupCode = (hashes: string[], code: string) => {
const hash = Buffer.from(backupCodeHash(code), 'hex');
return hashes.some((candidate) => {
const stored = Buffer.from(candidate, 'hex');
return stored.length === hash.length && timingSafeEqual(stored, hash);
});
};
const removeBackupCode = (hashes: string[], code: string) => hashes.filter((hash) => hash !== backupCodeHash(code));
export const authRoutes: FastifyPluginAsync = async (app) => {
// This is stored in PostgreSQL rather than process memory so the limit keeps
// working if the API is restarted or later scaled to more than one replica.
@@ -83,12 +141,13 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
}
const result = await client.query<UserRow>(
`insert into users (email, password_hash, display_name, role) values ($1, $2, $3, $4)
returning id, email, display_name, role, password_hash, is_active, token_version`,
returning id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled`,
[token.rows[0].email, await hashPassword(input.password), input.name, token.rows[0].role],
);
await client.query('commit');
const user = serializeUser(result.rows[0]);
return reply.code(201).send({ token: await reply.jwtSign(user, { expiresIn: config.JWT_SESSION_TTL }), user });
setSessionCookie(reply, await reply.jwtSign(user));
return reply.code(201).send({ user });
} catch {
await client.query('rollback');
return reply.code(409).send({ error: 'Este e-mail de convite já possui uma conta.' });
@@ -159,18 +218,18 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
const result = await pool.query<UserRow>(
`insert into users (email, password_hash, display_name)
values ($1, $2, $3)
returning id, email, display_name, role, password_hash, is_active, token_version`,
returning id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled`,
[input.email, passwordHash, input.name],
);
const user = serializeUser(result.rows[0]);
const token = await reply.jwtSign(user, { expiresIn: config.JWT_SESSION_TTL });
setSessionCookie(reply, await reply.jwtSign(user));
try {
const sent = await sendWelcomeEmail({ name: user.name, email: user.email });
if (!sent && config.SMTP_HOST) request.log.warn({ email: user.email }, 'Welcome email was rejected by the SMTP server');
} catch (error) {
request.log.error(error, 'Welcome email could not be sent');
}
return reply.code(201).send({ token, user });
return reply.code(201).send({ user });
} catch (error: unknown) {
if (typeof error === 'object' && error && 'code' in error && error.code === '23505') {
return reply.code(409).send({ error: 'Já existe uma conta com este e-mail.' });
@@ -183,7 +242,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
if (await rejectIfRateLimited(request.ip, reply)) return;
const input = credentialsSchema.parse(request.body);
const result = await pool.query<UserRow>(
`select id, email, display_name, role, password_hash, is_active, token_version from users where email = $1`,
`select id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled from users where email = $1`,
[input.email],
);
const account = result.rows[0];
@@ -192,9 +251,197 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
return reply.code(401).send({ error: 'E-mail ou senha inválidos.' });
}
if (account.two_factor_enabled) {
const challengeToken = app.jwt.sign(
{ sub: account.id, purpose: '2fa', tokenVersion: account.token_version } as unknown as AuthUser,
{ expiresIn: '5m' },
);
return { twoFactorRequired: true, challengeToken };
}
const user = serializeUser(account);
const token = await reply.jwtSign(user, { expiresIn: config.JWT_SESSION_TTL });
return { token, user };
setSessionCookie(reply, await reply.jwtSign(user));
return { user };
});
app.post('/2fa/verify', async (request, reply) => {
if (await rejectIfRateLimited(request.ip, reply)) return;
const input = twoFactorVerifySchema.parse(request.body);
let challenge: { sub?: string; purpose?: string; tokenVersion?: number };
try {
challenge = app.jwt.verify<{ sub?: string; purpose?: string; tokenVersion?: number }>(input.challengeToken);
} catch {
return reply.code(401).send({ error: 'Verificação expirada. Entre novamente.' });
}
if (challenge.purpose !== '2fa' || !challenge.sub) {
return reply.code(401).send({ error: 'Verificação inválida. Entre novamente.' });
}
const result = await pool.query<TwoFactorRow>(
`select id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled,
two_factor_secret, two_factor_backup_codes
from users where id = $1`,
[challenge.sub],
);
const account = result.rows[0];
if (!account || !account.is_active || !account.two_factor_enabled || account.token_version !== challenge.tokenVersion) {
return reply.code(401).send({ error: 'Verificação expirada. Entre novamente.' });
}
if (verifyTotp(account.two_factor_secret, account.email, input.code)) {
// Valid authenticator code.
} else if (verifyBackupCode(account.two_factor_backup_codes, input.code)) {
await pool.query('update users set two_factor_backup_codes = $2::jsonb where id = $1', [
account.id,
JSON.stringify(removeBackupCode(account.two_factor_backup_codes, input.code)),
]);
} else {
return reply.code(401).send({ error: 'Código de verificação inválido.' });
}
const user = serializeUser(account);
setSessionCookie(reply, await reply.jwtSign(user));
return { user };
});
app.post('/logout', async (_request, reply) => {
clearSessionCookie(reply);
clearAdminSessionCookie(reply);
return reply.code(204).send();
});
app.post('/stop-impersonation', async (request, reply) => {
const adminToken = request.cookies[ADMIN_SESSION_COOKIE];
if (!adminToken) return reply.code(400).send({ error: 'Não há impersonação ativa.' });
let payload: AuthUser;
try {
payload = app.jwt.verify<AuthUser>(adminToken);
} catch {
clearAdminSessionCookie(reply);
return reply.code(401).send({ error: 'Sessão de administrador expirada.' });
}
const result = await pool.query<{ id: string; email: string; display_name: string; role: AuthUser['role']; token_version: number; is_active: boolean }>(
'select id, email, display_name, role, token_version, is_active from users where id = $1',
[payload.id],
);
const account = result.rows[0];
if (!account || !account.is_active || account.role !== 'admin' || account.token_version !== payload.tokenVersion) {
clearSessionCookie(reply);
clearAdminSessionCookie(reply);
return reply.code(401).send({ error: 'Sessão de administrador expirada.' });
}
const admin: AuthUser = {
id: account.id,
email: account.email,
name: account.display_name,
role: account.role,
tokenVersion: account.token_version,
};
setSessionCookie(reply, await reply.jwtSign(admin));
clearAdminSessionCookie(reply);
await recordAudit({
actorId: admin.id,
action: 'user.impersonation_stopped',
subjectType: 'session',
ipAddress: request.ip,
});
return { user: admin };
});
app.get('/2fa', { preHandler: app.requireRoles(['admin']) }, async (request) => {
const result = await pool.query<{ enabled: boolean; backupCodes: string[] }>(
`select two_factor_enabled as enabled, two_factor_backup_codes as "backupCodes"
from users where id = $1`,
[request.user.id],
);
return { data: { enabled: result.rows[0]?.enabled ?? false, backupCodesRemaining: result.rows[0]?.backupCodes?.length ?? 0 } };
});
app.post('/2fa/setup', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const result = await pool.query<{ email: string; enabled: boolean }>(
'select email, two_factor_enabled as enabled from users where id = $1',
[request.user.id],
);
const account = result.rows[0];
if (!account) return reply.code(404).send({ error: 'Conta não encontrada.' });
if (account.enabled) return reply.code(400).send({ error: 'A verificação em duas etapas já está ativa.' });
const secret = new OTPAuth.Secret({ size: 20 }).base32;
await pool.query(
'update users set two_factor_secret = $2, two_factor_enabled = false, two_factor_backup_codes = $3::jsonb where id = $1',
[request.user.id, secret, JSON.stringify([])],
);
const otpauthUrl = createTotp(secret, account.email).toString();
const qrCode = await QRCode.toDataURL(otpauthUrl, { margin: 1, width: 240 });
return { data: { secret, otpauthUrl, qrCode } };
});
app.post('/2fa/enable', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const input = twoFactorCodeSchema.parse(request.body);
const result = await pool.query<{ email: string; enabled: boolean; secret: string | null }>(
'select email, two_factor_enabled as enabled, two_factor_secret as secret from users where id = $1',
[request.user.id],
);
const account = result.rows[0];
if (!account?.secret) return reply.code(400).send({ error: 'Configure a verificação em duas etapas primeiro.' });
if (account.enabled) return reply.code(400).send({ error: 'A verificação em duas etapas já está ativa.' });
if (!verifyTotp(account.secret, account.email, input.code)) {
return reply.code(400).send({ error: 'Código de verificação inválido.' });
}
const backupCodes = generateBackupCodes();
await pool.query(
'update users set two_factor_enabled = true, two_factor_backup_codes = $2::jsonb where id = $1',
[request.user.id, JSON.stringify(backupCodes.map(backupCodeHash))],
);
return { data: { backupCodes } };
});
app.post('/2fa/backup-codes', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const input = twoFactorCodeSchema.parse(request.body);
const result = await pool.query<{ email: string; enabled: boolean; secret: string | null }>(
'select email, two_factor_enabled as enabled, two_factor_secret as secret from users where id = $1',
[request.user.id],
);
const account = result.rows[0];
if (!account?.enabled || !account.secret) return reply.code(400).send({ error: 'A verificação em duas etapas não está ativa.' });
if (!verifyTotp(account.secret, account.email, input.code)) {
return reply.code(400).send({ error: 'Código de verificação inválido.' });
}
const backupCodes = generateBackupCodes();
await pool.query(
'update users set two_factor_backup_codes = $2::jsonb where id = $1',
[request.user.id, JSON.stringify(backupCodes.map(backupCodeHash))],
);
return { data: { backupCodes } };
});
app.post('/2fa/disable', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const input = twoFactorDisableSchema.parse(request.body);
const result = await pool.query<{ email: string; password_hash: string; enabled: boolean; secret: string | null; backupCodes: string[] }>(
`select email, password_hash, two_factor_enabled as enabled, two_factor_secret as secret,
two_factor_backup_codes as "backupCodes"
from users where id = $1`,
[request.user.id],
);
const account = result.rows[0];
if (!account?.enabled) return reply.code(400).send({ error: 'A verificação em duas etapas não está ativa.' });
if (!(await verifyPassword(input.password, account.password_hash))) {
return reply.code(401).send({ error: 'Senha incorreta.' });
}
if (!verifyTotp(account.secret, account.email, input.code) && !verifyBackupCode(account.backupCodes, input.code)) {
return reply.code(401).send({ error: 'Código de verificação inválido.' });
}
await pool.query(
'update users set two_factor_enabled = false, two_factor_secret = null, two_factor_backup_codes = $2::jsonb where id = $1',
[request.user.id, JSON.stringify([])],
);
return reply.code(204).send();
});
app.get('/me', { preHandler: app.authenticate }, async (request) => ({ user: request.user }));

View File

@@ -34,6 +34,7 @@ export const courseSelect = (publicOnly = false, includeUnreadyMedia = false) =>
c.cover_image_position_x as "coverImagePositionX",
c.cover_image_position_y as "coverImagePositionY",
c.status,
c.scheduled_publish_at as "scheduledPublishAt",
c.published_at as "publishedAt",
c.updated_at as "updatedAt",
c.created_at as "createdAt",

View File

@@ -50,6 +50,7 @@ const courseSchema = z.object({
coverImagePositionX: z.number().min(0).max(100).default(50),
coverImagePositionY: z.number().min(0).max(100).default(50),
status: z.enum(['draft', 'published']).default('draft'),
scheduledPublishAt: z.string().datetime().nullable().optional(),
lessons: z.array(lessonSchema).min(1),
assets: z.array(assetSchema).default([]),
});
@@ -230,10 +231,10 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
await client.query('begin');
const slug = await uniqueSlug(client, input.slug, input.title);
const course = await client.query<{ id: string }>(
`insert into courses (slug, title, description, category, cover_image_url, cover_image_zoom, cover_image_position_x, cover_image_position_y, status, instructor_id, published_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::course_status, $10, case when $9::course_status = 'published'::course_status then now() else null end)
`insert into courses (slug, title, description, category, cover_image_url, cover_image_zoom, cover_image_position_x, cover_image_position_y, status, instructor_id, published_at, scheduled_publish_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::course_status, $10, case when $9::course_status = 'published'::course_status then now() else null end, case when $9::course_status = 'published'::course_status then null else $11::timestamptz end)
returning id`,
[slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, request.user.id],
[slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, request.user.id, input.scheduledPublishAt ?? null],
);
await replaceCourseContents(client, course.rows[0].id, input);
await client.query('commit');
@@ -263,9 +264,10 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
await client.query(
`update courses
set slug = $2, title = $3, description = $4, category = $5, cover_image_url = $6, cover_image_zoom = $7, cover_image_position_x = $8, cover_image_position_y = $9,
status = $10::course_status, published_at = case when $10::course_status = 'published'::course_status then coalesce(published_at, now()) else null end
status = $10::course_status, published_at = case when $10::course_status = 'published'::course_status then coalesce(published_at, now()) else null end,
scheduled_publish_at = case when $10::course_status = 'published'::course_status then null else $11::timestamptz end
where id = $1`,
[courseId, slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status],
[courseId, slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, input.scheduledPublishAt ?? null],
);
await replaceCourseContents(client, courseId, input);
await client.query('commit');
@@ -287,7 +289,7 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
const client = await pool.connect();
try {
await client.query('begin');
await client.query(`update courses set status = 'archived', published_at = null where id = $1`, [courseId]);
await client.query(`update courses set status = 'archived', published_at = null, scheduled_publish_at = null where id = $1`, [courseId]);
await client.query('delete from learning_path_courses where course_id = $1', [courseId]);
await client.query('commit');
} catch (error) {

View File

@@ -15,10 +15,9 @@ export const notificationRoutes: FastifyPluginAsync = async (app) => {
limit 50`,
[request.user.id],
),
pool.query<{ count: number }>(
'select count(*)::int as count from notifications where user_id = $1 and read_at is null',
[request.user.id],
),
pool.query<{ count: number }>('select count(*)::int as count from notifications where user_id = $1 and read_at is null', [
request.user.id,
]),
]);
return { data: { items: items.rows, unread: unread.rows[0].count } };
});
@@ -30,7 +29,10 @@ export const notificationRoutes: FastifyPluginAsync = async (app) => {
app.post('/:notificationId/read', { preHandler: app.authenticate }, async (request, reply) => {
const { notificationId } = notificationParamsSchema.parse(request.params);
await pool.query('update notifications set read_at = coalesce(read_at, now()) where id = $1 and user_id = $2', [notificationId, request.user.id]);
await pool.query('update notifications set read_at = coalesce(read_at, now()) where id = $1 and user_id = $2', [
notificationId,
request.user.id,
]);
return reply.code(204).send();
});
};

View File

@@ -0,0 +1,71 @@
import type { FastifyBaseLogger } from 'fastify';
import { recordAudit } from '../audit.js';
import { pool } from '../db/pool.js';
/**
* Publishes drafts whose scheduled time has arrived, but only when every lesson
* has a ready video. If media is still processing, the course stays scheduled
* and is retried on the next tick.
*/
export const publishScheduledCourses = async (log?: FastifyBaseLogger) => {
const client = await pool.connect();
try {
await client.query('begin');
const result = await client.query<{ id: string; title: string; instructor_id: string }>(
`update courses c
set status = 'published'::course_status,
published_at = now(),
scheduled_publish_at = null
where c.status = 'draft'
and c.scheduled_publish_at is not null
and c.scheduled_publish_at <= now()
and exists (select 1 from lessons l where l.course_id = c.id)
and not exists (
select 1
from lessons l
where l.course_id = c.id
and not exists (
select 1 from lesson_media lm
where lm.lesson_id = l.id and lm.status = 'ready'
)
)
returning c.id, c.title, c.instructor_id`,
);
for (const course of result.rows) {
await client.query(
`insert into notifications (user_id, kind, title, body, href)
values ($1, 'course_published', $2, $3, $4)`,
[course.instructor_id, `Curso publicado: ${course.title}`, 'A publicação agendada foi concluída automaticamente.', '/gerenciar'],
);
}
await client.query('commit');
for (const course of result.rows) {
await recordAudit({
action: 'course.published.scheduled',
subjectType: 'course',
subjectId: course.id,
metadata: { title: course.title },
});
}
if (result.rowCount) log?.info({ count: result.rowCount }, 'Scheduled courses published');
} catch (error) {
await client.query('rollback');
throw error;
} finally {
client.release();
}
};
export const startScheduledPublisher = (log?: FastifyBaseLogger) => {
const run = () => {
void publishScheduledCourses(log).catch((error) => log?.error(error, 'Scheduled publisher failed'));
};
run();
const timer = setInterval(run, 60_000);
timer.unref?.();
return timer;
};