Files
gruperly/apps/backend/src/modules/student-portal/features/recovery-email/use-case.ts
Jose Selesan bc5f676cea refactor(web): rutas de la app de alumnos en inglés
/acceso → /access, /alumno/* → /student/* (welcome, classes, payments,
profile, notify-absence, report-payment). El link del mail de confirmación
pasa a /access/email/:token. AGENTS.md documenta que los paths van en inglés.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:50:55 -03:00

144 lines
5.0 KiB
TypeScript

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()}/access/email/${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 });
});
}
}