Files
gruperly/apps/backend/src/http/session-auth.ts
Jose Selesan 060a4f09e4 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>
2026-10-28 15:39:09 -03:00

75 lines
2.5 KiB
TypeScript

import type { MiddlewareHandler } from 'hono';
import { auth } from '@/modules/auth/auth';
import type { BackendEnv } from './env';
import { problemJson, unauthorizedProblem } from './problem-details';
export const sessionAuthMiddleware: MiddlewareHandler<BackendEnv> = async (c, next) => {
if (isPublicApiRequest(c.req.method, c.req.path)) {
await next();
return;
}
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
c.set('user', session.user);
c.set('session', session.session);
await next();
};
export function isPublicApiRequest(method: string, path: string): boolean {
if (method === 'OPTIONS') {
return true;
}
const normalizedPath = normalizePath(path);
// Absence notice sent with the attendee's personal token (no session).
if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') {
return true;
}
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
return true;
}
// WhatsApp provider webhooks: no session, authenticated by their HMAC signature.
if (
method === 'POST'
&& (normalizedPath === '/api/v1/whatsapp/webhooks/openwa'
|| normalizedPath === '/api/v1/whatsapp/webhooks/kapso')
) {
return true;
}
// Mercado Pago notifications about Pro subscriptions, one URL per country:
// no session, authenticated by Mercado Pago's `x-signature`.
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
return true;
}
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
return true;
}
return (
normalizedPath === '/api/v1/health'
|| 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')
);
}
function matchesPublicPrefix(path: string, prefix: string): boolean {
return path === prefix || path.startsWith(`${prefix}/`);
}
function normalizePath(path: string): string {
const withoutQuery = path.split('?')[0]?.split('#')[0] ?? path;
return withoutQuery.length > 1 && withoutQuery.endsWith('/')
? withoutQuery.slice(0, -1)
: withoutQuery;
}