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:
@@ -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 });
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user