import { CanActivate, ExecutionContext, Injectable, ServiceUnavailableException, UnauthorizedException, } from '@nestjs/common'; import type { FastifyRequest } from 'fastify'; import type { User } from '../../users/user.js'; import { RedisClient } from '../../redis/redis.client.js'; import { UsersService } from '../../users/users.service.js'; import { MetricsService } from '../../metrics/metrics.service.js'; @Injectable() export class CurrentUserGuard implements CanActivate { constructor( private readonly redis: RedisClient, private readonly users: UsersService, private readonly metrics: MetricsService, ) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const authorization = request.headers.authorization; if ( typeof authorization !== 'string' || !/^Bearer\s+[^\s]+$/u.test(authorization) ) { throw new UnauthorizedException({ message: 'Unauthorized', challenge: 'Bearer realm="messenger"', }); } let session: string | null; try { this.metrics.increment('session_get'); session = await this.redis.get( `session:${authorization.slice(7).trim()}`, ); } catch { throw new ServiceUnavailableException('Session store unavailable'); } if (!session) throw new UnauthorizedException({ message: 'Unauthorized', challenge: 'Bearer realm="messenger"', }); let userId: string; try { const parsed: unknown = JSON.parse(session); if ( typeof parsed !== 'object' || parsed === null || !('user_id' in parsed) || typeof parsed.user_id !== 'string' || !('expires_at' in parsed) || typeof parsed.expires_at !== 'string' || !/^(?:\d{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u.test( parsed.expires_at, ) ) throw new Error('invalid session'); const expiresAt = Date.parse(parsed.expires_at); if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt) throw new Error('expired session'); userId = parsed.user_id; } catch { throw new UnauthorizedException({ message: 'Unauthorized', challenge: 'Bearer realm="messenger"', }); } let user: User | undefined; try { user = await this.users.findById(userId); } catch { throw new ServiceUnavailableException( 'Authentication service unavailable', ); } if (!user) throw new UnauthorizedException(); request.currentUser = user; return true; } }