Skip to content

Instantly share code, notes, and snippets.

@bradley-pp
Created January 17, 2025 17:11
Show Gist options
  • Select an option

  • Save bradley-pp/d6f52a4f9f1a05feabc0a09524ab66de to your computer and use it in GitHub Desktop.

Select an option

Save bradley-pp/d6f52a4f9f1a05feabc0a09524ab66de to your computer and use it in GitHub Desktop.
@Injectable()
abstract class AuthGuard implements CanActivate {
protected constructor(
private readonly cls: ClsService,
private readonly tokenValidator: Record<string, (token: string) => string | null>,
) {}
canActivate(
context: ExecutionContext,
): boolean {
const request = context.switchToHttp().getRequest<Request>();
const [_, token] = request.get("Authorization").split(" ")
const user = this.tokenValidator.validateToken(token);
if (!user) {
return false;
}
this.cls.set("userId", user);
return true;
}
}
@Injectable()
class MeInterceptor implements NestInterceptor {
constructor(
private readonly cls: ClsService
) {}
intercept(context: ExecutionContext, next: CallHandler) {
const request = context.switchToHttp().getRequest<Request>();
const userIdParam = request.params.userId;
if (!userIdParam || userIdParam.toLowerCase() !== "me") {
return;
}
request.params.userId = this.cls.get("userId");
return next.handle();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment