Files
TREK/server/src/nest/auth-core/cookie-auth.guard.ts
T
Maurice 2c3fb15263 style(server): format the files the health lanes added or moved
Prettier on every new or moved file that was not formatted, so lint:format
holds them; the files taken off the format baseline are the ones that moved
or were formatted on the way.
2026-10-10 20:16:04 +02:00

45 lines
1.8 KiB
TypeScript

import { UserSessions } from '../../db/entities/UserSessions.entity';
import { Users } from '../../db/entities/Users.entity';
import { verifyJwtAndLoadUser } from './jwt-verify';
import { EntityManager } from '@mikro-orm/core';
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
import type { Request } from 'express';
/**
* Mirrors the legacy `requireCookieAuth` middleware: accepts ONLY the httpOnly
* trek_session cookie (never a Bearer token), so CSRF-sensitive state-changing
* OAuth endpoints (consent submit, client/session mutations) can't be driven by
* a leaked Bearer. Error bodies + codes match the legacy 401 shapes exactly.
*
* `EntityManager` injection, not `@InjectRepository(Users)` — same reasoning
* as `JwtAuthGuard` (Plan 3b Task 1 RULING): the guard is instantiated per the
* HOST controller's module, and using the always-global `EntityManager`
* avoids new `forFeature` wiring in every module that applies it.
*/
@Injectable()
export class CookieAuthGuard implements CanActivate {
constructor(private readonly em: EntityManager) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest<Request & { cookies?: Record<string, string> }>();
const cookieToken = req.cookies?.trek_session;
if (!cookieToken) {
throw new HttpException(
{ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' },
401,
);
}
const user = await verifyJwtAndLoadUser(
cookieToken,
this.em.getRepository(Users),
this.em.getRepository(UserSessions),
);
if (!user) {
throw new HttpException({ error: 'Invalid or expired session', code: 'AUTH_REQUIRED' }, 401);
}
req.user = user;
return true;
}
}