33 lines
952 B
TypeScript
33 lines
952 B
TypeScript
import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
|
|
import type { IdentitySessionPort } from '@core/identity/application/ports/IdentitySessionPort';
|
|
import { IDENTITY_SESSION_PORT_TOKEN } from './AuthProviders';
|
|
|
|
type AuthenticatedRequest = {
|
|
user?: { userId: string; role?: string | undefined };
|
|
};
|
|
|
|
@Injectable()
|
|
export class AuthenticationGuard implements CanActivate {
|
|
constructor(
|
|
@Inject(IDENTITY_SESSION_PORT_TOKEN)
|
|
private readonly sessionPort: IdentitySessionPort,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
|
|
|
if (request.user?.userId) {
|
|
return true;
|
|
}
|
|
|
|
const session = await this.sessionPort.getCurrentSession();
|
|
if (session?.user?.id) {
|
|
request.user = {
|
|
userId: session.user.id,
|
|
role: session.user.role
|
|
};
|
|
}
|
|
|
|
return true;
|
|
}
|
|
} |