feat: app de alumnos sin contraseña (invitación de un solo uso, avisos de falta y pagos informados)
- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys opcionales (SimpleWebAuthn) y mail de recuperación con rate limit. - Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta, pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil. - Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar), "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de grupo y datos para transferir en Ajustes. - "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas. - Zona horaria por defecto: Buenos Aires. - Migración add_student_access, tests contra Postgres real (test:db) y docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,7 @@ import { invitationsRoutes } from './modules/invitations';
|
||||
import { mpRoutes } from './modules/mp';
|
||||
import { onboardingRoutes } from './modules/onboarding';
|
||||
import { paymentsRoutes } from './modules/payments';
|
||||
import { studentPortalRoutes } from './modules/student-portal';
|
||||
import { waitlistRoutes } from './modules/waitlist';
|
||||
import { whatsappRoutes } from './modules/whatsapp';
|
||||
|
||||
@@ -67,6 +68,7 @@ api.route('/classes', classesRoutes);
|
||||
api.route('/students', studentStatusRoutes);
|
||||
api.route('/groups-risk', groupsRiskOverviewRoute);
|
||||
api.route('/attention', attentionRoutes);
|
||||
api.route('/student-portal', studentPortalRoutes);
|
||||
|
||||
app.notFound((c) => {
|
||||
return problemJson(c, notFoundProblem(c.req.path));
|
||||
|
||||
@@ -2,11 +2,15 @@ import type { auth } from '@/modules/auth/auth';
|
||||
|
||||
type AuthSession = typeof auth.$Infer.Session;
|
||||
|
||||
/** Signed-in student (attendee or guardian): set only on /student-portal. */
|
||||
export type StudentContext = { accountId: string; sessionId: string };
|
||||
|
||||
export type BackendEnv = {
|
||||
Variables: {
|
||||
user: AuthSession['user'] | null;
|
||||
session: AuthSession['session'] | null;
|
||||
requestId: string;
|
||||
student: StudentContext | null;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -15,5 +19,6 @@ declare module 'hono' {
|
||||
user: AuthSession['user'] | null;
|
||||
session: AuthSession['session'] | null;
|
||||
requestId: string;
|
||||
student: StudentContext | null;
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,9 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/auth')
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/auth')
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/invitations')
|
||||
// Student app: its own cookie and middleware (modules/student-portal), never
|
||||
// the teacher's session.
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/student-portal')
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,15 @@ import nodemailer, { type Transporter } from 'nodemailer'
|
||||
type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||
type StudentEmailConfirmationData = { email: string; url: string; name: string }
|
||||
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
|
||||
type StudentPaymentReviewedData = {
|
||||
email: string
|
||||
name: string
|
||||
confirmed: boolean
|
||||
amount: string
|
||||
reason?: string | null
|
||||
}
|
||||
|
||||
// Brand colors (same system as the web app: index.css in apps/web).
|
||||
const BRAND_600 = '#2544ea'
|
||||
@@ -26,10 +35,27 @@ function loadLogoTypoDataUri(): string {
|
||||
|
||||
const LOGO_DATA_URI = loadLogoTypoDataUri()
|
||||
|
||||
interface EmailProvider {
|
||||
export interface EmailProvider {
|
||||
sendVerificationEmail(data: VerificationEmailData): Promise<void>
|
||||
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
|
||||
sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
|
||||
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
||||
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
||||
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
||||
}
|
||||
|
||||
// Names come from what teachers and students type: never raw into the HTML.
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function button(url: string, label: string): string {
|
||||
return `<a href="${escapeHtml(url)}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">${escapeHtml(label)}</a>`
|
||||
}
|
||||
|
||||
class SMTPEmailProvider implements EmailProvider {
|
||||
@@ -109,6 +135,47 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendStudentEmailConfirmation({ email, url, name }: StudentEmailConfirmationData) {
|
||||
await this.send(
|
||||
email,
|
||||
'Confirmá tu mail de recuperación en Gruperly',
|
||||
this.layout(
|
||||
'Confirmá tu mail',
|
||||
`Hola ${escapeHtml(name)}, confirmá este mail para poder pedir un link de ingreso si perdés el acceso a la app (el enlace vence en 24 horas). Si no fuiste vos, ignorá este mail.<br/><br/>${button(url, 'Confirmar mail')}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) {
|
||||
// A guardian may have one account per child with the same email: one button each.
|
||||
const buttons = links
|
||||
.map((link) =>
|
||||
links.length > 1
|
||||
? `<p style="margin:12px 0 4px;">${escapeHtml(link.name)}</p>${button(link.url, 'Ingresar')}`
|
||||
: button(link.url, 'Ingresar'),
|
||||
)
|
||||
.join('<br/>')
|
||||
await this.send(
|
||||
email,
|
||||
'Tu link para ingresar a Gruperly',
|
||||
this.layout(
|
||||
'Tu link de ingreso',
|
||||
`Pediste un link para volver a entrar. Sirve una sola vez y vence en 15 minutos. Si no fuiste vos, ignorá este mail.<br/><br/>${buttons}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendStudentPaymentReviewed({ email, name, confirmed, amount, reason }: StudentPaymentReviewedData) {
|
||||
const body = confirmed
|
||||
? `Hola ${escapeHtml(name)}, tu profe confirmó el pago de ${escapeHtml(amount)}. ¡Gracias!`
|
||||
: `Hola ${escapeHtml(name)}, tu profe no pudo confirmar el pago de ${escapeHtml(amount)}.${reason ? `<br/><br/>Motivo: ${escapeHtml(reason)}` : ''}<br/><br/>Podés volver a informarlo desde la app.`
|
||||
await this.send(
|
||||
email,
|
||||
confirmed ? 'Tu pago fue confirmado' : 'Tu pago no fue confirmado',
|
||||
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||
|
||||
36
apps/backend/src/lib/file-type.ts
Normal file
36
apps/backend/src/lib/file-type.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/* Real type of an uploaded file from its first bytes (magic numbers), never
|
||||
from the name or the Content-Type the browser claims. */
|
||||
|
||||
export type ReceiptMime = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/heic' | 'application/pdf';
|
||||
|
||||
export const RECEIPT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
export const RECEIPT_EXTENSIONS: Record<ReceiptMime, string> = {
|
||||
'image/jpeg': 'jpg',
|
||||
'image/png': 'png',
|
||||
'image/webp': 'webp',
|
||||
'image/heic': 'heic',
|
||||
'application/pdf': 'pdf',
|
||||
};
|
||||
|
||||
// ISO-BMFF brands used by HEIC/HEIF photos (iPhone camera).
|
||||
const HEIF_BRANDS = new Set(['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1']);
|
||||
|
||||
function ascii(bytes: Uint8Array, start: number, length: number): string {
|
||||
return String.fromCharCode(...bytes.subarray(start, start + length));
|
||||
}
|
||||
|
||||
export function detectReceiptType(bytes: Uint8Array): ReceiptMime | null {
|
||||
if (bytes.length < 12) return null;
|
||||
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
|
||||
if (
|
||||
bytes[0] === 0x89 && ascii(bytes, 1, 3) === 'PNG'
|
||||
&& bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
|
||||
) {
|
||||
return 'image/png';
|
||||
}
|
||||
if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') return 'image/webp';
|
||||
if (ascii(bytes, 4, 4) === 'ftyp' && HEIF_BRANDS.has(ascii(bytes, 8, 4))) return 'image/heic';
|
||||
if (ascii(bytes, 0, 5) === '%PDF-') return 'application/pdf';
|
||||
return null;
|
||||
}
|
||||
54
apps/backend/src/lib/storage.ts
Normal file
54
apps/backend/src/lib/storage.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { S3Client } from 'bun';
|
||||
|
||||
/* Private file storage (payment receipts). Behind a port, like the WhatsApp and
|
||||
billing providers: the use-cases never talk to S3 directly, and the tests
|
||||
inject an in-memory fake. Objects are never public; the teacher sees them
|
||||
through short-lived signed URLs. */
|
||||
export interface FileStorage {
|
||||
put(key: string, body: Uint8Array, contentType: string): Promise<void>;
|
||||
/** GET URL valid for `expiresInSeconds`. */
|
||||
signedUrl(key: string, expiresInSeconds: number): string;
|
||||
remove(key: string): Promise<void>;
|
||||
}
|
||||
|
||||
/* Any S3-compatible service (RustFS, MinIO, R2, AWS). Path-style addressing by
|
||||
default, which is what self-hosted services expect; S3_VIRTUAL_HOSTED=on for
|
||||
AWS-style bucket subdomains. */
|
||||
class S3FileStorage implements FileStorage {
|
||||
constructor(private readonly client: S3Client) {}
|
||||
|
||||
async put(key: string, body: Uint8Array, contentType: string): Promise<void> {
|
||||
await this.client.write(key, body, { type: contentType });
|
||||
}
|
||||
|
||||
signedUrl(key: string, expiresInSeconds: number): string {
|
||||
return this.client.presign(key, { method: 'GET', expiresIn: expiresInSeconds });
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await this.client.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
let storage: FileStorage | null | undefined;
|
||||
|
||||
/** null when S3 isn't configured: the endpoints that need it answer 503. */
|
||||
export function getFileStorage(): FileStorage | null {
|
||||
if (storage !== undefined) return storage;
|
||||
const { S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY } = process.env;
|
||||
if (!S3_ENDPOINT || !S3_BUCKET || !S3_ACCESS_KEY_ID || !S3_SECRET_ACCESS_KEY) {
|
||||
storage = null;
|
||||
return storage;
|
||||
}
|
||||
storage = new S3FileStorage(
|
||||
new S3Client({
|
||||
endpoint: S3_ENDPOINT,
|
||||
bucket: S3_BUCKET,
|
||||
region: process.env.S3_REGION || 'us-east-1',
|
||||
accessKeyId: S3_ACCESS_KEY_ID,
|
||||
secretAccessKey: S3_SECRET_ACCESS_KEY,
|
||||
virtualHostedStyle: process.env.S3_VIRTUAL_HOSTED === 'on',
|
||||
}),
|
||||
);
|
||||
return storage;
|
||||
}
|
||||
@@ -102,7 +102,14 @@ export class GetAttentionOverview {
|
||||
},
|
||||
}) as Promise<AttendanceRow[]>,
|
||||
db.payment.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'OVERDUE', attendee: { status: 'ACTIVE' } },
|
||||
where: {
|
||||
groupId: { in: groupIds },
|
||||
status: 'OVERDUE',
|
||||
attendee: { status: 'ACTIVE' },
|
||||
// A fee the student reported (with a receipt) is out of the alert while
|
||||
// the teacher reviews it; a rejection brings it back.
|
||||
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
|
||||
},
|
||||
select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true },
|
||||
orderBy: { dueDate: 'asc' },
|
||||
}) as Promise<PaymentRow[]>,
|
||||
|
||||
@@ -10,6 +10,7 @@ import updateAttendeeRoute from '../attendees/features/update/route';
|
||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
||||
import { studentAccessRoutes } from '../student-access';
|
||||
import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route';
|
||||
import createGroupRoute from './features/create/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
@@ -36,5 +37,6 @@ routes.route('/', getAttendeeRoute);
|
||||
routes.route('/', updateAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
routes.route('/', removeAttendeeRoute);
|
||||
routes.route('/', studentAccessRoutes);
|
||||
|
||||
export default routes;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { WeekDay } from '@gruperly/shared';
|
||||
|
||||
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Mexico_City';
|
||||
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Argentina/Buenos_Aires';
|
||||
|
||||
// Window (in hours) during which an already started class shows as "in progress".
|
||||
export const CLASS_WINDOW_HOURS = 2;
|
||||
@@ -185,4 +185,50 @@ export function todayOccurrence(opt: {
|
||||
export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
|
||||
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
||||
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);
|
||||
}
|
||||
}
|
||||
// Every class start of a group within [from, to), in `timeZone`. Empty when the
|
||||
// group has no valid schedule.
|
||||
export function occurrencesBetween(opt: {
|
||||
days: WeekDay[];
|
||||
time: string | null;
|
||||
from: Date;
|
||||
to: Date;
|
||||
timeZone: string;
|
||||
}): Date[] {
|
||||
const { days, time, from, to, timeZone } = opt;
|
||||
if (days.length === 0 || !time) return [];
|
||||
const [hour, minute] = time.split(':').map(Number);
|
||||
if (
|
||||
Number.isNaN(hour) ||
|
||||
Number.isNaN(minute) ||
|
||||
hour < 0 ||
|
||||
hour > 23 ||
|
||||
minute < 0 ||
|
||||
minute > 59
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dowSet = new Set(days.map((day) => WEEKDAY_TO_DOW[day]));
|
||||
const { year, month, day } = wallDateInTimeZone(from, timeZone);
|
||||
const result: Date[] = [];
|
||||
// One extra day on each side covers the time zone offset.
|
||||
const spanDays = Math.ceil((to.getTime() - from.getTime()) / (24 * 60 * 60 * 1000)) + 1;
|
||||
for (let offset = -1; offset <= spanDays; offset++) {
|
||||
const candidateDay = new Date(Date.UTC(year, month - 1, day + offset));
|
||||
if (!dowSet.has(candidateDay.getUTCDay())) continue;
|
||||
const wall = `${candidateDay.toISOString().slice(0, 10)}T${pad(hour)}:${pad(minute)}`;
|
||||
const startsAt = zonedWallClockToUtc(wall, timeZone);
|
||||
if (startsAt >= from && startsAt < to) result.push(startsAt);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Monday 00:00 of `now`'s week in `timeZone`.
|
||||
export function startOfWeekInTimeZone(now: Date, timeZone: string): Date {
|
||||
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
||||
const date = new Date(Date.UTC(year, month - 1, day));
|
||||
const sinceMonday = (date.getUTCDay() + 6) % 7;
|
||||
const monday = new Date(Date.UTC(year, month - 1, day - sinceMonday));
|
||||
return zonedWallClockToUtc(`${monday.toISOString().slice(0, 10)}T00:00`, timeZone);
|
||||
}
|
||||
|
||||
40
apps/backend/src/modules/payments/features/reported/route.ts
Normal file
40
apps/backend/src/modules/payments/features/reported/route.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { type RejectReportedPayment, RejectReportedPaymentSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ReportedPayments } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/reported', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().list(user.id));
|
||||
});
|
||||
|
||||
route.get('/reported/:reportId/receipt', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().receiptUrl(user.id, c.req.param('reportId')));
|
||||
});
|
||||
|
||||
route.post('/reported/:reportId/confirm', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().confirm(user.id, c.req.param('reportId')));
|
||||
});
|
||||
|
||||
route.post('/reported/:reportId/reject', validate.json(RejectReportedPaymentSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
const { reason } = c.req.valid('json') as RejectReportedPayment;
|
||||
return resultJson(c, await new ReportedPayments().reject(user.id, c.req.param('reportId'), reason ?? null));
|
||||
});
|
||||
|
||||
route.post('/reported/:reportId/undo', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().undo(user.id, c.req.param('reportId')));
|
||||
});
|
||||
|
||||
export default route;
|
||||
226
apps/backend/src/modules/payments/features/reported/use-case.ts
Normal file
226
apps/backend/src/modules/payments/features/reported/use-case.ts
Normal file
@@ -0,0 +1,226 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, ReceiptUrlDto, ReportedPaymentDto, ReportedPaymentList, Result } from '@gruperly/shared';
|
||||
import { err, ok, REVIEW_UNDO_MINUTES } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { type FileStorage, getFileStorage } from '@/lib/storage';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems';
|
||||
import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments';
|
||||
import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications';
|
||||
|
||||
export const RECEIPT_URL_TTL_SECONDS = 5 * 60;
|
||||
const PREVIEWABLE = new Set(['image/jpeg', 'image/png', 'image/webp']);
|
||||
|
||||
type ReportedDeps = {
|
||||
db?: Pick<PrismaClient, 'reportedPayment'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
storage?: FileStorage | null;
|
||||
notify?: ReviewNotifier;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const reportSelect = {
|
||||
id: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
totalAmount: true,
|
||||
currency: true,
|
||||
receiptKey: true,
|
||||
receiptMime: true,
|
||||
receiptName: true,
|
||||
receiptSize: true,
|
||||
attendee: { select: { id: true, fullName: true } },
|
||||
group: { select: { id: true, name: true } },
|
||||
items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } },
|
||||
} satisfies Prisma.ReportedPaymentSelect;
|
||||
|
||||
type ReportRow = Prisma.ReportedPaymentGetPayload<{ select: typeof reportSelect }>;
|
||||
|
||||
const STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const;
|
||||
|
||||
function accessible(userId: string): Prisma.ReportedPaymentWhereInput {
|
||||
return { group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput };
|
||||
}
|
||||
|
||||
/* Cobros → "Pagos para verificar": reports waiting for the teacher, across
|
||||
their groups, oldest first. */
|
||||
export class ReportedPayments {
|
||||
constructor(private readonly deps: ReportedDeps = {}) {}
|
||||
|
||||
private get db() {
|
||||
return this.deps.db ?? prisma;
|
||||
}
|
||||
|
||||
private get storage(): FileStorage | null {
|
||||
return this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
|
||||
}
|
||||
|
||||
private get now(): Date {
|
||||
return this.deps.now ?? new Date();
|
||||
}
|
||||
|
||||
async list(userId: string): Promise<Result<ReportedPaymentList, ProblemDetails>> {
|
||||
const rows = await this.db.reportedPayment.findMany({
|
||||
where: { ...accessible(userId), status: 'REPORTED' },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: reportSelect,
|
||||
});
|
||||
return ok({ data: rows.map((row) => this.toDto(row)) });
|
||||
}
|
||||
|
||||
async receiptUrl(userId: string, reportId: string): Promise<Result<ReceiptUrlDto, ProblemDetails>> {
|
||||
const row = await this.db.reportedPayment.findFirst({
|
||||
where: { id: reportId, ...accessible(userId) },
|
||||
select: { receiptKey: true, receiptMime: true, receiptName: true },
|
||||
});
|
||||
if (!row?.receiptKey) return err(notFoundResourceProblem('Receipt', reportId));
|
||||
const storage = this.storage;
|
||||
if (!storage) return err(storageNotAvailableProblem());
|
||||
return ok({
|
||||
url: storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS),
|
||||
mime: row.receiptMime,
|
||||
name: row.receiptName,
|
||||
expiresAt: new Date(this.now.getTime() + RECEIPT_URL_TTL_SECONDS * 1000).toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
/* Confirm: the report and its fees become paid, in one transaction. A fee
|
||||
already PAID (e.g. through Mercado Pago meanwhile) is left as it is. */
|
||||
async confirm(userId: string, reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
return this.review(userId, reportId, 'CONFIRMED', null);
|
||||
}
|
||||
|
||||
/* Reject: the fees stay as they were, and they come back to the overdue alert. */
|
||||
async reject(userId: string, reportId: string, reason: string | null): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
return this.review(userId, reportId, 'REJECTED', reason);
|
||||
}
|
||||
|
||||
/* "Deshacer", for a few minutes after the review: back to REPORTED. A confirm
|
||||
is reverted only on the fees it paid (paid_at equal to the review and no MP
|
||||
payment), which go back to PENDING or OVERDUE by the overdue job's rule. */
|
||||
async undo(userId: string, reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
const now = this.now;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const undone = await unitOfWork.executeResult(async (tx) => {
|
||||
const report = await tx.reportedPayment.findFirst({
|
||||
where: {
|
||||
id: reportId,
|
||||
...accessible(userId),
|
||||
status: { in: ['CONFIRMED', 'REJECTED'] },
|
||||
reviewedAt: { gt: new Date(now.getTime() - REVIEW_UNDO_MINUTES * 60 * 1000) },
|
||||
},
|
||||
select: { status: true, reviewedAt: true, items: { select: { paymentId: true } } },
|
||||
});
|
||||
if (!report?.reviewedAt) {
|
||||
return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' }));
|
||||
}
|
||||
const claimed = await tx.reportedPayment.updateMany({
|
||||
where: { id: reportId, status: report.status, reviewedAt: report.reviewedAt },
|
||||
data: { status: 'REPORTED', reviewedAt: null, reviewedById: null, rejectionReason: null },
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' }));
|
||||
}
|
||||
if (report.status === 'CONFIRMED') {
|
||||
const paidByReview = {
|
||||
id: { in: report.items.map((item) => item.paymentId) },
|
||||
status: 'PAID' as const,
|
||||
paidAt: report.reviewedAt,
|
||||
mpPaymentId: null,
|
||||
};
|
||||
const overdueBefore = new Date(now.getTime() - OVERDUE_GRACE_MS);
|
||||
await tx.payment.updateMany({
|
||||
where: { ...paidByReview, dueDate: { lt: overdueBefore } },
|
||||
data: { status: 'OVERDUE', paidAt: null },
|
||||
});
|
||||
await tx.payment.updateMany({
|
||||
where: { ...paidByReview, dueDate: { gte: overdueBefore } },
|
||||
data: { status: 'PENDING', paidAt: null },
|
||||
});
|
||||
}
|
||||
return ok(null);
|
||||
});
|
||||
if (!undone.ok) return undone;
|
||||
return this.load(reportId);
|
||||
}
|
||||
|
||||
private async review(
|
||||
userId: string,
|
||||
reportId: string,
|
||||
status: 'CONFIRMED' | 'REJECTED',
|
||||
reason: string | null,
|
||||
): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
const now = this.now;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
|
||||
const reviewed = await unitOfWork.executeResult(async (tx) => {
|
||||
const claimed = await tx.reportedPayment.updateMany({
|
||||
where: { id: reportId, ...accessible(userId), status: 'REPORTED' },
|
||||
data: {
|
||||
status,
|
||||
reviewedById: userId,
|
||||
reviewedAt: now,
|
||||
rejectionReason: status === 'REJECTED' ? reason || null : null,
|
||||
},
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
const exists = await tx.reportedPayment.findFirst({ where: { id: reportId, ...accessible(userId) }, select: { id: true } });
|
||||
return err(
|
||||
exists
|
||||
? conflictProblem({ detail: 'Este pago ya fue revisado.', code: 'payment_report_already_reviewed' })
|
||||
: notFoundResourceProblem('ReportedPayment', reportId),
|
||||
);
|
||||
}
|
||||
if (status === 'CONFIRMED') {
|
||||
const items = await tx.reportedPaymentItem.findMany({ where: { reportedPaymentId: reportId }, select: { paymentId: true } });
|
||||
await tx.payment.updateMany({
|
||||
where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||
data: { status: 'PAID', paidAt: now },
|
||||
});
|
||||
}
|
||||
return ok(null);
|
||||
});
|
||||
if (!reviewed.ok) return reviewed;
|
||||
|
||||
(this.deps.notify ?? scheduleReviewNotification)(reportId, now);
|
||||
return this.load(reportId);
|
||||
}
|
||||
|
||||
private async load(reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
const row = await this.db.reportedPayment.findUniqueOrThrow({ where: { id: reportId }, select: reportSelect });
|
||||
return ok(this.toDto(row));
|
||||
}
|
||||
|
||||
private toDto(row: ReportRow): ReportedPaymentDto {
|
||||
const storage = this.storage;
|
||||
const thumbnailUrl =
|
||||
row.receiptKey && storage && PREVIEWABLE.has(row.receiptMime)
|
||||
? storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS)
|
||||
: null;
|
||||
return {
|
||||
id: row.id,
|
||||
status: STATUS[row.status],
|
||||
attendee: row.attendee,
|
||||
group: row.group,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
totalAmount: row.totalAmount.toNumber(),
|
||||
currency: row.currency,
|
||||
fees: row.items
|
||||
.map(({ payment }) => ({
|
||||
id: payment.id,
|
||||
description: payment.description,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
amount: payment.amount.toNumber(),
|
||||
}))
|
||||
.sort((a, b) => a.dueDate.localeCompare(b.dueDate)),
|
||||
receipt: {
|
||||
mime: row.receiptMime,
|
||||
name: row.receiptName,
|
||||
size: row.receiptSize,
|
||||
thumbnailUrl,
|
||||
available: row.receiptKey !== null,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { type UpdateTransferDetails, UpdateTransferDetailsSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
/* Bank transfer details (Ajustes) that students see when reporting a payment. */
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/transfer-details', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
const row = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: user.id },
|
||||
select: { transferAlias: true, transferHolder: true },
|
||||
});
|
||||
return c.json({ alias: row.transferAlias, holder: row.transferHolder });
|
||||
});
|
||||
|
||||
route.put('/transfer-details', validate.json(UpdateTransferDetailsSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
const { alias, holder } = c.req.valid('json') as UpdateTransferDetails;
|
||||
const row = await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { transferAlias: alias || null, transferHolder: holder || null },
|
||||
select: { transferAlias: true, transferHolder: true },
|
||||
});
|
||||
return c.json({ alias: row.transferAlias, holder: row.transferHolder });
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -6,7 +6,7 @@ import prisma from '@/lib/prisma';
|
||||
* is still PENDING becomes OVERDUE; it stays billable, so the professor can
|
||||
* renew its link from Cobros.
|
||||
*/
|
||||
const GRACE_MS = 24 * 60 * 60 * 1000;
|
||||
export const OVERDUE_GRACE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export type MarkOverduePaymentsResult = {
|
||||
marked: number;
|
||||
@@ -23,7 +23,7 @@ export class MarkOverduePayments {
|
||||
async execute(): Promise<MarkOverduePaymentsResult> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const horizon = new Date(now.getTime() - GRACE_MS);
|
||||
const horizon = new Date(now.getTime() - OVERDUE_GRACE_MS);
|
||||
|
||||
const updated = await db.payment.updateMany({
|
||||
where: { status: 'PENDING', dueDate: { lt: horizon } },
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { CountryCode } from '@gruperly/shared';
|
||||
import { type EmailProvider, emailProvider } from '@/lib/email';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { formatAmount } from '@/modules/whatsapp/lib/format';
|
||||
|
||||
// Long enough to cover the "Deshacer" on the card: an undone review emails nothing.
|
||||
const NOTIFY_DELAY_MS = 60 * 1000;
|
||||
|
||||
export type ReviewNotifier = (reportId: string, reviewedAt: Date) => void;
|
||||
|
||||
/* Tells the student by email (only if they confirmed a recovery email) once
|
||||
the review settles. The in-app banner is the main channel; this is a
|
||||
courtesy, so an in-process timer lost on a restart is acceptable. */
|
||||
export const scheduleReviewNotification: ReviewNotifier = (reportId, reviewedAt) => {
|
||||
const timer = setTimeout(() => {
|
||||
void sendReviewNotification(reportId, reviewedAt).catch((error) =>
|
||||
logger.error({ error, reportId }, 'Payment review notification failed'),
|
||||
);
|
||||
}, NOTIFY_DELAY_MS);
|
||||
timer.unref?.();
|
||||
};
|
||||
|
||||
export async function sendReviewNotification(
|
||||
reportId: string,
|
||||
reviewedAt: Date,
|
||||
deps: { db?: Pick<PrismaClient, 'reportedPayment'>; email?: Pick<EmailProvider, 'sendStudentPaymentReviewed'> } = {},
|
||||
): Promise<boolean> {
|
||||
const db = deps.db ?? prisma;
|
||||
const report = await db.reportedPayment.findUnique({
|
||||
where: { id: reportId },
|
||||
select: {
|
||||
status: true,
|
||||
reviewedAt: true,
|
||||
rejectionReason: true,
|
||||
totalAmount: true,
|
||||
currency: true,
|
||||
group: { select: { owner: { select: { country: true } } } },
|
||||
account: { select: { name: true, recoveryEmail: true, recoveryEmailVerifiedAt: true } },
|
||||
},
|
||||
});
|
||||
// Undone or reviewed again since: this notification is stale.
|
||||
if (!report || report.status === 'REPORTED' || report.reviewedAt?.getTime() !== reviewedAt.getTime()) return false;
|
||||
const account = report.account;
|
||||
if (!account?.recoveryEmail || !account.recoveryEmailVerifiedAt) return false;
|
||||
|
||||
await (deps.email ?? emailProvider).sendStudentPaymentReviewed({
|
||||
email: account.recoveryEmail,
|
||||
name: account.name,
|
||||
confirmed: report.status === 'CONFIRMED',
|
||||
amount: formatAmount(report.totalAmount.toNumber(), report.currency, report.group.owner.country as CountryCode | null),
|
||||
reason: report.rejectionReason,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import { Hono } from 'hono';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import renewRoute from './features/renew/route';
|
||||
import reportedRoute from './features/reported/route';
|
||||
import transferDetailsRoute from './features/transfer-details/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getAllRoute);
|
||||
routes.route('/', reportedRoute);
|
||||
routes.route('/', transferDetailsRoute);
|
||||
routes.route('/', renewRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { GetStudentAccess } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/:groupId/attendees/:attendeeId/student-access', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const result = await new GetStudentAccess().execute(
|
||||
c.req.param('groupId'),
|
||||
c.req.param('attendeeId'),
|
||||
user.id,
|
||||
);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, StudentAccessDto } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { computeStudentAccess } from '../../lib/status';
|
||||
|
||||
type GetStudentAccessDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export class GetStudentAccess {
|
||||
constructor(private readonly deps: GetStudentAccessDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
): Promise<Result<StudentAccessDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { id: true } });
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
return ok(await computeStudentAccess(db, attendeeId, this.deps.now ?? new Date()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { InviteStudent } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/attendees/:attendeeId/student-access/invite', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const result = await new InviteStudent().execute(
|
||||
c.req.param('groupId'),
|
||||
c.req.param('attendeeId'),
|
||||
user.id,
|
||||
);
|
||||
return resultJson(c, result, { status: 201 });
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
|
||||
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
||||
import { computeStudentAccess } from '../../lib/status';
|
||||
|
||||
type InviteStudentDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
/* "Invitar" / "Reinvitar": reinviting restarts the access. It revokes every
|
||||
pending link and every session and removes the passkeys (a lost phone must not
|
||||
keep a way in), then issues a fresh 72 h single-use link. The welcome screen
|
||||
shows again on the next sign-in so the student can add a passkey back. The
|
||||
raw token only leaves here, inside the URL: the database keeps its hash. */
|
||||
export class InviteStudent {
|
||||
constructor(private readonly deps: InviteStudentDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
): Promise<Result<StudentInvitationDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
phone: true,
|
||||
guardianPhone: true,
|
||||
group: { select: { owner: { select: { country: true } } } },
|
||||
},
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
const token = generateAccessToken();
|
||||
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
|
||||
const issued = await unitOfWork.executeResult(async (tx) => {
|
||||
const link = await tx.studentAccountAttendee.findFirst({
|
||||
where: { attendeeId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { accountId: true },
|
||||
});
|
||||
const accountId =
|
||||
link?.accountId
|
||||
?? (
|
||||
await tx.studentAccount.create({
|
||||
data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } },
|
||||
select: { id: true },
|
||||
})
|
||||
).id;
|
||||
|
||||
await tx.studentAccessToken.updateMany({
|
||||
where: { accountId, usedAt: null, revokedAt: null },
|
||||
data: { revokedAt: now },
|
||||
});
|
||||
await tx.studentSession.updateMany({
|
||||
where: { accountId, revokedAt: null },
|
||||
data: { revokedAt: now },
|
||||
});
|
||||
await tx.studentPasskey.deleteMany({ where: { accountId } });
|
||||
await tx.studentAccount.update({ where: { id: accountId }, data: { welcomedAt: null } });
|
||||
await tx.studentAccessToken.create({
|
||||
data: {
|
||||
accountId,
|
||||
kind: 'INVITATION',
|
||||
tokenHash: hashToken(token),
|
||||
expiresAt,
|
||||
createdById: userId,
|
||||
createdAt: now,
|
||||
},
|
||||
});
|
||||
return ok(accountId);
|
||||
});
|
||||
if (!issued.ok) return issued;
|
||||
|
||||
return ok({
|
||||
url: studentLinkUrl(token),
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
whatsappPhone: toWhatsappPhone(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country),
|
||||
access: await computeStudentAccess(db, attendeeId, now),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
|
||||
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { ListGroupAbsenceNotices } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/:groupId/absence-notices', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
return resultJson(c, await new ListGroupAbsenceNotices().execute(c.req.param('groupId'), user.id));
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, TeacherAbsenceNoticeList } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
||||
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
|
||||
|
||||
const REASON = { HEALTH: 'health', TRAVEL: 'travel', WORK_STUDY: 'work_study', OTHER: 'other' } as const;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
type ListAbsenceNoticesDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'user' | 'absenceNotice'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
/* "Faltas avisadas · esta semana" on the group card: active notices for this
|
||||
week's classes (Monday to Sunday on the teacher's clock). */
|
||||
export class ListGroupAbsenceNotices {
|
||||
constructor(private readonly deps: ListAbsenceNoticesDeps = {}) {}
|
||||
|
||||
async execute(groupId: string, userId: string): Promise<Result<TeacherAbsenceNoticeList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const owner = await db.user.findUnique({ where: { id: access.value.createdById }, select: { country: true } });
|
||||
const timeZone = teacherTimeZone(owner?.country);
|
||||
const from = startOfWeekInTimeZone(now, timeZone);
|
||||
const to = startOfWeekInTimeZone(new Date(from.getTime() + 8 * DAY_MS), timeZone);
|
||||
|
||||
const notices = await db.absenceNotice.findMany({
|
||||
where: { cancelledAt: null, classSession: { groupId, startsAt: { gte: from, lt: to } } },
|
||||
orderBy: [{ classSession: { startsAt: 'asc' } }, { createdAt: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
reason: true,
|
||||
message: true,
|
||||
createdAt: true,
|
||||
attendee: { select: { id: true, fullName: true } },
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
data: notices.map((notice) => ({
|
||||
id: notice.id,
|
||||
attendee: notice.attendee,
|
||||
startsAt: notice.classSession.startsAt.toISOString(),
|
||||
reason: notice.reason ? REASON[notice.reason] : null,
|
||||
message: notice.message,
|
||||
createdAt: notice.createdAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
2
apps/backend/src/modules/student-access/index.ts
Normal file
2
apps/backend/src/modules/student-access/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { startStudentAccessJobs } from './jobs/cleanup';
|
||||
export { default as studentAccessRoutes } from './routes';
|
||||
95
apps/backend/src/modules/student-access/jobs/cleanup.ts
Normal file
95
apps/backend/src/modules/student-access/jobs/cleanup.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type FileStorage, getFileStorage } from '@/lib/storage';
|
||||
import { logger } from '@/logger';
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const BATCH = 100;
|
||||
|
||||
type CleanupDeps = {
|
||||
db?: Pick<PrismaClient, 'reportedPayment' | 'studentAccessToken' | 'studentWebauthnChallenge' | 'rateLimitEvent' | 'studentSession'>;
|
||||
storage?: FileStorage | null;
|
||||
now?: Date;
|
||||
/** Days a receipt is kept after the teacher reviewed it; 0 keeps it forever. */
|
||||
retentionDays?: number;
|
||||
};
|
||||
|
||||
export function receiptRetentionDays(): number {
|
||||
const parsed = Number(process.env.RECEIPT_RETENTION_DAYS ?? 0);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;
|
||||
}
|
||||
|
||||
/* Daily housekeeping of the student access:
|
||||
- Receipt retention: deletes the files of reports reviewed more than
|
||||
RECEIPT_RETENTION_DAYS ago (the row stays, without `receipt_key`). Reports
|
||||
still waiting for the teacher are never touched.
|
||||
- Drops dead tokens, challenges, rate limit hits and sessions after a grace
|
||||
period (they only matter for the audit while they are recent). */
|
||||
export class StudentAccessCleanup {
|
||||
constructor(private readonly deps: CleanupDeps = {}) {}
|
||||
|
||||
async execute() {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const storage = this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
|
||||
const retentionDays = this.deps.retentionDays ?? receiptRetentionDays();
|
||||
|
||||
let receiptsDeleted = 0;
|
||||
if (retentionDays > 0 && storage) {
|
||||
const before = new Date(now.getTime() - retentionDays * DAY_MS);
|
||||
for (;;) {
|
||||
const rows = await db.reportedPayment.findMany({
|
||||
where: { status: { in: ['CONFIRMED', 'REJECTED'] }, reviewedAt: { lt: before }, receiptKey: { not: null } },
|
||||
select: { id: true, receiptKey: true },
|
||||
take: BATCH,
|
||||
});
|
||||
if (rows.length === 0) break;
|
||||
for (const row of rows) {
|
||||
try {
|
||||
await storage.remove(row.receiptKey as string);
|
||||
await db.reportedPayment.update({ where: { id: row.id }, data: { receiptKey: null } });
|
||||
receiptsDeleted++;
|
||||
} catch (error) {
|
||||
logger.warn({ error, reportId: row.id }, 'Receipt retention: file could not be removed');
|
||||
}
|
||||
}
|
||||
if (rows.length < BATCH) break;
|
||||
}
|
||||
}
|
||||
|
||||
const monthAgo = new Date(now.getTime() - 30 * DAY_MS);
|
||||
const [tokens, challenges, hits, sessions] = await Promise.all([
|
||||
db.studentAccessToken.deleteMany({ where: { expiresAt: { lt: monthAgo } } }),
|
||||
db.studentWebauthnChallenge.deleteMany({ where: { expiresAt: { lt: now } } }),
|
||||
db.rateLimitEvent.deleteMany({ where: { createdAt: { lt: new Date(now.getTime() - DAY_MS) } } }),
|
||||
db.studentSession.deleteMany({
|
||||
where: { OR: [{ expiresAt: { lt: monthAgo } }, { revokedAt: { lt: monthAgo } }] },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
receiptsDeleted,
|
||||
tokensDeleted: tokens.count,
|
||||
challengesDeleted: challenges.count,
|
||||
rateLimitHitsDeleted: hits.count,
|
||||
sessionsDeleted: sessions.count,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const CLEANUP_CRON = '23 5 * * *';
|
||||
|
||||
/** Registered from server.ts, with the same guards as the other jobs. */
|
||||
export function startStudentAccessJobs(): void {
|
||||
Bun.cron(
|
||||
CLEANUP_CRON,
|
||||
async () => {
|
||||
try {
|
||||
logger.info(await new StudentAccessCleanup().execute(), 'Student access cleanup finished');
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Student access cleanup failed');
|
||||
}
|
||||
},
|
||||
{ tz: 'UTC' },
|
||||
).unref();
|
||||
}
|
||||
70
apps/backend/src/modules/student-access/lib/status.ts
Normal file
70
apps/backend/src/modules/student-access/lib/status.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { StudentAccessDto } from '@gruperly/shared';
|
||||
|
||||
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountAttendee'>;
|
||||
|
||||
/* Passive state for the attendee's card: active (a live session) > invited
|
||||
(a pending invitation) > expired (invited before, nothing alive) > not invited. */
|
||||
export async function computeStudentAccess(
|
||||
db: StudentAccessStatusDb,
|
||||
attendeeId: string,
|
||||
now: Date,
|
||||
): Promise<StudentAccessDto> {
|
||||
const link = await db.studentAccountAttendee.findFirst({
|
||||
where: { attendeeId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
account: {
|
||||
select: {
|
||||
_count: { select: { passkeys: true } },
|
||||
sessions: {
|
||||
where: { revokedAt: null, expiresAt: { gt: now } },
|
||||
orderBy: { lastUsedAt: 'desc' },
|
||||
select: { device: true, createdAt: true, lastUsedAt: true },
|
||||
},
|
||||
tokens: {
|
||||
where: { kind: 'INVITATION' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 1,
|
||||
select: { usedAt: true, revokedAt: true, expiresAt: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!link) {
|
||||
return { status: 'not_invited', invitationExpiresAt: null, devices: [], hasPasskey: false };
|
||||
}
|
||||
|
||||
const { account } = link;
|
||||
const devices = account.sessions.map((session) => ({
|
||||
device: session.device,
|
||||
createdAt: session.createdAt.toISOString(),
|
||||
lastUsedAt: session.lastUsedAt.toISOString(),
|
||||
}));
|
||||
const hasPasskey = account._count.passkeys > 0;
|
||||
const lastInvitation = account.tokens[0] ?? null;
|
||||
const pending =
|
||||
lastInvitation && !lastInvitation.usedAt && !lastInvitation.revokedAt && lastInvitation.expiresAt > now
|
||||
? lastInvitation
|
||||
: null;
|
||||
|
||||
if (devices.length > 0) {
|
||||
return { status: 'active', invitationExpiresAt: null, devices, hasPasskey };
|
||||
}
|
||||
if (pending) {
|
||||
return {
|
||||
status: 'invited',
|
||||
invitationExpiresAt: pending.expiresAt.toISOString(),
|
||||
devices,
|
||||
hasPasskey,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: lastInvitation ? 'expired' : 'not_invited',
|
||||
invitationExpiresAt: null,
|
||||
devices,
|
||||
hasPasskey,
|
||||
};
|
||||
}
|
||||
15
apps/backend/src/modules/student-access/routes.ts
Normal file
15
apps/backend/src/modules/student-access/routes.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Hono } from 'hono';
|
||||
import getStatusRoute from './features/get-status/route';
|
||||
import inviteRoute from './features/invite/route';
|
||||
import listAbsenceNoticesRoute from './features/list-absence-notices/route';
|
||||
|
||||
// Teacher side of the student access. Hooked into modules/groups/routes.ts:
|
||||
// it hangs from /groups/:groupId (absence notices) and
|
||||
// /groups/:groupId/attendees/:attendeeId (access).
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getStatusRoute);
|
||||
routes.route('/', inviteRoute);
|
||||
routes.route('/', listAbsenceNoticesRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -0,0 +1,148 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
CreateAbsenceNotices,
|
||||
CreateAbsenceNoticesResult,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { validationProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { absenceReleaseHours, registerAbsence } from '@/modules/classes/lib';
|
||||
import { occurrencesBetween } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
classAlreadyStartedProblem,
|
||||
findLinkedAttendee,
|
||||
studentAttendeeNotFoundProblem,
|
||||
teacherTimeZone,
|
||||
} from '../../lib';
|
||||
import { ABSENCE_REASON_TO_DB, horizonEnd } from '../classes/use-case';
|
||||
|
||||
type AbsenceDb = Pick<
|
||||
PrismaClient,
|
||||
'attendee' | 'classSession' | 'absenceNotice' | 'attendance' | 'slotRelease'
|
||||
>;
|
||||
|
||||
type AbsenceDeps = {
|
||||
db?: AbsenceDb;
|
||||
unitOfWork?: UnitOfWork;
|
||||
now?: Date;
|
||||
releaseHours?: number;
|
||||
};
|
||||
|
||||
/* "No voy a ir": only before the class starts, only for real classes of the
|
||||
attendee's group. Each class goes through the same `registerAbsence` the
|
||||
teacher and the old absence link use (EXCUSED + spot release), so an excused
|
||||
absence doesn't count for the attendance risk rules. Classes already
|
||||
notified are skipped (idempotent). */
|
||||
export class NotifyStudentAbsences {
|
||||
constructor(private readonly deps: AbsenceDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
accountId: string,
|
||||
input: CreateAbsenceNotices,
|
||||
): Promise<Result<CreateAbsenceNoticesResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
||||
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||
|
||||
const timeZone = teacherTimeZone(attendee.group.owner.country);
|
||||
const valid = new Set(
|
||||
occurrencesBetween({
|
||||
days: attendee.group.days,
|
||||
time: attendee.group.time,
|
||||
from: now,
|
||||
to: horizonEnd(now),
|
||||
timeZone,
|
||||
}).map((date) => date.getTime()),
|
||||
);
|
||||
|
||||
const requested = [...new Set(input.startsAt.map((value) => new Date(value).getTime()))];
|
||||
for (const time of requested) {
|
||||
if (time <= now.getTime()) return err(classAlreadyStartedProblem());
|
||||
if (!valid.has(time)) {
|
||||
return err(validationProblem({ detail: 'Una de las clases elegidas no es del grupo.' }));
|
||||
}
|
||||
}
|
||||
|
||||
const notified: CreateAbsenceNoticesResult['notified'] = [];
|
||||
for (const time of requested.sort((a, b) => a - b)) {
|
||||
const startsAt = new Date(time);
|
||||
const session = await db.classSession.upsert({
|
||||
where: { groupId_startsAt: { groupId: attendee.groupId, startsAt } },
|
||||
create: { groupId: attendee.groupId, startsAt },
|
||||
update: {},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const existing = await db.absenceNotice.findFirst({
|
||||
where: { attendeeId: attendee.id, classSessionId: session.id, cancelledAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) continue;
|
||||
|
||||
const registered = await registerAbsence(
|
||||
{ db, unitOfWork },
|
||||
{
|
||||
attendeeId: attendee.id,
|
||||
classSessionId: session.id,
|
||||
now,
|
||||
releaseHours: this.deps.releaseHours ?? absenceReleaseHours(),
|
||||
},
|
||||
);
|
||||
if (!registered.ok) return registered;
|
||||
|
||||
const notice = await db.absenceNotice.create({
|
||||
data: {
|
||||
attendeeId: attendee.id,
|
||||
classSessionId: session.id,
|
||||
accountId,
|
||||
reason: input.reason ? ABSENCE_REASON_TO_DB[input.reason] : null,
|
||||
message: input.message || null,
|
||||
createdAt: now,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
notified.push({ id: notice.id, startsAt: startsAt.toISOString() });
|
||||
}
|
||||
|
||||
return ok({ notified });
|
||||
}
|
||||
}
|
||||
|
||||
/* "Deshacer": while the class hasn't started. Undoes what the notice did: the
|
||||
EXCUSED mark and the released spot, if nobody claimed it. */
|
||||
export class CancelStudentAbsence {
|
||||
constructor(private readonly deps: AbsenceDeps = {}) {}
|
||||
|
||||
async execute(accountId: string, noticeId: string): Promise<Result<{ id: string }, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const notice = await db.absenceNotice.findFirst({
|
||||
where: {
|
||||
id: noticeId,
|
||||
cancelledAt: null,
|
||||
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } },
|
||||
},
|
||||
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
||||
});
|
||||
if (!notice) return err(studentAttendeeNotFoundProblem());
|
||||
if (notice.classSession.startsAt <= now) return err(classAlreadyStartedProblem());
|
||||
|
||||
return unitOfWork.executeResult(async (tx) => {
|
||||
await tx.absenceNotice.update({ where: { id: notice.id }, data: { cancelledAt: now } });
|
||||
await tx.attendance.deleteMany({
|
||||
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, status: 'EXCUSED' },
|
||||
});
|
||||
await tx.slotRelease.deleteMany({
|
||||
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, isClaimed: false },
|
||||
});
|
||||
return ok({ id: notice.id });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
type CreateAbsenceNotices,
|
||||
CreateAbsenceNoticesSchema,
|
||||
type StudentAttendeeQuery,
|
||||
StudentAttendeeQuerySchema,
|
||||
} from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { currentStudent, studentSession } from '../../middleware';
|
||||
import { CancelStudentAbsence, NotifyStudentAbsences } from '../absences/use-case';
|
||||
import { GetStudentClasses } from './use-case';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
route.get('/classes', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery;
|
||||
return resultJson(c, await new GetStudentClasses().execute(accountId, attendeeId));
|
||||
});
|
||||
|
||||
route.post('/absences', studentSession, validate.json(CreateAbsenceNoticesSchema), async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
const input = c.req.valid('json') as CreateAbsenceNotices;
|
||||
return resultJson(c, await new NotifyStudentAbsences().execute(accountId, input), { status: 201 });
|
||||
});
|
||||
|
||||
route.delete('/absences/:noticeId', studentSession, async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
return resultJson(c, await new CancelStudentAbsence().execute(accountId, c.req.param('noticeId')));
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AbsenceReasonValue, ProblemDetails, Result, StudentClassesDto } from '@gruperly/shared';
|
||||
import { ABSENCE_NOTICE_HORIZON_DAYS, err, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
||||
import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib';
|
||||
|
||||
type GetStudentClassesDeps = {
|
||||
db?: Pick<PrismaClient, 'attendee' | 'absenceNotice'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export const ABSENCE_REASON_TO_DB = {
|
||||
health: 'HEALTH',
|
||||
travel: 'TRAVEL',
|
||||
work_study: 'WORK_STUDY',
|
||||
other: 'OTHER',
|
||||
} as const;
|
||||
|
||||
const ABSENCE_REASON_FROM_DB: Record<string, AbsenceReasonValue> = {
|
||||
HEALTH: 'health',
|
||||
TRAVEL: 'travel',
|
||||
WORK_STUDY: 'work_study',
|
||||
OTHER: 'other',
|
||||
};
|
||||
|
||||
export function horizonEnd(now: Date): Date {
|
||||
return new Date(now.getTime() + ABSENCE_NOTICE_HORIZON_DAYS * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
/* Classes of this week (already started ones included, for "Esta semana") up
|
||||
to the notice horizon, with the student's active notice on each. Only the
|
||||
attendee's own data: never other members of the group. */
|
||||
export class GetStudentClasses {
|
||||
constructor(private readonly deps: GetStudentClassesDeps = {}) {}
|
||||
|
||||
async execute(accountId: string, attendeeId: string): Promise<Result<StudentClassesDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const attendee = await findLinkedAttendee(db, accountId, attendeeId);
|
||||
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||
|
||||
const timeZone = teacherTimeZone(attendee.group.owner.country);
|
||||
const from = startOfWeekInTimeZone(now, timeZone);
|
||||
const to = horizonEnd(now);
|
||||
const weekEndsAt = startOfWeekInTimeZone(new Date(from.getTime() + 8 * 24 * 60 * 60 * 1000), timeZone);
|
||||
const starts = occurrencesBetween({ days: attendee.group.days, time: attendee.group.time, from, to, timeZone });
|
||||
|
||||
const notices = await db.absenceNotice.findMany({
|
||||
where: {
|
||||
attendeeId,
|
||||
cancelledAt: null,
|
||||
classSession: { groupId: attendee.groupId, startsAt: { gte: from, lt: to } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
reason: true,
|
||||
message: true,
|
||||
createdAt: true,
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
});
|
||||
const noticeByStart = new Map(notices.map((notice) => [notice.classSession.startsAt.getTime(), notice]));
|
||||
|
||||
return ok({
|
||||
attendeeId,
|
||||
timeZone,
|
||||
weekEndsAt: weekEndsAt.toISOString(),
|
||||
classes: starts.map((startsAt) => {
|
||||
const notice = noticeByStart.get(startsAt.getTime());
|
||||
return {
|
||||
startsAt: startsAt.toISOString(),
|
||||
groupName: attendee.group.name,
|
||||
started: startsAt <= now,
|
||||
notice: notice
|
||||
? {
|
||||
id: notice.id,
|
||||
reason: notice.reason ? ABSENCE_REASON_FROM_DB[notice.reason] ?? null : null,
|
||||
message: notice.message,
|
||||
createdAt: notice.createdAt.toISOString(),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson } from '@/http/problem-details';
|
||||
import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib';
|
||||
import { ConsumeStudentLink } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/links/:token/consume', async (c) => {
|
||||
const result = await new ConsumeStudentLink().execute({
|
||||
token: c.req.param('token'),
|
||||
ip: clientIp(c),
|
||||
userAgent: userAgent(c),
|
||||
currentSessionToken: readStudentSessionCookie(c),
|
||||
});
|
||||
if (!result.ok) return problemJson(c, result.error);
|
||||
|
||||
writeStudentSessionCookie(c, result.value.sessionToken);
|
||||
return c.json({ firstLogin: result.value.firstLogin });
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import {
|
||||
createStudentSession,
|
||||
hashToken,
|
||||
revokeStudentSessionByToken,
|
||||
studentLinkInvalidProblem,
|
||||
} from '../../lib';
|
||||
|
||||
type ConsumeStudentLinkDeps = {
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type ConsumeStudentLinkInput = {
|
||||
token: string;
|
||||
ip: string | null;
|
||||
userAgent: string | null;
|
||||
/** Session cookie already on this device, if any: it is replaced. */
|
||||
currentSessionToken?: string;
|
||||
};
|
||||
|
||||
export type ConsumeStudentLinkOutput = { sessionToken: string; firstLogin: boolean };
|
||||
|
||||
/* POST of the link. The conditional update is what makes it single use: under
|
||||
concurrency Postgres re-checks `used_at IS NULL` after the first commit, so
|
||||
exactly one request gets count === 1 and the rest see a dead link. */
|
||||
export class ConsumeStudentLink {
|
||||
constructor(private readonly deps: ConsumeStudentLinkDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
input: ConsumeStudentLinkInput,
|
||||
): Promise<Result<ConsumeStudentLinkOutput, ProblemDetails>> {
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const now = this.deps.now ?? new Date();
|
||||
const tokenHash = hashToken(input.token);
|
||||
|
||||
return unitOfWork.executeResult(async (tx) => {
|
||||
const claimed = await tx.studentAccessToken.updateMany({
|
||||
where: {
|
||||
tokenHash,
|
||||
kind: { in: ['INVITATION', 'RECOVERY'] },
|
||||
usedAt: null,
|
||||
revokedAt: null,
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
data: { usedAt: now, usedIp: input.ip, usedUserAgent: input.userAgent },
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
return err(studentLinkInvalidProblem());
|
||||
}
|
||||
|
||||
const row = await tx.studentAccessToken.findUniqueOrThrow({
|
||||
where: { tokenHash },
|
||||
select: { accountId: true, account: { select: { welcomedAt: true } } },
|
||||
});
|
||||
|
||||
if (input.currentSessionToken) {
|
||||
await revokeStudentSessionByToken(tx, input.currentSessionToken, now);
|
||||
}
|
||||
const sessionToken = await createStudentSession(tx, {
|
||||
accountId: row.accountId,
|
||||
userAgent: input.userAgent,
|
||||
now,
|
||||
});
|
||||
|
||||
return ok({ sessionToken, firstLogin: row.account.welcomedAt === null });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { type StudentAttendeeQuery, StudentAttendeeQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { validationProblem } from '@/http/problem-builders';
|
||||
import { problemJson, resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||
import { currentStudent, studentSession } from '../../middleware';
|
||||
import { ReportStudentPayment } from '../payment-reports/use-case';
|
||||
import { GetStudentFees } from './use-case';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery;
|
||||
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
|
||||
});
|
||||
|
||||
// multipart/form-data: attendeeId, paymentIds (repeated) and file.
|
||||
route.post('/payment-reports', studentSession, async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
// Reject oversized bodies before buffering them (10 MB + room for the fields).
|
||||
const length = Number(c.req.header('Content-Length') ?? 0);
|
||||
if (length > RECEIPT_MAX_BYTES + 64 * 1024) {
|
||||
return problemJson(c, validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
|
||||
}
|
||||
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await c.req.formData();
|
||||
} catch {
|
||||
return problemJson(c, validationProblem({ detail: 'Invalid form data' }));
|
||||
}
|
||||
const attendeeId = form.get('attendeeId');
|
||||
const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0);
|
||||
const file = form.get('file');
|
||||
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
|
||||
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
|
||||
}
|
||||
|
||||
const result = await new ReportStudentPayment().execute(accountId, {
|
||||
attendeeId,
|
||||
paymentIds,
|
||||
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
|
||||
});
|
||||
return resultJson(c, result, { status: 201 });
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, StudentFeeStatus, StudentFeesDto } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
|
||||
import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib';
|
||||
|
||||
type GetStudentFeesDeps = {
|
||||
db?: Pick<PrismaClient, 'attendee' | 'payment' | 'reportedPayment'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const REPORTS_SHOWN = 10;
|
||||
|
||||
const REPORT_STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const;
|
||||
|
||||
/* Unpaid fees of the attendee and their latest reports. A fee inside a report
|
||||
the teacher hasn't reviewed shows as "reported" (the Payment row itself is
|
||||
not touched until the teacher confirms). */
|
||||
export class GetStudentFees {
|
||||
constructor(private readonly deps: GetStudentFeesDeps = {}) {}
|
||||
|
||||
async execute(accountId: string, attendeeId: string): Promise<Result<StudentFeesDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const attendee = await findLinkedAttendee(db, accountId, attendeeId);
|
||||
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||
const startOfToday = startOfDayInTimeZone(now, teacherTimeZone(attendee.group.owner.country));
|
||||
|
||||
const [payments, reports] = await Promise.all([
|
||||
db.payment.findMany({
|
||||
where: { attendeeId, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||
orderBy: { dueDate: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
description: true,
|
||||
amount: true,
|
||||
currency: true,
|
||||
dueDate: true,
|
||||
status: true,
|
||||
checkoutUrl: true,
|
||||
reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } },
|
||||
},
|
||||
}),
|
||||
db.reportedPayment.findMany({
|
||||
where: { attendeeId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: REPORTS_SHOWN,
|
||||
select: {
|
||||
id: true,
|
||||
totalAmount: true,
|
||||
currency: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
reviewedAt: true,
|
||||
rejectionReason: true,
|
||||
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const { transferAlias, transferHolder } = attendee.group.owner;
|
||||
return ok({
|
||||
attendeeId,
|
||||
fees: payments.map((payment) => {
|
||||
let status: StudentFeeStatus = 'pending';
|
||||
if (payment.reportedItems.length > 0) status = 'reported';
|
||||
else if (payment.status === 'OVERDUE' || payment.dueDate < startOfToday) status = 'overdue';
|
||||
return {
|
||||
id: payment.id,
|
||||
description: payment.description,
|
||||
amount: payment.amount.toNumber(),
|
||||
currency: payment.currency,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
status,
|
||||
checkoutUrl: payment.checkoutUrl,
|
||||
};
|
||||
}),
|
||||
transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null,
|
||||
reports: reports.map((report) => ({
|
||||
id: report.id,
|
||||
totalAmount: report.totalAmount.toNumber(),
|
||||
currency: report.currency,
|
||||
status: REPORT_STATUS[report.status],
|
||||
createdAt: report.createdAt.toISOString(),
|
||||
reviewedAt: report.reviewedAt?.toISOString() ?? null,
|
||||
rejectionReason: report.rejectionReason,
|
||||
fees: report.items.map(({ payment }) => ({
|
||||
id: payment.id,
|
||||
description: payment.description,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
})),
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { GetStudentLinkInfo } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/links/:token', async (c) => {
|
||||
const result = await new GetStudentLinkInfo().execute(c.req.param('token'));
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { hashToken } from '../../lib';
|
||||
|
||||
type GetStudentLinkInfoDeps = {
|
||||
db?: Pick<PrismaClient, 'studentAccessToken'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
||||
|
||||
/* GET of the link: only reads, never consumes (WhatsApp previews and link
|
||||
scanners open it). Every unusable link answers the same `invalid`. */
|
||||
export class GetStudentLinkInfo {
|
||||
constructor(private readonly deps: GetStudentLinkInfoDeps = {}) {}
|
||||
|
||||
async execute(token: string): Promise<Result<StudentLinkInfo, ProblemDetails>> {
|
||||
if (!TOKEN_PATTERN.test(token)) return ok({ status: 'invalid' });
|
||||
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const row = await db.studentAccessToken.findUnique({
|
||||
where: { tokenHash: hashToken(token) },
|
||||
select: {
|
||||
kind: true,
|
||||
usedAt: true,
|
||||
revokedAt: true,
|
||||
expiresAt: true,
|
||||
account: {
|
||||
select: {
|
||||
name: true,
|
||||
attendees: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 1,
|
||||
select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
!row
|
||||
|| row.kind === 'EMAIL_CONFIRMATION'
|
||||
|| row.usedAt
|
||||
|| row.revokedAt
|
||||
|| row.expiresAt <= now
|
||||
) {
|
||||
return ok({ status: 'invalid' });
|
||||
}
|
||||
|
||||
const group = row.account.attendees[0]?.attendee.group ?? null;
|
||||
return ok({
|
||||
status: 'valid',
|
||||
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
||||
name: row.account.name,
|
||||
teacherName: group?.owner.name ?? null,
|
||||
groupName: group?.name ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Hono } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { clearStudentSessionCookie } from '../../lib';
|
||||
import { currentStudent, studentSession } from '../../middleware';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
// Closes this device only. Reinviting from the teacher's side closes all of them.
|
||||
route.post('/logout', studentSession, async (c) => {
|
||||
const student = currentStudent(c);
|
||||
await prisma.studentSession.updateMany({
|
||||
where: { id: student.sessionId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
clearStudentSessionCookie(c);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
export default route;
|
||||
19
apps/backend/src/modules/student-portal/features/me/route.ts
Normal file
19
apps/backend/src/modules/student-portal/features/me/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { currentStudent, studentSession } from '../../middleware';
|
||||
import { GetStudentMe, MarkStudentWelcomed } from './use-case';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
route.get('/me', studentSession, async (c) => {
|
||||
const student = currentStudent(c);
|
||||
return resultJson(c, await new GetStudentMe().execute(student.accountId));
|
||||
});
|
||||
|
||||
route.post('/me/welcome', studentSession, async (c) => {
|
||||
const student = currentStudent(c);
|
||||
return resultJson(c, await new MarkStudentWelcomed().execute(student.accountId));
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { unauthorizedProblem } from '@/http/problem-details';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
|
||||
|
||||
export class GetStudentMe {
|
||||
constructor(private readonly deps: StudentMeDeps = {}) {}
|
||||
|
||||
async execute(accountId: string): Promise<Result<StudentMe, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const account = await db.studentAccount.findUnique({
|
||||
where: { id: accountId },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
recoveryEmail: true,
|
||||
pendingRecoveryEmail: true,
|
||||
welcomedAt: true,
|
||||
_count: { select: { passkeys: true } },
|
||||
attendees: {
|
||||
where: { attendee: { status: { not: 'DROPPED' } } },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
attendee: {
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!account) return err(unauthorizedProblem('/student-portal/me'));
|
||||
|
||||
return ok({
|
||||
account: {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
recoveryEmail: account.recoveryEmail,
|
||||
pendingRecoveryEmail: account.pendingRecoveryEmail,
|
||||
hasPasskey: account._count.passkeys > 0,
|
||||
welcomed: account.welcomedAt !== null,
|
||||
},
|
||||
students: account.attendees.map(({ attendee }) => ({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
groupId: attendee.group.id,
|
||||
groupName: attendee.group.name,
|
||||
teacherName: attendee.group.owner.name,
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* The welcome screen is shown until the student goes past it once. */
|
||||
export class MarkStudentWelcomed {
|
||||
constructor(private readonly deps: StudentMeDeps = {}) {}
|
||||
|
||||
async execute(accountId: string): Promise<Result<StudentMe, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
await db.studentAccount.updateMany({
|
||||
where: { id: accountId, welcomedAt: null },
|
||||
data: { welcomedAt: this.deps.now ?? new Date() },
|
||||
});
|
||||
return new GetStudentMe({ db }).execute(accountId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { type PasskeyVerify, PasskeyVerifySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { problemJson, resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib';
|
||||
import { currentStudent, studentSession } from '../../middleware';
|
||||
import { GetStudentMe } from '../me/use-case';
|
||||
import { StudentPasskeys } from './use-case';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
route.post('/passkeys/register/options', studentSession, async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
return resultJson(c, await new StudentPasskeys().registrationOptions(accountId));
|
||||
});
|
||||
|
||||
route.post('/passkeys/register/verify', studentSession, validate.json(PasskeyVerifySchema), async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
const input = c.req.valid('json') as PasskeyVerify;
|
||||
const result = await new StudentPasskeys().verifyRegistration(accountId, input, userAgent(c));
|
||||
if (!result.ok) return problemJson(c, result.error);
|
||||
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||
});
|
||||
|
||||
route.delete('/passkeys', studentSession, async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
await new StudentPasskeys().removeAll(accountId);
|
||||
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||
});
|
||||
|
||||
route.post('/passkeys/login/options', async (c) => {
|
||||
return resultJson(c, await new StudentPasskeys().loginOptions(clientIp(c)));
|
||||
});
|
||||
|
||||
route.post('/passkeys/login/verify', validate.json(PasskeyVerifySchema), async (c) => {
|
||||
const input = c.req.valid('json') as PasskeyVerify;
|
||||
const result = await new StudentPasskeys().verifyLogin(input, {
|
||||
userAgent: userAgent(c),
|
||||
currentSessionToken: readStudentSessionCookie(c),
|
||||
});
|
||||
if (!result.ok) return problemJson(c, result.error);
|
||||
writeStudentSessionCookie(c, result.value.sessionToken);
|
||||
return c.json({ firstLogin: false });
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,246 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { PasskeyOptionsResult, PasskeyVerify, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
type AuthenticationResponseJSON,
|
||||
type AuthenticatorTransportFuture,
|
||||
generateAuthenticationOptions,
|
||||
generateRegistrationOptions,
|
||||
type RegistrationResponseJSON,
|
||||
verifyAuthenticationResponse,
|
||||
verifyRegistrationResponse,
|
||||
} from '@simplewebauthn/server';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import {
|
||||
consumeRateLimit,
|
||||
createStudentSession,
|
||||
describeDevice,
|
||||
passkeyInvalidProblem,
|
||||
revokeStudentSessionByToken,
|
||||
tooManyRequestsProblem,
|
||||
WEBAUTHN_CHALLENGE_TTL_MS,
|
||||
webauthnConfig,
|
||||
} from '../../lib';
|
||||
|
||||
type PasskeyDb = Pick<
|
||||
PrismaClient,
|
||||
'studentAccount' | 'studentPasskey' | 'studentWebauthnChallenge' | 'studentSession' | 'rateLimitEvent'
|
||||
>;
|
||||
|
||||
/* The library is injectable so the tests don't need a real authenticator. */
|
||||
export type WebauthnLib = {
|
||||
generateRegistrationOptions: typeof generateRegistrationOptions;
|
||||
verifyRegistrationResponse: typeof verifyRegistrationResponse;
|
||||
generateAuthenticationOptions: typeof generateAuthenticationOptions;
|
||||
verifyAuthenticationResponse: typeof verifyAuthenticationResponse;
|
||||
};
|
||||
|
||||
const defaultWebauthn: WebauthnLib = {
|
||||
generateRegistrationOptions,
|
||||
verifyRegistrationResponse,
|
||||
generateAuthenticationOptions,
|
||||
verifyAuthenticationResponse,
|
||||
};
|
||||
|
||||
type PasskeyDeps = {
|
||||
db?: PasskeyDb;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
webauthn?: WebauthnLib;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const LOGIN_OPTIONS_PER_IP = 30;
|
||||
|
||||
/* Optional passkeys ("Entrar con Face ID o huella"): registered from a signed-in
|
||||
session; the login is discoverable (no account typed), so it works from the
|
||||
"Ingresar" and "Link ya usado" pages without the teacher. */
|
||||
export class StudentPasskeys {
|
||||
constructor(private readonly deps: PasskeyDeps = {}) {}
|
||||
|
||||
private get db(): PasskeyDb {
|
||||
return this.deps.db ?? prisma;
|
||||
}
|
||||
|
||||
private get webauthn(): WebauthnLib {
|
||||
return this.deps.webauthn ?? defaultWebauthn;
|
||||
}
|
||||
|
||||
private get now(): Date {
|
||||
return this.deps.now ?? new Date();
|
||||
}
|
||||
|
||||
async registrationOptions(accountId: string): Promise<Result<PasskeyOptionsResult, ProblemDetails>> {
|
||||
const { rpID, rpName } = webauthnConfig();
|
||||
const account = await this.db.studentAccount.findUniqueOrThrow({
|
||||
where: { id: accountId },
|
||||
select: { name: true, passkeys: { select: { credentialId: true, transports: true } } },
|
||||
});
|
||||
|
||||
const options = await this.webauthn.generateRegistrationOptions({
|
||||
rpName,
|
||||
rpID,
|
||||
userID: new TextEncoder().encode(accountId),
|
||||
userName: account.name,
|
||||
userDisplayName: account.name,
|
||||
attestationType: 'none',
|
||||
excludeCredentials: account.passkeys.map((passkey) => ({
|
||||
id: passkey.credentialId,
|
||||
transports: passkey.transports as AuthenticatorTransportFuture[],
|
||||
})),
|
||||
authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
|
||||
});
|
||||
|
||||
const challengeId = await this.storeChallenge(options.challenge, 'REGISTER', accountId);
|
||||
return ok({ challengeId, options: options as unknown as Record<string, unknown> });
|
||||
}
|
||||
|
||||
async verifyRegistration(
|
||||
accountId: string,
|
||||
input: PasskeyVerify,
|
||||
userAgent: string | null,
|
||||
): Promise<Result<{ registered: true }, ProblemDetails>> {
|
||||
const challenge = await this.takeChallenge(input.challengeId, 'REGISTER', accountId);
|
||||
if (!challenge) return err(passkeyInvalidProblem());
|
||||
|
||||
const { rpID, origin } = webauthnConfig();
|
||||
let verification: Awaited<ReturnType<typeof verifyRegistrationResponse>>;
|
||||
try {
|
||||
verification = await this.webauthn.verifyRegistrationResponse({
|
||||
response: input.response as unknown as RegistrationResponseJSON,
|
||||
expectedChallenge: challenge,
|
||||
expectedOrigin: origin,
|
||||
expectedRPID: rpID,
|
||||
requireUserVerification: false,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn({ error: (error as Error).message }, 'Student passkey registration rejected');
|
||||
return err(passkeyInvalidProblem());
|
||||
}
|
||||
if (!verification.verified || !verification.registrationInfo) return err(passkeyInvalidProblem());
|
||||
|
||||
const { credential } = verification.registrationInfo;
|
||||
await this.db.studentPasskey.upsert({
|
||||
where: { credentialId: credential.id },
|
||||
create: {
|
||||
accountId,
|
||||
credentialId: credential.id,
|
||||
publicKey: Uint8Array.from(credential.publicKey),
|
||||
counter: credential.counter,
|
||||
transports: credential.transports ?? [],
|
||||
device: describeDevice(userAgent),
|
||||
createdAt: this.now,
|
||||
},
|
||||
// Same authenticator again (excludeCredentials failed open): keep it, no takeover.
|
||||
update: {},
|
||||
});
|
||||
return ok({ registered: true });
|
||||
}
|
||||
|
||||
async loginOptions(ip: string | null): Promise<Result<PasskeyOptionsResult, ProblemDetails>> {
|
||||
const allowed = await consumeRateLimit(this.db, `passkey-login:ip:${ip ?? 'unknown'}`, {
|
||||
limit: LOGIN_OPTIONS_PER_IP,
|
||||
windowMs: 15 * 60 * 1000,
|
||||
now: this.now,
|
||||
});
|
||||
if (!allowed) return err(tooManyRequestsProblem());
|
||||
|
||||
const { rpID } = webauthnConfig();
|
||||
const options = await this.webauthn.generateAuthenticationOptions({
|
||||
rpID,
|
||||
userVerification: 'preferred',
|
||||
});
|
||||
const challengeId = await this.storeChallenge(options.challenge, 'LOGIN', null);
|
||||
return ok({ challengeId, options: options as unknown as Record<string, unknown> });
|
||||
}
|
||||
|
||||
async verifyLogin(
|
||||
input: PasskeyVerify,
|
||||
request: { userAgent: string | null; currentSessionToken?: string },
|
||||
): Promise<Result<{ sessionToken: string }, ProblemDetails>> {
|
||||
const challenge = await this.takeChallenge(input.challengeId, 'LOGIN', null);
|
||||
if (!challenge) return err(passkeyInvalidProblem());
|
||||
|
||||
const response = input.response as unknown as AuthenticationResponseJSON;
|
||||
if (typeof response.id !== 'string') return err(passkeyInvalidProblem());
|
||||
const passkey = await this.db.studentPasskey.findUnique({ where: { credentialId: response.id } });
|
||||
if (!passkey) return err(passkeyInvalidProblem());
|
||||
|
||||
const { rpID, origin } = webauthnConfig();
|
||||
let verification: Awaited<ReturnType<typeof verifyAuthenticationResponse>>;
|
||||
try {
|
||||
verification = await this.webauthn.verifyAuthenticationResponse({
|
||||
response,
|
||||
expectedChallenge: challenge,
|
||||
expectedOrigin: origin,
|
||||
expectedRPID: rpID,
|
||||
credential: {
|
||||
id: passkey.credentialId,
|
||||
publicKey: Uint8Array.from(passkey.publicKey),
|
||||
counter: passkey.counter,
|
||||
transports: passkey.transports as AuthenticatorTransportFuture[],
|
||||
},
|
||||
requireUserVerification: false,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn({ error: (error as Error).message }, 'Student passkey login rejected');
|
||||
return err(passkeyInvalidProblem());
|
||||
}
|
||||
if (!verification.verified) return err(passkeyInvalidProblem());
|
||||
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
return unitOfWork.executeResult(async (tx) => {
|
||||
await tx.studentPasskey.update({
|
||||
where: { id: passkey.id },
|
||||
data: { counter: verification.authenticationInfo.newCounter, lastUsedAt: this.now },
|
||||
});
|
||||
if (request.currentSessionToken) {
|
||||
await revokeStudentSessionByToken(tx, request.currentSessionToken, this.now);
|
||||
}
|
||||
const sessionToken = await createStudentSession(tx, {
|
||||
accountId: passkey.accountId,
|
||||
userAgent: request.userAgent,
|
||||
now: this.now,
|
||||
});
|
||||
return ok({ sessionToken });
|
||||
});
|
||||
}
|
||||
|
||||
/* "Quitar Face ID": removes every passkey of the account. */
|
||||
async removeAll(accountId: string): Promise<Result<null, ProblemDetails>> {
|
||||
await this.db.studentPasskey.deleteMany({ where: { accountId } });
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
private async storeChallenge(
|
||||
challenge: string,
|
||||
purpose: 'REGISTER' | 'LOGIN',
|
||||
accountId: string | null,
|
||||
): Promise<string> {
|
||||
await this.db.studentWebauthnChallenge.deleteMany({ where: { expiresAt: { lt: this.now } } });
|
||||
const row = await this.db.studentWebauthnChallenge.create({
|
||||
data: {
|
||||
challenge,
|
||||
purpose,
|
||||
accountId,
|
||||
expiresAt: new Date(this.now.getTime() + WEBAUTHN_CHALLENGE_TTL_MS),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return row.id;
|
||||
}
|
||||
|
||||
/* Single use: whoever deletes the row gets the challenge. */
|
||||
private async takeChallenge(
|
||||
challengeId: string,
|
||||
purpose: 'REGISTER' | 'LOGIN',
|
||||
accountId: string | null,
|
||||
): Promise<string | null> {
|
||||
const row = await this.db.studentWebauthnChallenge.findUnique({ where: { id: challengeId } });
|
||||
if (!row || row.purpose !== purpose || row.accountId !== accountId || row.expiresAt <= this.now) {
|
||||
return null;
|
||||
}
|
||||
const deleted = await this.db.studentWebauthnChallenge.deleteMany({ where: { id: challengeId } });
|
||||
return deleted.count === 1 ? row.challenge : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, validationProblem } from '@/http/problem-builders';
|
||||
import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { type FileStorage, getFileStorage } from '@/lib/storage';
|
||||
import { logger } from '@/logger';
|
||||
import { findLinkedAttendee, storageNotAvailableProblem, studentAttendeeNotFoundProblem } from '../../lib';
|
||||
|
||||
type ReportPaymentDeps = {
|
||||
db?: Pick<PrismaClient, 'attendee' | 'payment'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
storage?: FileStorage | null;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type ReportPaymentInput = {
|
||||
attendeeId: string;
|
||||
paymentIds: string[];
|
||||
file: { name: string; bytes: Uint8Array };
|
||||
};
|
||||
|
||||
/* "Informar pago": the receipt goes to private storage and the report stays
|
||||
REPORTED until the teacher reviews it; nothing about the fees changes here.
|
||||
The fees are locked (FOR UPDATE) while checking that none of them is already
|
||||
in another unreviewed report, so two concurrent reports can't overlap. */
|
||||
export class ReportStudentPayment {
|
||||
constructor(private readonly deps: ReportPaymentDeps = {}) {}
|
||||
|
||||
async execute(accountId: string, input: ReportPaymentInput): Promise<Result<{ id: string }, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const storage = this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
||||
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||
|
||||
if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) {
|
||||
return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
|
||||
}
|
||||
const mime = detectReceiptType(input.file.bytes);
|
||||
if (!mime) {
|
||||
return err(validationProblem({ detail: 'El comprobante tiene que ser JPG, PNG, WEBP, HEIC o PDF.', errors: { file: ['invalid_type'] } }));
|
||||
}
|
||||
if (!storage) return err(storageNotAvailableProblem());
|
||||
|
||||
const paymentIds = [...new Set(input.paymentIds)];
|
||||
const payments = await db.payment.findMany({
|
||||
where: { id: { in: paymentIds }, attendeeId: attendee.id, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||
select: { id: true, amount: true, currency: true },
|
||||
});
|
||||
if (payments.length !== paymentIds.length) {
|
||||
return err(validationProblem({ detail: 'Alguna de las cuotas elegidas ya no está pendiente.', errors: { paymentIds: ['invalid'] } }));
|
||||
}
|
||||
const currencies = new Set(payments.map((payment) => payment.currency));
|
||||
if (currencies.size !== 1) {
|
||||
return err(validationProblem({ detail: 'Las cuotas tienen que ser de la misma moneda.' }));
|
||||
}
|
||||
const total = payments.reduce((sum, payment) => sum.add(payment.amount), new Prisma.Decimal(0));
|
||||
|
||||
const key = `receipts/${attendee.group.createdById}/${attendee.id}/${randomBytes(16).toString('hex')}.${RECEIPT_EXTENSIONS[mime]}`;
|
||||
await storage.put(key, input.file.bytes, mime);
|
||||
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const result = await unitOfWork.executeResult(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM payments WHERE id IN (${Prisma.join(paymentIds)}) FOR UPDATE`;
|
||||
const taken = await tx.reportedPaymentItem.count({
|
||||
where: { paymentId: { in: paymentIds }, reportedPayment: { status: 'REPORTED' } },
|
||||
});
|
||||
if (taken > 0) {
|
||||
return err(conflictProblem({ detail: 'Ya informaste el pago de alguna de estas cuotas.', code: 'payment_already_reported' }));
|
||||
}
|
||||
const report = await tx.reportedPayment.create({
|
||||
data: {
|
||||
attendeeId: attendee.id,
|
||||
groupId: attendee.groupId,
|
||||
accountId,
|
||||
totalAmount: total,
|
||||
currency: [...currencies][0] as string,
|
||||
receiptKey: key,
|
||||
receiptMime: mime,
|
||||
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
|
||||
receiptSize: input.file.bytes.length,
|
||||
createdAt: now,
|
||||
items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return ok({ id: report.id });
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
await storage.remove(key).catch((error) => logger.warn({ error }, 'Orphan receipt could not be removed'));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
type ConfirmRecoveryEmail as ConfirmRecoveryEmailInput,
|
||||
ConfirmRecoveryEmailSchema,
|
||||
type SetRecoveryEmail as SetRecoveryEmailInput,
|
||||
SetRecoveryEmailSchema,
|
||||
} from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { problemJson, resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { currentStudent, studentSession } from '../../middleware';
|
||||
import { GetStudentMe } from '../me/use-case';
|
||||
import { ConfirmRecoveryEmail, RemoveRecoveryEmail, SetRecoveryEmail } from './use-case';
|
||||
|
||||
const route = new Hono<BackendEnv>();
|
||||
|
||||
route.put('/me/recovery-email', studentSession, validate.json(SetRecoveryEmailSchema), async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
const { email } = c.req.valid('json') as SetRecoveryEmailInput;
|
||||
const result = await new SetRecoveryEmail().execute(accountId, email);
|
||||
if (!result.ok) return problemJson(c, result.error);
|
||||
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||
});
|
||||
|
||||
route.delete('/me/recovery-email', studentSession, async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
await new RemoveRecoveryEmail().execute(accountId);
|
||||
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||
});
|
||||
|
||||
route.post('/recovery-email/confirm', validate.json(ConfirmRecoveryEmailSchema), async (c) => {
|
||||
const { token } = c.req.valid('json') as ConfirmRecoveryEmailInput;
|
||||
return resultJson(c, await new ConfirmRecoveryEmail().execute(token));
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { EMAIL_CONFIRMATION_TTL_HOURS, err, ok } from '@gruperly/shared';
|
||||
import { type EmailProvider, emailProvider } from '@/lib/email';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import {
|
||||
consumeRateLimit,
|
||||
generateAccessToken,
|
||||
hashToken,
|
||||
studentLinkInvalidProblem,
|
||||
tooManyRequestsProblem,
|
||||
webUrl,
|
||||
} from '../../lib';
|
||||
|
||||
type RecoveryEmailDeps = {
|
||||
db?: Pick<PrismaClient, 'studentAccount' | 'studentAccessToken' | 'rateLimitEvent'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
email?: Pick<EmailProvider, 'sendStudentEmailConfirmation'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const CONFIRMATIONS_PER_HOUR = 5;
|
||||
|
||||
/* The student loads an optional recovery email. It stays "pending" until they
|
||||
open the confirmation link: an unconfirmed address is never used to recover. */
|
||||
export class SetRecoveryEmail {
|
||||
constructor(private readonly deps: RecoveryEmailDeps = {}) {}
|
||||
|
||||
async execute(accountId: string, email: string): Promise<Result<{ pending: boolean }, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const account = await db.studentAccount.findUniqueOrThrow({
|
||||
where: { id: accountId },
|
||||
select: { name: true, recoveryEmail: true },
|
||||
});
|
||||
if (account.recoveryEmail === email) {
|
||||
await db.studentAccount.update({ where: { id: accountId }, data: { pendingRecoveryEmail: null } });
|
||||
return ok({ pending: false });
|
||||
}
|
||||
|
||||
const allowed = await consumeRateLimit(db, `confirm-email:account:${accountId}`, {
|
||||
limit: CONFIRMATIONS_PER_HOUR,
|
||||
windowMs: 60 * 60 * 1000,
|
||||
now,
|
||||
});
|
||||
if (!allowed) return err(tooManyRequestsProblem());
|
||||
|
||||
const token = generateAccessToken();
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
await unitOfWork.executeResult(async (tx) => {
|
||||
await tx.studentAccessToken.updateMany({
|
||||
where: { accountId, kind: 'EMAIL_CONFIRMATION', usedAt: null, revokedAt: null },
|
||||
data: { revokedAt: now },
|
||||
});
|
||||
await tx.studentAccessToken.create({
|
||||
data: {
|
||||
accountId,
|
||||
kind: 'EMAIL_CONFIRMATION',
|
||||
email,
|
||||
tokenHash: hashToken(token),
|
||||
expiresAt: new Date(now.getTime() + EMAIL_CONFIRMATION_TTL_HOURS * 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
await tx.studentAccount.update({
|
||||
where: { id: accountId },
|
||||
data: { pendingRecoveryEmail: email },
|
||||
});
|
||||
return ok(null);
|
||||
});
|
||||
|
||||
const sender = this.deps.email ?? emailProvider;
|
||||
try {
|
||||
await sender.sendStudentEmailConfirmation({
|
||||
email,
|
||||
name: account.name,
|
||||
url: `${webUrl()}/acceso/mail/${token}`,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent');
|
||||
}
|
||||
return ok({ pending: true });
|
||||
}
|
||||
}
|
||||
|
||||
export class RemoveRecoveryEmail {
|
||||
constructor(private readonly deps: Pick<RecoveryEmailDeps, 'db' | 'now'> = {}) {}
|
||||
|
||||
async execute(accountId: string): Promise<Result<null, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
await db.studentAccessToken.updateMany({
|
||||
where: { accountId, kind: { in: ['EMAIL_CONFIRMATION', 'RECOVERY'] }, usedAt: null, revokedAt: null },
|
||||
data: { revokedAt: this.deps.now ?? new Date() },
|
||||
});
|
||||
await db.studentAccount.update({
|
||||
where: { id: accountId },
|
||||
data: { recoveryEmail: null, recoveryEmailVerifiedAt: null, pendingRecoveryEmail: null },
|
||||
});
|
||||
return ok(null);
|
||||
}
|
||||
}
|
||||
|
||||
/* Public: the link may open in the mail app's browser, without the session. */
|
||||
export class ConfirmRecoveryEmail {
|
||||
constructor(private readonly deps: Pick<RecoveryEmailDeps, 'unitOfWork' | 'now'> = {}) {}
|
||||
|
||||
async execute(token: string): Promise<Result<{ email: string }, ProblemDetails>> {
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const now = this.deps.now ?? new Date();
|
||||
const tokenHash = hashToken(token);
|
||||
|
||||
return unitOfWork.executeResult(async (tx) => {
|
||||
const claimed = await tx.studentAccessToken.updateMany({
|
||||
where: {
|
||||
tokenHash,
|
||||
kind: 'EMAIL_CONFIRMATION',
|
||||
usedAt: null,
|
||||
revokedAt: null,
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
data: { usedAt: now },
|
||||
});
|
||||
if (claimed.count !== 1) return err(studentLinkInvalidProblem());
|
||||
|
||||
const row = await tx.studentAccessToken.findUniqueOrThrow({
|
||||
where: { tokenHash },
|
||||
select: { accountId: true, email: true, account: { select: { pendingRecoveryEmail: true } } },
|
||||
});
|
||||
if (!row.email) return err(studentLinkInvalidProblem());
|
||||
|
||||
await tx.studentAccount.update({
|
||||
where: { id: row.accountId },
|
||||
data: {
|
||||
recoveryEmail: row.email,
|
||||
recoveryEmailVerifiedAt: now,
|
||||
...(row.account.pendingRecoveryEmail === row.email ? { pendingRecoveryEmail: null } : {}),
|
||||
},
|
||||
});
|
||||
return ok({ email: row.email });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { type RequestRecoveryLink as RequestRecoveryLinkInput, RequestRecoveryLinkSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { clientIp } from '../../lib';
|
||||
import { RequestRecoveryLink } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/recovery', validate.json(RequestRecoveryLinkSchema), async (c) => {
|
||||
const { email } = c.req.valid('json') as RequestRecoveryLinkInput;
|
||||
const result = await new RequestRecoveryLink().execute({ email, ip: clientIp(c) });
|
||||
if (!result.ok) {
|
||||
c.header('Retry-After', '900');
|
||||
return problemJson(c, result.error);
|
||||
}
|
||||
return c.json({ accepted: true }, 202);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,88 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok, RECOVERY_TTL_MINUTES } from '@gruperly/shared';
|
||||
import { type EmailProvider, emailProvider } from '@/lib/email';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import {
|
||||
consumeRateLimit,
|
||||
generateAccessToken,
|
||||
hashToken,
|
||||
studentLinkUrl,
|
||||
tooManyRequestsProblem,
|
||||
} from '../../lib';
|
||||
|
||||
type RequestRecoveryLinkDeps = {
|
||||
db?: Pick<PrismaClient, 'studentAccount' | 'studentAccessToken' | 'rateLimitEvent'>;
|
||||
email?: Pick<EmailProvider, 'sendStudentRecoveryLinks'>;
|
||||
/** Runs the lookup + send after answering, so the response time doesn't
|
||||
* tell whether the email exists. Tests run it inline. */
|
||||
defer?: (task: () => Promise<void>) => void;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export const RECOVERY_LIMIT_PER_EMAIL = 3;
|
||||
export const RECOVERY_LIMIT_PER_IP = 10;
|
||||
const WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
function runInBackground(task: () => Promise<void>) {
|
||||
void task().catch((error) => logger.error({ error }, 'Student recovery link could not be sent'));
|
||||
}
|
||||
|
||||
/* "Pedir un link a mi mail". The answer is identical whether the email exists
|
||||
or not; only the rate limit (3 per email and 10 per IP every 15 minutes,
|
||||
counted the same for unknown emails) can say no. */
|
||||
export class RequestRecoveryLink {
|
||||
constructor(private readonly deps: RequestRecoveryLinkDeps = {}) {}
|
||||
|
||||
async execute(input: { email: string; ip: string | null }): Promise<Result<{ accepted: true }, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const ipAllowed = await consumeRateLimit(db, `recovery:ip:${input.ip ?? 'unknown'}`, {
|
||||
limit: RECOVERY_LIMIT_PER_IP,
|
||||
windowMs: WINDOW_MS,
|
||||
now,
|
||||
});
|
||||
if (!ipAllowed) return err(tooManyRequestsProblem());
|
||||
|
||||
const emailKey = createHash('sha256').update(input.email).digest('hex');
|
||||
const emailAllowed = await consumeRateLimit(db, `recovery:email:${emailKey}`, {
|
||||
limit: RECOVERY_LIMIT_PER_EMAIL,
|
||||
windowMs: WINDOW_MS,
|
||||
now,
|
||||
});
|
||||
if (!emailAllowed) return err(tooManyRequestsProblem());
|
||||
|
||||
(this.deps.defer ?? runInBackground)(() => this.send(db, input.email, now));
|
||||
return ok({ accepted: true });
|
||||
}
|
||||
|
||||
private async send(
|
||||
db: NonNullable<RequestRecoveryLinkDeps['db']>,
|
||||
email: string,
|
||||
now: Date,
|
||||
): Promise<void> {
|
||||
const accounts = await db.studentAccount.findMany({
|
||||
where: { recoveryEmail: email, recoveryEmailVerifiedAt: { not: null } },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (accounts.length === 0) return;
|
||||
|
||||
const links: { name: string; url: string }[] = [];
|
||||
for (const account of accounts) {
|
||||
const token = generateAccessToken();
|
||||
await db.studentAccessToken.create({
|
||||
data: {
|
||||
accountId: account.id,
|
||||
kind: 'RECOVERY',
|
||||
tokenHash: hashToken(token),
|
||||
expiresAt: new Date(now.getTime() + RECOVERY_TTL_MINUTES * 60 * 1000),
|
||||
},
|
||||
});
|
||||
links.push({ name: account.name, url: studentLinkUrl(token) });
|
||||
}
|
||||
await (this.deps.email ?? emailProvider).sendStudentRecoveryLinks({ email, links });
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/student-portal/index.ts
Normal file
1
apps/backend/src/modules/student-portal/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as studentPortalRoutes } from './routes';
|
||||
49
apps/backend/src/modules/student-portal/lib/access.ts
Normal file
49
apps/backend/src/modules/student-portal/lib/access.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
|
||||
export type StudentAccessDb = {
|
||||
studentAccountAttendee: Prisma.StudentAccountAttendeeDelegate;
|
||||
};
|
||||
|
||||
/* The authorization rule of every student endpoint: only the attendees linked
|
||||
to the session's account. Anything else is a 404 (we don't confirm ids). */
|
||||
export async function linkedAttendeeIds(db: StudentAccessDb, accountId: string): Promise<string[]> {
|
||||
const links = await db.studentAccountAttendee.findMany({
|
||||
// A DROPPED attendee loses access; a PAUSED one keeps it.
|
||||
where: { accountId, attendee: { status: { not: 'DROPPED' } } },
|
||||
select: { attendeeId: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return links.map((link) => link.attendeeId);
|
||||
}
|
||||
|
||||
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
||||
|
||||
/* One attendee of the session, with what the student screens need from the
|
||||
group. null for an attendee not linked to the account (or DROPPED): routes
|
||||
answer 404, the same as for an id that doesn't exist. */
|
||||
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
||||
return db.attendee.findFirst({
|
||||
where: {
|
||||
id: attendeeId,
|
||||
status: { not: 'DROPPED' },
|
||||
studentAccounts: { some: { accountId } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
groupId: true,
|
||||
group: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
days: true,
|
||||
time: true,
|
||||
createdById: true,
|
||||
owner: { select: { name: true, country: true, transferAlias: true, transferHolder: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export type LinkedAttendee = NonNullable<Awaited<ReturnType<typeof findLinkedAttendee>>>;
|
||||
31
apps/backend/src/modules/student-portal/lib/device.ts
Normal file
31
apps/backend/src/modules/student-portal/lib/device.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/* Human-readable device from the user agent ("iPhone · Safari"), shown to the
|
||||
teacher in "Acceso a la app". Best effort: never used for security. */
|
||||
export function describeDevice(userAgent: string | null | undefined): string {
|
||||
const ua = userAgent ?? '';
|
||||
const platform = detectPlatform(ua);
|
||||
const browser = detectBrowser(ua);
|
||||
if (platform && browser) return `${platform} · ${browser}`;
|
||||
return platform ?? browser ?? 'Dispositivo desconocido';
|
||||
}
|
||||
|
||||
function detectPlatform(ua: string): string | null {
|
||||
if (/iPhone/i.test(ua)) return 'iPhone';
|
||||
if (/iPad/i.test(ua)) return 'iPad';
|
||||
if (/Android/i.test(ua)) return /Mobile/i.test(ua) ? 'Android' : 'Tablet Android';
|
||||
if (/CrOS/i.test(ua)) return 'Chromebook';
|
||||
if (/Macintosh|Mac OS X/i.test(ua)) return 'Mac';
|
||||
if (/Windows/i.test(ua)) return 'Windows';
|
||||
if (/Linux/i.test(ua)) return 'Linux';
|
||||
return null;
|
||||
}
|
||||
|
||||
function detectBrowser(ua: string): string | null {
|
||||
// Order matters: Edge, Opera and Samsung also say "Chrome"; every iOS browser says "Safari".
|
||||
if (/EdgiOS|Edg\//i.test(ua)) return 'Edge';
|
||||
if (/OPR\/|OPiOS/i.test(ua)) return 'Opera';
|
||||
if (/SamsungBrowser/i.test(ua)) return 'Samsung Internet';
|
||||
if (/FxiOS|Firefox\//i.test(ua)) return 'Firefox';
|
||||
if (/CriOS|Chrome\//i.test(ua)) return 'Chrome';
|
||||
if (/Safari\//i.test(ua)) return 'Safari';
|
||||
return null;
|
||||
}
|
||||
9
apps/backend/src/modules/student-portal/lib/index.ts
Normal file
9
apps/backend/src/modules/student-portal/lib/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export * from './access';
|
||||
export * from './device';
|
||||
export * from './problems';
|
||||
export * from './rate-limit';
|
||||
export * from './request';
|
||||
export * from './schedule';
|
||||
export * from './session';
|
||||
export * from './tokens';
|
||||
export * from './webauthn';
|
||||
72
apps/backend/src/modules/student-portal/lib/problems.ts
Normal file
72
apps/backend/src/modules/student-portal/lib/problems.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import type { ProblemDetails } from '@gruperly/shared';
|
||||
import { problemDetails } from '@/http/problem-details';
|
||||
import { PROBLEM_DOMAIN } from '@/http/problem-domain';
|
||||
|
||||
export function studentLinkInvalidProblem(): ProblemDetails {
|
||||
return problemDetails({
|
||||
type: `${PROBLEM_DOMAIN}/problems/student-link-invalid`,
|
||||
title: 'Gone',
|
||||
status: 410,
|
||||
detail: 'Este link ya fue usado o venció.',
|
||||
code: 'student_link_invalid',
|
||||
});
|
||||
}
|
||||
|
||||
export function passkeyInvalidProblem(): ProblemDetails {
|
||||
return problemDetails({
|
||||
type: `${PROBLEM_DOMAIN}/problems/passkey-invalid`,
|
||||
title: 'Bad Request',
|
||||
status: 400,
|
||||
detail: 'No pudimos verificar la llave de acceso.',
|
||||
code: 'passkey_invalid',
|
||||
});
|
||||
}
|
||||
|
||||
export function tooManyRequestsProblem(): ProblemDetails {
|
||||
return problemDetails({
|
||||
type: `${PROBLEM_DOMAIN}/problems/too-many-requests`,
|
||||
title: 'Too Many Requests',
|
||||
status: 429,
|
||||
detail: 'Hiciste muchos pedidos seguidos. Probá de nuevo en unos minutos.',
|
||||
code: 'too_many_requests',
|
||||
});
|
||||
}
|
||||
|
||||
export function crossOriginProblem(): ProblemDetails {
|
||||
return problemDetails({
|
||||
type: `${PROBLEM_DOMAIN}/problems/forbidden`,
|
||||
title: 'Forbidden',
|
||||
status: 403,
|
||||
detail: 'Origen no permitido.',
|
||||
code: 'cross_origin_request',
|
||||
});
|
||||
}
|
||||
|
||||
export function studentAttendeeNotFoundProblem(): ProblemDetails {
|
||||
return problemDetails({
|
||||
title: 'Not Found',
|
||||
status: 404,
|
||||
detail: 'The requested resource was not found.',
|
||||
code: 'not_found',
|
||||
});
|
||||
}
|
||||
|
||||
export function classAlreadyStartedProblem(): ProblemDetails {
|
||||
return problemDetails({
|
||||
type: `${PROBLEM_DOMAIN}/problems/conflict`,
|
||||
title: 'Conflict',
|
||||
status: 409,
|
||||
detail: 'La clase ya empezó: el aviso solo se puede dar o deshacer antes.',
|
||||
code: 'class_already_started',
|
||||
});
|
||||
}
|
||||
|
||||
export function storageNotAvailableProblem(): ProblemDetails {
|
||||
return problemDetails({
|
||||
type: `${PROBLEM_DOMAIN}/problems/service-unavailable`,
|
||||
title: 'Service Unavailable',
|
||||
status: 503,
|
||||
detail: 'Por ahora no se pueden adjuntar comprobantes.',
|
||||
code: 'storage_not_available',
|
||||
});
|
||||
}
|
||||
19
apps/backend/src/modules/student-portal/lib/rate-limit.ts
Normal file
19
apps/backend/src/modules/student-portal/lib/rate-limit.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
|
||||
export type RateLimitDb = { rateLimitEvent: Prisma.RateLimitEventDelegate };
|
||||
|
||||
/* Sliding window counted in `rate_limit_events`: returns false (and records
|
||||
nothing) once `key` reached `limit` hits inside the window. Old hits of the
|
||||
same key are swept on the way. */
|
||||
export async function consumeRateLimit(
|
||||
db: RateLimitDb,
|
||||
key: string,
|
||||
options: { limit: number; windowMs: number; now: Date },
|
||||
): Promise<boolean> {
|
||||
const windowStart = new Date(options.now.getTime() - options.windowMs);
|
||||
await db.rateLimitEvent.deleteMany({ where: { key, createdAt: { lt: windowStart } } });
|
||||
const hits = await db.rateLimitEvent.count({ where: { key, createdAt: { gte: windowStart } } });
|
||||
if (hits >= options.limit) return false;
|
||||
await db.rateLimitEvent.create({ data: { key, createdAt: options.now } });
|
||||
return true;
|
||||
}
|
||||
19
apps/backend/src/modules/student-portal/lib/request.ts
Normal file
19
apps/backend/src/modules/student-portal/lib/request.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { Context } from 'hono';
|
||||
|
||||
/* Client IP for the rate limit and the token audit. Each proxy appends to
|
||||
X-Forwarded-For, so the client is the entry `TRUSTED_PROXY_HOPS` from the end
|
||||
(1 = only our nginx; 2 = Traefik + nginx). Entries further left can be forged
|
||||
by the client and are ignored. */
|
||||
export function clientIp(c: Context): string | null {
|
||||
const hops = Math.max(1, Number(process.env.TRUSTED_PROXY_HOPS ?? 1) || 1);
|
||||
const chain = (c.req.header('X-Forwarded-For') ?? '')
|
||||
.split(',')
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean);
|
||||
if (chain.length >= hops) return chain[chain.length - hops] ?? null;
|
||||
return c.req.header('X-Real-IP') ?? null;
|
||||
}
|
||||
|
||||
export function userAgent(c: Context): string | null {
|
||||
return c.req.header('User-Agent')?.slice(0, 512) ?? null;
|
||||
}
|
||||
7
apps/backend/src/modules/student-portal/lib/schedule.ts
Normal file
7
apps/backend/src/modules/student-portal/lib/schedule.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { COUNTRY_TIME_ZONES, type CountryCode } from '@gruperly/shared';
|
||||
import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler';
|
||||
|
||||
// The class schedule runs on the teacher's clock (their country).
|
||||
export function teacherTimeZone(country: string | null | undefined): string {
|
||||
return (country && COUNTRY_TIME_ZONES[country as CountryCode]) || DEFAULT_TIME_ZONE;
|
||||
}
|
||||
99
apps/backend/src/modules/student-portal/lib/session.ts
Normal file
99
apps/backend/src/modules/student-portal/lib/session.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
import { STUDENT_SESSION_TTL_DAYS } from '@gruperly/shared';
|
||||
import type { Context } from 'hono';
|
||||
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||
import { describeDevice } from './device';
|
||||
import { generateAccessToken, hashToken, webUrl } from './tokens';
|
||||
|
||||
export type StudentSessionDb = { studentSession: Prisma.StudentSessionDelegate };
|
||||
|
||||
const COOKIE_NAME = 'gruperly_student';
|
||||
const SESSION_TTL_MS = STUDENT_SESSION_TTL_DAYS * 24 * 60 * 60 * 1000;
|
||||
// Sliding renewal is written at most once per hour, not on every request.
|
||||
const TOUCH_INTERVAL_MS = 60 * 60 * 1000;
|
||||
|
||||
// Its own cookie, never Better Auth's: a student session can't reach the
|
||||
// teacher's endpoints and a teacher session can't reach the student's.
|
||||
// With HTTPS it carries the `__Host-` prefix (Secure, Path=/, no Domain).
|
||||
function isSecure(): boolean {
|
||||
return webUrl().startsWith('https://');
|
||||
}
|
||||
|
||||
export function readStudentSessionCookie(c: Context): string | undefined {
|
||||
return isSecure() ? getCookie(c, COOKIE_NAME, 'host') : getCookie(c, COOKIE_NAME);
|
||||
}
|
||||
|
||||
export function writeStudentSessionCookie(c: Context, token: string): void {
|
||||
setCookie(c, COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
secure: isSecure(),
|
||||
sameSite: 'Lax',
|
||||
path: '/',
|
||||
maxAge: SESSION_TTL_MS / 1000,
|
||||
...(isSecure() ? { prefix: 'host' as const } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function clearStudentSessionCookie(c: Context): void {
|
||||
deleteCookie(c, COOKIE_NAME, {
|
||||
path: '/',
|
||||
secure: isSecure(),
|
||||
...(isSecure() ? { prefix: 'host' as const } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/* A brand-new identifier on every sign-in (link or passkey): sessions are never
|
||||
reused or upgraded. Returns the raw token for the cookie. */
|
||||
export async function createStudentSession(
|
||||
db: StudentSessionDb,
|
||||
input: { accountId: string; userAgent: string | null | undefined; now: Date },
|
||||
): Promise<string> {
|
||||
const token = generateAccessToken();
|
||||
await db.studentSession.create({
|
||||
data: {
|
||||
accountId: input.accountId,
|
||||
tokenHash: hashToken(token),
|
||||
device: describeDevice(input.userAgent),
|
||||
createdAt: input.now,
|
||||
lastUsedAt: input.now,
|
||||
expiresAt: new Date(input.now.getTime() + SESSION_TTL_MS),
|
||||
},
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
export type ResolvedStudentSession = {
|
||||
sessionId: string;
|
||||
accountId: string;
|
||||
/** The expiry moved forward: the cookie has to be written again. */
|
||||
renewed: boolean;
|
||||
};
|
||||
|
||||
export async function resolveStudentSession(
|
||||
db: StudentSessionDb,
|
||||
token: string,
|
||||
now: Date,
|
||||
): Promise<ResolvedStudentSession | null> {
|
||||
const session = await db.studentSession.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
if (!session || session.revokedAt || session.expiresAt <= now) return null;
|
||||
|
||||
const renewed = now.getTime() - session.lastUsedAt.getTime() >= TOUCH_INTERVAL_MS;
|
||||
if (renewed) {
|
||||
await db.studentSession.update({
|
||||
where: { id: session.id },
|
||||
data: { lastUsedAt: now, expiresAt: new Date(now.getTime() + SESSION_TTL_MS) },
|
||||
});
|
||||
}
|
||||
return { sessionId: session.id, accountId: session.accountId, renewed };
|
||||
}
|
||||
|
||||
export async function revokeStudentSessionByToken(
|
||||
db: StudentSessionDb,
|
||||
token: string,
|
||||
now: Date,
|
||||
): Promise<void> {
|
||||
await db.studentSession.updateMany({
|
||||
where: { tokenHash: hashToken(token), revokedAt: null },
|
||||
data: { revokedAt: now },
|
||||
});
|
||||
}
|
||||
19
apps/backend/src/modules/student-portal/lib/tokens.ts
Normal file
19
apps/backend/src/modules/student-portal/lib/tokens.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
|
||||
// 32 bytes from the CSPRNG, base64url: what travels in links and cookies.
|
||||
export function generateAccessToken(): string {
|
||||
return randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
// Only this goes to the database.
|
||||
export function hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
export function webUrl(): string {
|
||||
return (process.env.WEB_URL ?? 'http://localhost:6173').replace(/\/$/, '');
|
||||
}
|
||||
|
||||
export function studentLinkUrl(token: string): string {
|
||||
return `${webUrl()}/i/${token}`;
|
||||
}
|
||||
14
apps/backend/src/modules/student-portal/lib/webauthn.ts
Normal file
14
apps/backend/src/modules/student-portal/lib/webauthn.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { webUrl } from './tokens';
|
||||
|
||||
// Relying party: the web's host. Override them when the web is served from
|
||||
// another origin than WEB_URL (e.g. a tunnel to test on a phone).
|
||||
export function webauthnConfig() {
|
||||
const origin = process.env.WEBAUTHN_ORIGIN || webUrl();
|
||||
return {
|
||||
rpName: 'Gruperly',
|
||||
rpID: process.env.WEBAUTHN_RP_ID || new URL(origin).hostname,
|
||||
origin,
|
||||
};
|
||||
}
|
||||
|
||||
export const WEBAUTHN_CHALLENGE_TTL_MS = 5 * 60 * 1000;
|
||||
57
apps/backend/src/modules/student-portal/middleware.ts
Normal file
57
apps/backend/src/modules/student-portal/middleware.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import type { Context, MiddlewareHandler } from 'hono';
|
||||
import type { BackendEnv, StudentContext } from '@/http/env';
|
||||
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import prisma from '@/lib/prisma';
|
||||
import {
|
||||
crossOriginProblem,
|
||||
readStudentSessionCookie,
|
||||
resolveStudentSession,
|
||||
type StudentSessionDb,
|
||||
webUrl,
|
||||
writeStudentSessionCookie,
|
||||
} from './lib';
|
||||
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
|
||||
/* CSRF: besides SameSite=Lax, every state-changing request must come from the
|
||||
web's origin. Browsers always send `Origin` on POST/PATCH/DELETE, so a
|
||||
missing header is rejected too. */
|
||||
export const studentOriginGuard: MiddlewareHandler = async (c, next) => {
|
||||
if (SAFE_METHODS.has(c.req.method)) {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
const allowed = new Set([webUrl(), process.env.WEBAUTHN_ORIGIN].filter(Boolean));
|
||||
const origin = c.req.header('Origin');
|
||||
if (!origin || !allowed.has(origin)) {
|
||||
return problemJson(c, crossOriginProblem());
|
||||
}
|
||||
await next();
|
||||
};
|
||||
|
||||
export function requireStudentSession(
|
||||
deps: { db?: StudentSessionDb; now?: () => Date } = {},
|
||||
): MiddlewareHandler {
|
||||
return async (c, next) => {
|
||||
const token = readStudentSessionCookie(c);
|
||||
const session = token
|
||||
? await resolveStudentSession(deps.db ?? prisma, token, (deps.now ?? (() => new Date()))())
|
||||
: null;
|
||||
if (!token || !session) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
// Sliding session: the cookie's Max-Age moves with the stored expiry.
|
||||
if (session.renewed) writeStudentSessionCookie(c, token);
|
||||
c.set('student', { accountId: session.accountId, sessionId: session.sessionId });
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
export const studentSession = requireStudentSession();
|
||||
|
||||
/** The signed-in student, on a route behind `studentSession`. */
|
||||
export function currentStudent(c: Context<BackendEnv>): StudentContext {
|
||||
const student = c.get('student');
|
||||
if (!student) throw new Error('currentStudent() used on a route without studentSession');
|
||||
return student;
|
||||
}
|
||||
31
apps/backend/src/modules/student-portal/routes.ts
Normal file
31
apps/backend/src/modules/student-portal/routes.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Hono } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import classesRoute from './features/classes/route';
|
||||
import consumeLinkRoute from './features/consume-link/route';
|
||||
import feesRoute from './features/fees/route';
|
||||
import linkInfoRoute from './features/link-info/route';
|
||||
import logoutRoute from './features/logout/route';
|
||||
import meRoute from './features/me/route';
|
||||
import passkeysRoute from './features/passkeys/route';
|
||||
import recoveryEmailRoute from './features/recovery-email/route';
|
||||
import requestRecoveryRoute from './features/request-recovery/route';
|
||||
import { studentOriginGuard } from './middleware';
|
||||
|
||||
/* Student API. Outside the teacher's session middleware (public prefix): each
|
||||
private route declares `studentSession`, which only accepts the student
|
||||
cookie. Every state-changing request passes the Origin check (CSRF). */
|
||||
const routes = new Hono<BackendEnv>();
|
||||
|
||||
routes.use('*', studentOriginGuard);
|
||||
|
||||
routes.route('/', linkInfoRoute);
|
||||
routes.route('/', consumeLinkRoute);
|
||||
routes.route('/', requestRecoveryRoute);
|
||||
routes.route('/', meRoute);
|
||||
routes.route('/', logoutRoute);
|
||||
routes.route('/', recoveryEmailRoute);
|
||||
routes.route('/', passkeysRoute);
|
||||
routes.route('/', classesRoute);
|
||||
routes.route('/', feesRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -60,6 +60,8 @@ export class SendPaymentReminders {
|
||||
checkoutUrl: { not: null },
|
||||
dueDate: { lte: new Date(now.getTime() + DUE_HORIZON_MS) },
|
||||
attendee: { status: 'ACTIVE' },
|
||||
// Already reported by the student: the teacher is reviewing it.
|
||||
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { CountryCode } from '@gruperly/shared';
|
||||
import { DEFAULT_COUNTRY } from '@gruperly/shared';
|
||||
import { COUNTRY_TIME_ZONES, DEFAULT_COUNTRY } from '@gruperly/shared';
|
||||
|
||||
/* Amounts and dates go inside a WhatsApp message, so they are formatted the way
|
||||
people in the teacher's country write them (the student is there too). */
|
||||
@@ -14,15 +14,7 @@ const LOCALES: Record<CountryCode, string> = {
|
||||
UY: 'es-UY',
|
||||
};
|
||||
|
||||
const TIME_ZONES: Record<CountryCode, string> = {
|
||||
AR: 'America/Argentina/Buenos_Aires',
|
||||
BR: 'America/Sao_Paulo',
|
||||
CL: 'America/Santiago',
|
||||
CO: 'America/Bogota',
|
||||
MX: 'America/Mexico_City',
|
||||
PE: 'America/Lima',
|
||||
UY: 'America/Montevideo',
|
||||
};
|
||||
const TIME_ZONES = COUNTRY_TIME_ZONES;
|
||||
|
||||
/** `25000` ARS → `$ 25.000`; cents only when there are any. */
|
||||
export function formatAmount(
|
||||
|
||||
@@ -4,6 +4,7 @@ import { logger } from '@/logger';
|
||||
import { startBillingJobs } from '@/modules/billing';
|
||||
import { startMpJobs } from '@/modules/mp';
|
||||
import { startPaymentJobs } from '@/modules/payments';
|
||||
import { startStudentAccessJobs } from '@/modules/student-access';
|
||||
import { startWhatsappJobs } from '@/modules/whatsapp';
|
||||
|
||||
const port = Number(process.env.PORT ?? 4000);
|
||||
@@ -19,6 +20,7 @@ startMpJobs();
|
||||
startPaymentJobs();
|
||||
startWhatsappJobs();
|
||||
startBillingJobs();
|
||||
startStudentAccessJobs();
|
||||
|
||||
async function shutdown(): Promise<void> {
|
||||
server.stop(true);
|
||||
|
||||
Reference in New Issue
Block a user