email-allowlist.guard.tsβ’1.16 kB
import { Injectable, ExecutionContext, UnauthorizedException, CanActivate } from '@nestjs/common'
import { AllowlistService } from './allowlist.service'
/**
* Guard that validates email allowlist after JWT authentication
* This guard assumes that McpAuthJwtGuard has already authenticated the user
* and populated request.user with the JWT payload containing the email
*/
@Injectable()
export class EmailAllowlistGuard implements CanActivate {
constructor(private readonly allowlistService: AllowlistService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
// Get the request object (user should already be authenticated by McpAuthJwtGuard)
const request = context.switchToHttp().getRequest()
const user = request.user
// Check if user has an email
if (!user || !user.email) {
throw new UnauthorizedException('User email not found in token')
}
// Check if email is in the allowlist
if (!this.allowlistService.isEmailAllowed(user.email)) {
throw new UnauthorizedException(
`Email ${user.email} is not authorized to access this resource`,
)
}
return true
}
}