26 lines
919 B
TypeScript
26 lines
919 B
TypeScript
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
|
import { FastifyRequest } from 'fastify';
|
|
import { ApiError } from '../common/filters/api-error';
|
|
import { AuthService } from './auth.service';
|
|
|
|
const BEARER_CHALLENGE = 'Bearer realm="messenger"';
|
|
|
|
@Injectable()
|
|
export class AuthGuard implements CanActivate {
|
|
constructor(private readonly auth: AuthService) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
|
const match = /^Bearer (\S+)$/i.exec(request.headers.authorization ?? '');
|
|
const session = match ? await this.auth.resolve(match[1]) : null;
|
|
if (!session) {
|
|
throw new ApiError('unauthorized', 'missing or invalid session', {
|
|
'WWW-Authenticate': BEARER_CHALLENGE,
|
|
});
|
|
}
|
|
request.currentUser = session.user;
|
|
request.sessionTokenHash = session.tokenHash;
|
|
return true;
|
|
}
|
|
}
|