import { AppError } from '../common/errors/app-error'; import { Injectable } from '@nestjs/common'; import { DatabaseService } from '../database/database.service'; import { recordAudit } from './audit'; import type { Principal } from './identity.types'; @Injectable() export class AuthStore { constructor(private readonly db: DatabaseService) {} findUser(organizationId: string, email: string) { return this.db.user.findUnique({ where: { organizationId_email: { organizationId, email } }, }); } async createSession( userId: string, expectedHash: string, tokenHash: string, expiresAt: Date, ) { return this.db.$transaction(async (tx) => { await tx.$queryRaw`SELECT id FROM users WHERE id = ${userId}::uuid FOR UPDATE`; const user = await tx.user.findUniqueOrThrow({ where: { id: userId } }); if (user.status !== 'ACTIVE' || user.passwordHash !== expectedHash) throw new AppError('SESSION_INVALID', 'LOGIN_SNAPSHOT_CHANGED'); await tx.session.create({ data: { userId, tokenHash, expiresAt } }); await recordAudit( tx, user.organizationId, user.id, 'auth.login', user.id, ); }); } async logout(principal: Principal, all: boolean) { await this.db.$transaction(async (tx) => { await tx.session.deleteMany({ where: all ? { userId: principal.userId } : { id: principal.sessionId }, }); await recordAudit( tx, principal.organizationId, principal.userId, all ? 'auth.logout_all' : 'auth.logout', ); }); } async failedLogin(organizationId: string, userId: string) { await recordAudit( this.db, organizationId, userId, 'auth.login_failed', userId, ); } }