Skip to content

Instantly share code, notes, and snippets.

@EndyKaufman
Created August 28, 2019 07:43
Show Gist options
  • Save EndyKaufman/2864fb73351b67770d8aff2bfca8adf6 to your computer and use it in GitHub Desktop.
Save EndyKaufman/2864fb73351b67770d8aff2bfca8adf6 to your computer and use it in GitHub Desktop.
access.guard.ts
import { ExecutionContext, Injectable, Logger } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { User } from '../entities/user.entity';
import { GqlExecutionContext } from '@nestjs/graphql';
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context.host';
@Injectable()
export class AccessGuard extends AuthGuard('jwt') {
constructor(private readonly reflector: Reflector) {
super();
}
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
async canActivate(context: ExecutionContext) {
try {
await super.canActivate(context);
} catch (error) {}
const roles = this.reflector.get<string[]>('roles', context.getHandler());
const permissions = this.reflector.get<string[]>(
'permissions',
context.getHandler()
);
const request =
context.switchToHttp().getRequest() || this.getRequest(context);
const user: User = request.user;
Logger.log(JSON.stringify(user), AccessGuard.name);
const hasRole = roles
? roles.filter(roleName => user && user instanceof User && user[roleName])
.length > 0
: null;
const hasPermission = permissions
? user && user instanceof User && user.checkPermissions(permissions)
: null;
return (
hasRole === true ||
hasPermission === true ||
(hasRole === null && hasPermission === null)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment