feat: add reviews, notifications, notes and account hardening
This commit is contained in:
@@ -15,6 +15,7 @@ import { profileRoutes } from './routes/profiles.js';
|
||||
import { savedCourseRoutes } from './routes/saved-courses.js';
|
||||
import { downloadRoutes } from './routes/downloads.js';
|
||||
import { searchRoutes } from './routes/search.js';
|
||||
import { notificationRoutes } from './routes/notifications.js';
|
||||
|
||||
export function buildApp() {
|
||||
const app = Fastify({ logger: true, trustProxy: true });
|
||||
@@ -25,6 +26,7 @@ export function buildApp() {
|
||||
app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (request, body, done) => {
|
||||
const rawBody = Buffer.isBuffer(body) ? body : Buffer.from(body);
|
||||
(request as typeof request & { rawBody?: Buffer }).rawBody = rawBody;
|
||||
if (rawBody.length === 0) return done(null, undefined);
|
||||
try {
|
||||
done(null, JSON.parse(rawBody.toString('utf8')));
|
||||
} catch {
|
||||
@@ -86,6 +88,7 @@ export function buildApp() {
|
||||
app.register(savedCourseRoutes, { prefix: '/api/v1/saved-courses' });
|
||||
app.register(downloadRoutes, { prefix: '/api/v1/downloads' });
|
||||
app.register(searchRoutes, { prefix: '/api/v1/search' });
|
||||
app.register(notificationRoutes, { prefix: '/api/v1/notifications' });
|
||||
app.register(manageCourseRoutes, { prefix: '/api/v1/manage/courses' });
|
||||
app.register(mediaRoutes, { prefix: '/api/v1/manage/media' });
|
||||
app.register(bunnyWebhookRoutes, { prefix: '/api/v1/webhooks' });
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface AuthUser {
|
||||
email: string;
|
||||
role: UserRole;
|
||||
name: string;
|
||||
tokenVersion: number;
|
||||
}
|
||||
|
||||
declare module '@fastify/jwt' {
|
||||
@@ -38,8 +39,8 @@ const registerAuth: FastifyPluginAsync = async (app) => {
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = await pool.query<{ role: UserRole; display_name: string }>(
|
||||
'select role, display_name from users where id = $1 and is_active = true',
|
||||
const result = await pool.query<{ role: UserRole; display_name: string; token_version: number }>(
|
||||
'select role, display_name, token_version from users where id = $1 and is_active = true',
|
||||
[request.user.id],
|
||||
);
|
||||
const account = result.rows[0];
|
||||
@@ -48,8 +49,14 @@ const registerAuth: FastifyPluginAsync = async (app) => {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((request.user.tokenVersion ?? 0) !== account.token_version) {
|
||||
reply.code(401).send({ error: 'Sua sessão expirou. Entre novamente.' });
|
||||
return false;
|
||||
}
|
||||
|
||||
request.user.role = account.role;
|
||||
request.user.name = account.display_name;
|
||||
request.user.tokenVersion = account.token_version;
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { pool } from '../db/pool.js';
|
||||
import { createRawToken, hashToken } from '../auth/account-tokens.js';
|
||||
import { config } from '../config.js';
|
||||
import { recordAudit } from '../audit.js';
|
||||
import { sendInvitationEmail, sendPasswordResetEmail } from '../services/email.js';
|
||||
|
||||
const userParamsSchema = z.object({
|
||||
userId: z.string().uuid(),
|
||||
@@ -373,7 +374,14 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
[input.email, input.role, hashToken(rawToken), config.INVITATION_TTL_HOURS, request.user.id],
|
||||
);
|
||||
await recordAudit({ actorId: request.user.id, action: 'invitation.created', subjectType: 'invitation', metadata: { email: input.email, role: input.role }, ipAddress: request.ip });
|
||||
return reply.code(201).send({ data: { inviteUrl: `${config.FRONTEND_ORIGIN}/invite?token=${rawToken}` } });
|
||||
const inviteUrl = `${config.FRONTEND_ORIGIN}/invite?token=${rawToken}`;
|
||||
try {
|
||||
const sent = await sendInvitationEmail({ email: input.email, inviteUrl });
|
||||
if (!sent && config.SMTP_HOST) request.log.warn({ email: input.email }, 'Invitation email was rejected by the SMTP server');
|
||||
} catch (error) {
|
||||
request.log.error(error, 'Invitation email could not be sent');
|
||||
}
|
||||
return reply.code(201).send({ data: { inviteUrl } });
|
||||
});
|
||||
|
||||
app.post('/users/:userId/password-reset', adminAccess, async (request, reply) => {
|
||||
@@ -387,7 +395,14 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
[account.rows[0].email, account.rows[0].role, hashToken(rawToken), config.PASSWORD_RESET_TTL_HOURS, request.user.id],
|
||||
);
|
||||
await recordAudit({ actorId: request.user.id, action: 'password_reset.created', subjectType: 'user', subjectId: userId, metadata: { email: account.rows[0].email }, ipAddress: request.ip });
|
||||
return { data: { resetUrl: `${config.FRONTEND_ORIGIN}/reset-password?token=${rawToken}` } };
|
||||
const resetUrl = `${config.FRONTEND_ORIGIN}/reset-password?token=${rawToken}`;
|
||||
try {
|
||||
const sent = await sendPasswordResetEmail({ email: account.rows[0].email, resetUrl });
|
||||
if (!sent && config.SMTP_HOST) request.log.warn({ email: account.rows[0].email }, 'Password reset email was rejected by the SMTP server');
|
||||
} catch (error) {
|
||||
request.log.error(error, 'Password reset email could not be sent');
|
||||
}
|
||||
return { data: { resetUrl } };
|
||||
});
|
||||
|
||||
app.patch('/users/:userId', adminAccess, async (request, reply) => {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { hashPassword, verifyPassword } from '../auth/passwords.js';
|
||||
import { hashToken } from '../auth/account-tokens.js';
|
||||
import { createRawToken, hashToken } from '../auth/account-tokens.js';
|
||||
import type { AuthUser } from '../auth/plugin.js';
|
||||
import { pool } from '../db/pool.js';
|
||||
import { config } from '../config.js';
|
||||
import { sendWelcomeEmail } from '../services/email.js';
|
||||
import { sendPasswordResetEmail, sendWelcomeEmail } from '../services/email.js';
|
||||
|
||||
const credentialsSchema = z.object({
|
||||
email: z.string().email().transform((email) => email.toLowerCase()),
|
||||
@@ -16,6 +16,9 @@ const registerSchema = credentialsSchema.extend({
|
||||
name: z.string().trim().min(2).max(120),
|
||||
});
|
||||
const tokenPasswordSchema = z.object({ token: z.string().min(20), password: z.string().min(8).max(200), name: z.string().trim().min(2).max(120).optional() });
|
||||
const forgotPasswordSchema = z.object({
|
||||
email: z.string().email().transform((email) => email.toLowerCase()),
|
||||
});
|
||||
|
||||
type UserRow = {
|
||||
id: string;
|
||||
@@ -24,6 +27,7 @@ type UserRow = {
|
||||
role: AuthUser['role'];
|
||||
password_hash: string;
|
||||
is_active: boolean;
|
||||
token_version: number;
|
||||
};
|
||||
|
||||
const serializeUser = (user: UserRow): AuthUser => ({
|
||||
@@ -31,6 +35,7 @@ const serializeUser = (user: UserRow): AuthUser => ({
|
||||
email: user.email,
|
||||
name: user.display_name,
|
||||
role: user.role,
|
||||
tokenVersion: user.token_version,
|
||||
});
|
||||
|
||||
export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
@@ -78,7 +83,7 @@ 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`,
|
||||
returning id, email, display_name, role, password_hash, is_active, token_version`,
|
||||
[token.rows[0].email, await hashPassword(input.password), input.name, token.rows[0].role],
|
||||
);
|
||||
await client.query('commit');
|
||||
@@ -107,7 +112,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
await client.query('rollback');
|
||||
return reply.code(400).send({ error: 'Este link de redefinição é inválido ou expirou.' });
|
||||
}
|
||||
await client.query('update users set password_hash = $2 where email = $1', [token.rows[0].email, await hashPassword(input.password)]);
|
||||
await client.query('update users set password_hash = $2, token_version = token_version + 1 where email = $1', [token.rows[0].email, await hashPassword(input.password)]);
|
||||
await client.query('commit');
|
||||
return reply.code(204).send();
|
||||
} catch (error) {
|
||||
@@ -117,6 +122,34 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
app.post('/forgot-password', async (request, reply) => {
|
||||
if (await rejectIfRateLimited(request.ip, reply)) return;
|
||||
const input = forgotPasswordSchema.parse(request.body);
|
||||
const account = await pool.query<{ id: string; role: AuthUser['role'] }>(
|
||||
'select id, role from users where email = $1 and is_active = true',
|
||||
[input.email],
|
||||
);
|
||||
|
||||
// Always answer 204 so the endpoint cannot be used to enumerate accounts.
|
||||
if (account.rows[0]) {
|
||||
const rawToken = createRawToken();
|
||||
await pool.query(
|
||||
`insert into account_access_tokens (email, role, purpose, token_hash, expires_at, created_by)
|
||||
values ($1, $2::user_role, 'password_reset', $3, now() + ($4::int * interval '1 hour'), $5)`,
|
||||
[input.email, account.rows[0].role, hashToken(rawToken), config.PASSWORD_RESET_TTL_HOURS, account.rows[0].id],
|
||||
);
|
||||
const resetUrl = `${config.FRONTEND_ORIGIN}/reset-password?token=${rawToken}`;
|
||||
try {
|
||||
const sent = await sendPasswordResetEmail({ email: input.email, resetUrl });
|
||||
if (!sent && config.SMTP_HOST) request.log.warn({ email: input.email }, 'Password reset email was rejected by the SMTP server');
|
||||
} catch (error) {
|
||||
request.log.error(error, 'Password reset email could not be sent');
|
||||
}
|
||||
}
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.post('/register', async (request, reply) => {
|
||||
if (await rejectIfRateLimited(request.ip, reply)) return;
|
||||
const input = registerSchema.parse(request.body);
|
||||
@@ -126,7 +159,7 @@ 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`,
|
||||
returning id, email, display_name, role, password_hash, is_active, token_version`,
|
||||
[input.email, passwordHash, input.name],
|
||||
);
|
||||
const user = serializeUser(result.rows[0]);
|
||||
@@ -150,7 +183,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 from users where email = $1`,
|
||||
`select id, email, display_name, role, password_hash, is_active, token_version from users where email = $1`,
|
||||
[input.email],
|
||||
);
|
||||
const account = result.rows[0];
|
||||
|
||||
@@ -15,6 +15,10 @@ const coverParamsSchema = z.object({
|
||||
filename: z.string().regex(/^[0-9a-f]{8}-[0-9a-f-]{27}\.(?:jpg|png|webp)$/i),
|
||||
});
|
||||
const assetParamsSchema = z.object({ assetId: z.string().uuid() });
|
||||
const reviewSchema = z.object({
|
||||
rating: z.number().int().min(1).max(5),
|
||||
comment: z.string().trim().max(2000).default(''),
|
||||
});
|
||||
|
||||
export const courseSelect = (publicOnly = false, includeUnreadyMedia = false) => `
|
||||
select
|
||||
@@ -117,6 +121,31 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
|
||||
}
|
||||
};
|
||||
|
||||
const publishedCourseExists = async (courseId: string) => {
|
||||
const result = await pool.query("select 1 from courses where id = $1 and status = 'published'", [courseId]);
|
||||
return result.rowCount === 1;
|
||||
};
|
||||
|
||||
const reviewSummary = async (courseId: string) => {
|
||||
const [summary, reviews] = await Promise.all([
|
||||
pool.query<{ average: number; count: number }>(
|
||||
`select coalesce(avg(rating)::float8, 0) as average, count(*)::int as count
|
||||
from course_reviews where course_id = $1`,
|
||||
[courseId],
|
||||
),
|
||||
pool.query<{ rating: number; comment: string; updatedAt: string; userName: string }>(
|
||||
`select r.rating, r.comment, r.updated_at as "updatedAt", u.display_name as "userName"
|
||||
from course_reviews r
|
||||
join users u on u.id = r.user_id
|
||||
where r.course_id = $1
|
||||
order by r.updated_at desc
|
||||
limit 30`,
|
||||
[courseId],
|
||||
),
|
||||
]);
|
||||
return { ...summary.rows[0], reviews: reviews.rows };
|
||||
};
|
||||
|
||||
app.get('/categories', async () => {
|
||||
const result = await pool.query<{ name: string }>(`select name from course_categories where is_active order by position, name`);
|
||||
return { data: result.rows.map((row) => row.name) };
|
||||
@@ -272,17 +301,66 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
app.get('/me/learning/stats', { preHandler: app.authenticate }, async (request) => {
|
||||
const [summary, days] = await Promise.all([
|
||||
pool.query<{ watchedSeconds: number; completedLessons: number; activeCourses: number; weeklyCompleted: number }>(
|
||||
`select coalesce(sum(lp.watched_seconds), 0)::int as "watchedSeconds",
|
||||
count(*) filter (where lp.completed_at is not null)::int as "completedLessons",
|
||||
count(distinct l.course_id)::int as "activeCourses",
|
||||
count(*) filter (where lp.completed_at >= date_trunc('week', now()))::int as "weeklyCompleted"
|
||||
from lesson_progress lp
|
||||
join lessons l on l.id = lp.lesson_id
|
||||
join courses c on c.id = l.course_id and c.status = 'published'
|
||||
where lp.user_id = $1`,
|
||||
[request.user.id],
|
||||
),
|
||||
pool.query<{ day: string }>(
|
||||
`select distinct to_char(lp.updated_at at time zone 'America/Sao_Paulo', 'YYYY-MM-DD') as day
|
||||
from lesson_progress lp
|
||||
join lessons l on l.id = lp.lesson_id
|
||||
join courses c on c.id = l.course_id and c.status = 'published'
|
||||
where lp.user_id = $1
|
||||
order by day desc
|
||||
limit 90`,
|
||||
[request.user.id],
|
||||
),
|
||||
]);
|
||||
|
||||
const dayKeys = new Set(days.rows.map((row) => row.day));
|
||||
const keyFor = (date: Date) => new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Sao_Paulo' }).format(date);
|
||||
let cursor = new Date();
|
||||
if (!dayKeys.has(keyFor(cursor))) cursor = new Date(cursor.getTime() - 86_400_000);
|
||||
let streakDays = 0;
|
||||
while (dayKeys.has(keyFor(cursor))) {
|
||||
streakDays += 1;
|
||||
cursor = new Date(cursor.getTime() - 86_400_000);
|
||||
}
|
||||
|
||||
return { data: { ...summary.rows[0], streakDays } };
|
||||
});
|
||||
|
||||
app.post('/:courseId/view', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
const result = await pool.query<{ views: number }>(
|
||||
`update courses
|
||||
set view_count = view_count + 1
|
||||
where id = $1 and status = 'published'
|
||||
returning view_count as views`,
|
||||
[courseId],
|
||||
const course = await pool.query("select id from courses where id = $1 and status = 'published'", [courseId]);
|
||||
if (!course.rowCount) return reply.code(404).send({ error: 'Curso não encontrado.' });
|
||||
|
||||
const inserted = await pool.query(
|
||||
`insert into course_views (course_id, user_id) values ($1, $2)
|
||||
on conflict (course_id, user_id, viewed_on) do nothing
|
||||
returning course_id`,
|
||||
[courseId, request.user.id],
|
||||
);
|
||||
if (!result.rows[0]) return reply.code(404).send({ error: 'Curso não encontrado.' });
|
||||
return { data: result.rows[0] };
|
||||
|
||||
if (inserted.rowCount) {
|
||||
const updated = await pool.query<{ views: number }>(
|
||||
`update courses set view_count = view_count + 1 where id = $1 returning view_count as views`,
|
||||
[courseId],
|
||||
);
|
||||
return { data: updated.rows[0] };
|
||||
}
|
||||
|
||||
const current = await pool.query<{ views: number }>('select view_count as views from courses where id = $1', [courseId]);
|
||||
return { data: current.rows[0] };
|
||||
});
|
||||
|
||||
app.get('/:courseId', async (request, reply) => {
|
||||
@@ -298,6 +376,43 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
|
||||
return { data: authenticated ? course : withoutProtectedMedia(course) };
|
||||
});
|
||||
|
||||
app.get('/:courseId/reviews', async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
if (!(await publishedCourseExists(courseId))) return reply.code(404).send({ error: 'Curso não encontrado.' });
|
||||
return { data: await reviewSummary(courseId) };
|
||||
});
|
||||
|
||||
app.get('/:courseId/reviews/mine', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
if (!(await publishedCourseExists(courseId))) return reply.code(404).send({ error: 'Curso não encontrado.' });
|
||||
const result = await pool.query<{ rating: number; comment: string; updatedAt: string }>(
|
||||
`select rating, comment, updated_at as "updatedAt" from course_reviews
|
||||
where course_id = $1 and user_id = $2`,
|
||||
[courseId, request.user.id],
|
||||
);
|
||||
return { data: result.rows[0] || null };
|
||||
});
|
||||
|
||||
app.put('/:courseId/reviews/mine', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
const input = reviewSchema.parse(request.body);
|
||||
if (!(await publishedCourseExists(courseId))) return reply.code(404).send({ error: 'Curso não encontrado.' });
|
||||
const result = await pool.query<{ rating: number; comment: string; updatedAt: string }>(
|
||||
`insert into course_reviews (user_id, course_id, rating, comment)
|
||||
values ($1, $2, $3, $4)
|
||||
on conflict (user_id, course_id) do update set rating = excluded.rating, comment = excluded.comment, updated_at = now()
|
||||
returning rating, comment, updated_at as "updatedAt"`,
|
||||
[request.user.id, courseId, input.rating, input.comment],
|
||||
);
|
||||
return { data: { review: result.rows[0], summary: await reviewSummary(courseId) } };
|
||||
});
|
||||
|
||||
app.delete('/:courseId/reviews/mine', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
await pool.query('delete from course_reviews where course_id = $1 and user_id = $2', [courseId, request.user.id]);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.get('/:courseId/lessons/:lessonId/playback', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { courseId, lessonId } = playbackParamsSchema.parse(request.params);
|
||||
const result = await pool.query<{
|
||||
|
||||
@@ -22,6 +22,7 @@ const commentSchema = z.object({
|
||||
});
|
||||
const commentParamsSchema = z.object({ commentId: z.string().uuid() });
|
||||
const replySchema = z.object({ text: z.string().trim().min(1).max(4000) });
|
||||
const noteSchema = z.object({ body: z.string().max(20_000) });
|
||||
const communityQuerySchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
@@ -42,6 +43,54 @@ const canViewCourseComments = async (courseId: string, user: { id: string; role:
|
||||
};
|
||||
|
||||
export const learningRoutes: FastifyPluginAsync = async (app) => {
|
||||
const createNotification = async (input: { userId: string; kind: string; title: string; body: string; href: string }) => {
|
||||
await pool.query(
|
||||
'insert into notifications (user_id, kind, title, body, href) values ($1, $2, $3, $4, $5)',
|
||||
[input.userId, input.kind, input.title, input.body, input.href],
|
||||
);
|
||||
};
|
||||
|
||||
const lessonAccessible = async (lessonId: string, user: { id: string; role: string }) => {
|
||||
const result = await pool.query(
|
||||
`select l.id
|
||||
from lessons l
|
||||
join courses c on c.id = l.course_id
|
||||
where l.id = $1 and (c.status = 'published' or c.instructor_id = $2 or $3 = 'admin')`,
|
||||
[lessonId, user.id, user.role],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
};
|
||||
|
||||
app.get('/lessons/:lessonId/note', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { lessonId } = lessonParamsSchema.parse(request.params);
|
||||
if (!(await lessonAccessible(lessonId, request.user))) return reply.code(404).send({ error: 'Aula não encontrada.' });
|
||||
const result = await pool.query<{ body: string; updatedAt: string | null }>(
|
||||
'select body, updated_at as "updatedAt" from lesson_notes where user_id = $1 and lesson_id = $2',
|
||||
[request.user.id, lessonId],
|
||||
);
|
||||
return { data: result.rows[0] || { body: '', updatedAt: null } };
|
||||
});
|
||||
|
||||
app.put('/lessons/:lessonId/note', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { lessonId } = lessonParamsSchema.parse(request.params);
|
||||
const input = noteSchema.parse(request.body);
|
||||
if (!(await lessonAccessible(lessonId, request.user))) return reply.code(404).send({ error: 'Aula não encontrada.' });
|
||||
const result = await pool.query<{ body: string; updatedAt: string }>(
|
||||
`insert into lesson_notes (user_id, lesson_id, body)
|
||||
values ($1, $2, $3)
|
||||
on conflict (user_id, lesson_id) do update set body = excluded.body, updated_at = now()
|
||||
returning body, updated_at as "updatedAt"`,
|
||||
[request.user.id, lessonId, input.body],
|
||||
);
|
||||
return { data: result.rows[0] };
|
||||
});
|
||||
|
||||
app.delete('/lessons/:lessonId/note', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { lessonId } = lessonParamsSchema.parse(request.params);
|
||||
await pool.query('delete from lesson_notes where user_id = $1 and lesson_id = $2', [request.user.id, lessonId]);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// Public, paginated feed used by the community screen. Individual course
|
||||
// threads remain authenticated because they are part of the lesson area.
|
||||
app.get('/community/comments', async (request) => {
|
||||
@@ -165,6 +214,26 @@ export const learningRoutes: FastifyPluginAsync = async (app) => {
|
||||
join users u on u.id = $3`,
|
||||
[courseId, input.lessonId || null, request.user.id, input.text],
|
||||
);
|
||||
|
||||
const course = await pool.query<{ instructorId: string; title: string }>(
|
||||
'select instructor_id as "instructorId", title from courses where id = $1',
|
||||
[courseId],
|
||||
);
|
||||
const owner = course.rows[0];
|
||||
if (owner && owner.instructorId !== request.user.id) {
|
||||
try {
|
||||
await createNotification({
|
||||
userId: owner.instructorId,
|
||||
kind: 'question',
|
||||
title: `Nova pergunta em ${owner.title}`,
|
||||
body: `${request.user.name}: ${input.text.slice(0, 180)}`,
|
||||
href: input.lessonId ? `/cursos/${courseId}/aulas/${input.lessonId}` : '/comunidade',
|
||||
});
|
||||
} catch (error) {
|
||||
request.log.error(error, 'Could not create question notification');
|
||||
}
|
||||
}
|
||||
|
||||
return reply.code(201).send({ data: result.rows[0] });
|
||||
});
|
||||
|
||||
@@ -178,6 +247,28 @@ export const learningRoutes: FastifyPluginAsync = async (app) => {
|
||||
on conflict (comment_id) do update set author_id = excluded.author_id, body = excluded.body`,
|
||||
[commentId, request.user.id, input.text],
|
||||
);
|
||||
const target = await pool.query<{ authorId: string; courseId: string; lessonId: string | null; courseTitle: string }>(
|
||||
`select c.author_id as "authorId", c.course_id as "courseId", c.lesson_id as "lessonId", co.title as "courseTitle"
|
||||
from comments c
|
||||
join courses co on co.id = c.course_id
|
||||
where c.id = $1`,
|
||||
[commentId],
|
||||
);
|
||||
const comment = target.rows[0];
|
||||
if (comment && comment.authorId !== request.user.id) {
|
||||
try {
|
||||
await createNotification({
|
||||
userId: comment.authorId,
|
||||
kind: 'reply',
|
||||
title: 'Seu comentário recebeu uma resposta',
|
||||
body: `${request.user.name}: ${input.text.slice(0, 180)}`,
|
||||
href: comment.lessonId ? `/cursos/${comment.courseId}/aulas/${comment.lessonId}` : '/comunidade',
|
||||
});
|
||||
} catch (error) {
|
||||
request.log.error(error, 'Could not create reply notification');
|
||||
}
|
||||
}
|
||||
|
||||
await recordAudit({ actorId: request.user.id, action: 'comment.replied', subjectType: 'comment', subjectId: commentId, ipAddress: request.ip });
|
||||
return { data: { id: commentId } };
|
||||
});
|
||||
|
||||
36
server/src/routes/notifications.ts
Normal file
36
server/src/routes/notifications.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { pool } from '../db/pool.js';
|
||||
|
||||
const notificationParamsSchema = z.object({ notificationId: z.string().uuid() });
|
||||
|
||||
export const notificationRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/', { preHandler: app.authenticate }, async (request) => {
|
||||
const [items, unread] = await Promise.all([
|
||||
pool.query<{ id: string; kind: string; title: string; body: string; href: string; readAt: string | null; createdAt: string }>(
|
||||
`select id, kind, title, body, href, read_at as "readAt", created_at as "createdAt"
|
||||
from notifications
|
||||
where user_id = $1
|
||||
order by created_at desc
|
||||
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],
|
||||
),
|
||||
]);
|
||||
return { data: { items: items.rows, unread: unread.rows[0].count } };
|
||||
});
|
||||
|
||||
app.post('/read-all', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
await pool.query('update notifications set read_at = now() where user_id = $1 and read_at is null', [request.user.id]);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
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]);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
};
|
||||
@@ -1,23 +1,43 @@
|
||||
import { config } from '../config.js';
|
||||
import nodemailer from 'nodemailer';
|
||||
|
||||
type WelcomeRecipient = { name: string; email: string };
|
||||
const isConfigured = () => Boolean(config.SMTP_HOST && config.SMTP_PORT && config.SMTP_USER && config.SMTP_PASS && config.MAIL_FROM);
|
||||
|
||||
export async function sendWelcomeEmail(recipient: WelcomeRecipient) {
|
||||
if (!config.SMTP_HOST || !config.SMTP_PORT || !config.SMTP_USER || !config.SMTP_PASS || !config.MAIL_FROM) return false;
|
||||
|
||||
const escapedName = recipient.name.replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[character] || character));
|
||||
const sendEmail = async (to: string, subject: string, html: string) => {
|
||||
if (!isConfigured()) return false;
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: config.SMTP_HOST,
|
||||
port: config.SMTP_PORT,
|
||||
secure: config.SMTP_PORT === 465,
|
||||
auth: { user: config.SMTP_USER, pass: config.SMTP_PASS },
|
||||
});
|
||||
await transporter.sendMail({
|
||||
from: config.MAIL_FROM,
|
||||
to: recipient.email,
|
||||
subject: 'Bem-vindo(a) ao Compor HUB',
|
||||
html: `<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Bem-vindo(a), ${escapedName}!</h1><p>Sua conta no <strong>Compor HUB</strong> já está pronta.</p><p>Agora você pode acessar cursos, acompanhar suas aulas e baixar materiais complementares.</p><p><a href="${config.FRONTEND_ORIGIN}" style="display:inline-block;background:#f97316;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Acessar Compor HUB</a></p></main>`,
|
||||
});
|
||||
await transporter.sendMail({ from: config.MAIL_FROM, to, subject, html });
|
||||
return true;
|
||||
};
|
||||
|
||||
const escapeHtml = (value: string) => value.replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[character] || character));
|
||||
|
||||
export async function sendWelcomeEmail(recipient: { name: string; email: string }) {
|
||||
const escapedName = escapeHtml(recipient.name);
|
||||
return sendEmail(
|
||||
recipient.email,
|
||||
'Bem-vindo(a) ao Compor HUB',
|
||||
`<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Bem-vindo(a), ${escapedName}!</h1><p>Sua conta no <strong>Compor HUB</strong> já está pronta.</p><p>Agora você pode acessar cursos, acompanhar suas aulas e baixar materiais complementares.</p><p><a href="${config.FRONTEND_ORIGIN}" style="display:inline-block;background:#0a84ff;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Acessar Compor HUB</a></p></main>`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function sendInvitationEmail(recipient: { email: string; inviteUrl: string }) {
|
||||
return sendEmail(
|
||||
recipient.email,
|
||||
'Você foi convidado para o Compor HUB',
|
||||
`<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Convite para o Compor HUB</h1><p>Você recebeu acesso como professor à plataforma.</p><p>Defina seu nome e sua senha para começar.</p><p><a href="${recipient.inviteUrl}" style="display:inline-block;background:#0a84ff;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Aceitar convite</a></p><p style="color:#6e6e73;font-size:13px">Este link expira em ${config.INVITATION_TTL_HOURS} horas.</p></main>`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function sendPasswordResetEmail(recipient: { email: string; resetUrl: string }) {
|
||||
return sendEmail(
|
||||
recipient.email,
|
||||
'Redefinição de senha do Compor HUB',
|
||||
`<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Redefinir senha</h1><p>Recebemos um pedido para redefinir a senha da sua conta.</p><p><a href="${recipient.resetUrl}" style="display:inline-block;background:#0a84ff;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Escolher nova senha</a></p><p style="color:#6e6e73;font-size:13px">Se você não pediu isso, ignore este e-mail. O link expira em ${config.PASSWORD_RESET_TTL_HOURS} horas.</p></main>`,
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user