@nestjs/common#CanActivate TypeScript Examples
The following examples show how to use
@nestjs/common#CanActivate.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: environment.guard.ts From relate with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class EnvironmentGuard implements CanActivate {
constructor(@Inject(SystemProvider) private readonly systemProvider: SystemProvider) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const ctx = GqlExecutionContext.create(context);
const {fieldName} = ctx.getInfo();
const {environmentNameOrId} = ctx.getArgs();
const environment = await this.systemProvider.getEnvironment(environmentNameOrId);
return environment.supports(fieldName);
}
}
Example #2
Source File: google-recaptcha.guard.ts From google-recaptcha with MIT License | 6 votes |
@Injectable()
export class GoogleRecaptchaGuard implements CanActivate {
constructor(private readonly validator: GoogleRecaptchaValidator,
private readonly reflector: Reflector,
private readonly requestResolver: RecaptchaRequestResolver,
@Inject(RECAPTCHA_OPTIONS) private readonly options: GoogleRecaptchaGuardOptions) {
}
async canActivate(context: ExecutionContext): Promise<true | never> {
const request = this.options.applicationType
? this.requestResolver.resolveByApplicationType(context, this.options.applicationType)
: this.requestResolver.resolve(context);
const skip = typeof this.options.skipIf === 'function'
? await this.options.skipIf(request)
: !!this.options.skipIf;
if (skip) {
return true;
}
const options: VerifyResponseDecoratorOptions = this.reflector.get(RECAPTCHA_VALIDATION_OPTIONS, context.getHandler());
const response = options?.response
? await options?.response(request)
: await this.options.response(request);
const score = options?.score || this.options.score;
const action = options?.action;
request.recaptchaValidationResult = await this.validator.validate({response, score, action});
if (request.recaptchaValidationResult.success) {
return true;
}
throw new GoogleRecaptchaException(request.recaptchaValidationResult.errors);
}
}
Example #3
Source File: auth.guard.ts From codeclannigeria-backend with MIT License | 6 votes |
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
return await this.validateRequest(request);
}
async validateRequest(request: Request): Promise<boolean> {
if (!configuration().isAuthEnabled) return true;
const { email, password }: LoginReqDto = request.body;
const user = await this.authService.validateUser(email, password);
if (!user || !user.isActive) throw new UnauthorizedException();
request.user = user;
return true;
}
}
Example #4
Source File: roles.guard.ts From edu-server with MIT License | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request['user'];
const hasRole = () => roles.includes(user.role);
return user && user.role && hasRole();
}
}
Example #5
Source File: auth.guard.ts From bad-cards-game with GNU Affero General Public License v3.0 | 6 votes |
@Injectable()
export class AuthGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const authorization = request.headers['authorization'];
if (authorization && authorization.startsWith('Bearer ')) {
const token = authorization.substring(7, authorization.length);
request.user = await admin.auth().verifyIdToken(token);
return !!request.user;
}
return false;
}
}
Example #6
Source File: access.guard.ts From nest-casl with MIT License | 6 votes |
@Injectable()
export class AccessGuard implements CanActivate {
constructor(
private reflector: Reflector,
private readonly accessService: AccessService,
private moduleRef: ModuleRef,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const ability = this.reflector.get<AbilityMetadata | undefined>(CASL_META_ABILITY, context.getHandler());
const request = await ContextProxy.create(context).getRequest();
const { getUserHook } = CaslConfig.getRootOptions();
const req = new RequestProxy(request);
req.setUserHook(await userHookFactory(this.moduleRef, getUserHook));
req.setSubjectHook(await subjectHookFactory(this.moduleRef, ability?.subjectHook));
return await this.accessService.canActivateAbility(request, ability);
}
}
Example #7
Source File: roles.guard.ts From nestjs-rest-sample with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const roles = this.reflector.get<RoleType[]>(
HAS_ROLES_KEY,
context.getHandler(),
);
if (!roles || roles.length == 0) {
return true;
}
const {
user,
} = context.switchToHttp().getRequest() as AuthenticatedRequest;
return user.roles && user.roles.some((r) => roles.includes(r));
}
}
Example #8
Source File: roles.guard.ts From pandaid with MIT License | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler())
if (!roles) {
return true
}
const request = context.switchToHttp().getRequest()
const user = request.user
return roles.includes(user.role)
}
}
Example #9
Source File: auth.guard.ts From life-helper-backend with MIT License | 6 votes |
/**
* 用于需要登录的接口(即需要 `userId` 参数的控制器方法)
*
* 校验条件:
* 1. `request` 对象挂载 `user` 对象
* 2. `user` 对象的 `id` 值大于 0
*/
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request: ExtRequest = context.switchToHttp().getRequest()
if (request.user && request.user.id > 0) {
return true
} else {
throw new HttpException(INVALID_AUTH_INFO, HttpStatus.UNAUTHORIZED)
}
}
}
Example #10
Source File: roles.guard.ts From nestjs-starter-rest-api with MIT License | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<ROLE[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
if (requiredRoles.some((role) => user.roles?.includes(role))) {
return true;
}
throw new UnauthorizedException(
`User with roles ${user.roles} does not have access to this route with roles ${requiredRoles}`,
);
}
}
Example #11
Source File: auth.guard.ts From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class AuthGuard implements CanActivate {
canActivate = async (context: ExecutionContext): Promise<boolean> => {
const request = context.switchToHttp().getRequest();
if (!request.headers.autorization) return false;
request.user = await this.verifyToken(request.headers.autorization);
return true;
};
private verifyToken = async (auth: string) => {
const authHeader = auth.split(' ');
if (authHeader[0] !== 'Bearer') {
throw new HttpException('Unauthorized token', HttpStatus.UNAUTHORIZED);
}
try {
const token = authHeader[1];
const decode = await verify(token, process.env.SECRET);
return decode;
} catch (err) {
const message = 'Token error: ' + (err.message || err.name);
throw new HttpException(message, HttpStatus.UNAUTHORIZED);
}
};
}
Example #12
Source File: auth.guard.ts From nestjs-mercurius with MIT License | 6 votes |
@Injectable()
export class AuthGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const ctx = GqlExecutionContext.create(context);
const { authorization } = ctx.getContext().headers;
return authorization && authorization === 'ok';
}
}
Example #13
Source File: roles.guard.ts From api with GNU Affero General Public License v3.0 | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const ctx = GqlExecutionContext.create(context);
const roles = this.reflector.get<string[]>('roles', ctx.getHandler());
if (!roles) {
return true;
}
const userRoles = ctx.getContext().req.user ? ctx.getContext().req.user.roles : []
for (const role of roles) {
if (!userRoles.includes(role)) {
return false;
}
}
return true;
}
}
Example #14
Source File: roles.guard.ts From bank-server with MIT License | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly _reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this._reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const { role } = <UserAuthEntity>request.user.userAuth;
return roles.includes(role);
}
}
Example #15
Source File: roles.guard.ts From MyAPI with MIT License | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(
private readonly reflector: Reflector
) {}
canActivate(
context: ExecutionContext
): boolean | Promise<boolean> | Observable<boolean> {
const roles = this.reflector.get<DefaultRole[]>('roles', context.getHandler())
if (!roles || !roles.length) {
return true
}
const request = context.switchToHttp().getRequest()
const payload = request.user as AuthPayload
const hasRole = () => !!roles.some(role => role === payload.role)
return payload && payload.role && hasRole()
}
}
Example #16
Source File: HttpRoleAuthGuard.ts From typescript-clean-architecture with MIT License | 6 votes |
@Injectable()
export class HttpRoleAuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector
) {}
public async canActivate(context: ExecutionContext): Promise<boolean> {
const roles: UserRole[] = this.reflector.get<UserRole[]>('roles', context.getHandler()) || [];
const request: HttpRequestWithUser = context.switchToHttp().getRequest();
const canActivate: boolean = roles.length > 0
? roles.includes(request.user.role)
: true;
if (!canActivate) {
throw Exception.new({code: Code.ACCESS_DENIED_ERROR});
}
return canActivate;
}
}
Example #17
Source File: auth.guard.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private permissionService: PermissionService,
private reflector: Reflector,
) {}
async canActivate(
context: ExecutionContext,
): Promise<boolean> {
const request = context.switchToHttp().getRequest() as IncomingMessage & { user: any };
const permissions = this.reflector.get<string[]>('permissions', context.getHandler());
try {
const hasPermission = await this.permissionService.hasPermission(request.user?.uuid || request.headers.authorization, permissions)
if (!hasPermission) {
throw new ForbiddenException(`Missing permissions: ${permissions.join(", ")}`)
}
} catch (e) {
throw e;
}
return true;
}
}
Example #18
Source File: FabricEndpointGuard.ts From tatum-blockchain-connector with MIT License | 6 votes |
export class FabricEndpointGuard implements CanActivate {
public canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
if (request.header(FABRIC_HEADER_ENDPOINT)?.length) {
return true;
}
throw new FabricError(`Http header ${FABRIC_HEADER_ENDPOINT} not present.`, 'header.missing', 400)
}
}
Example #19
Source File: admin.guard.ts From NextJS-NestJS-GraphQL-Starter with MIT License | 6 votes |
@Injectable()
export class AdminGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();
return Boolean(req.user && req.user.role === Roles.ADMIN);
}
}
Example #20
Source File: auth.guard.ts From twilio-voice-notification-app with Apache License 2.0 | 6 votes |
/**
* AuthGuard acts as an authorization middleware. All the Controllers / Endpoints
* decorated with this Guard expect to receive a 'x-twilio-notification-key'
* in the headers object to match the one stored in ENV variables.
* Otherwise, a 403 response will be sent.
*/
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private configService: ConfigService) {}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const { headers } = request;
const header = headers[AUTH_HEADDER];
const passcode = this.configService.get<string>(ENV_VAR.PASSCODE_KEY);
return header && header === passcode;
}
}
Example #21
Source File: levels.guard.ts From aqualink-app with MIT License | 6 votes |
@Injectable()
export class LevelsGuard implements CanActivate {
constructor(private reflector: Reflector) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.get<boolean>(
'isPublic',
context.getHandler(),
);
if (isPublic) {
return true;
}
const levels = this.reflector.get<AdminLevel[]>(
'levels',
context.getHandler(),
);
if (!levels || !levels.length) {
return true;
}
const request = context.switchToHttp().getRequest<AuthRequest>();
const { user } = request;
const hasAccess = levels.findIndex((l) => l === user.adminLevel) !== -1;
return hasAccess;
}
}
Example #22
Source File: roles.guard.ts From nest-js-quiz-manager with MIT License | 6 votes |
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector, private userService: UserService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
const request = context.switchToHttp().getRequest();
if (request?.user) {
const { id } = request.user;
const user = await this.userService.getUserById(id);
return roles.includes(user.role);
}
return false;
}
}
Example #23
Source File: roles.guard.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class RolesGuard implements CanActivate {
constructor(
private reflector: Reflector,
private jwtService: JwtService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request: Request = context.switchToHttp().getRequest();
const tokenData = (await this.jwtService
.decode(request.headers.authorization?.split('Bearer')[1].trim() as string) as JwtDecodeResponse | null);
if (tokenData?.role === RolesEnum.admin) {
return true;
}
return !tokenData ? false : roles.includes(tokenData?.role);
}
}
Example #24
Source File: collection.guard.ts From aqualink-app with MIT License | 6 votes |
export class CollectionGuard implements CanActivate {
constructor(
@InjectRepository(Collection)
private collectionRepository: Repository<Collection>,
private reflector: Reflector,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.get<boolean>(
'isPublic',
context.getHandler(),
);
if (isPublic) {
return true;
}
const request = context.switchToHttp().getRequest();
const { user }: { user: User } = request;
const { collectionId }: { collectionId: string } = request.params;
if (!Number.isNaN(parseInt(collectionId, 10))) {
const hasCollection = await this.collectionRepository.findOne({
where: {
id: collectionId,
user,
},
});
return !!hasCollection;
}
return false;
}
}
Example #25
Source File: roles.guard.ts From nest-js-boilerplate with MIT License | 6 votes |
@Injectable()
export default class RolesGuard implements CanActivate {
constructor(
private reflector: Reflector,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const req = context.switchToHttp().getRequest();
if (req.isUnauthenticated()) {
throw new UnauthorizedException('Login please');
}
return roles.some((role) => role === req?.user?.role);
}
}
Example #26
Source File: is-owner.guard.ts From NestJs-youtube with MIT License | 6 votes |
@Injectable()
export class IsOwnerGuard implements CanActivate {
constructor(private service: PostsService) { }
async canActivate(
context: ExecutionContext,
): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const user = (request as any).user;
const body = (request as any).body;
console.log({ params: request.params, body, user, IsOwnerGuard: true });
return this.canI(+request.params.id, +user.id);
}
private async canI(id: number, user_id: number): Promise<boolean> {
const p: Partial<PostEntity> = await this.service.postRepo.findOne(id);
console.log({ postIFound: p });
return p.user_id === user_id;
}
}
Example #27
Source File: role.guard.ts From nestjs-api-example with MIT License | 6 votes |
// RolesGuard 예제
// Guard는 각 Middleware 이후, Interceptors 또는 Pipes 전에 실행된다.
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
return true;
// matchRoles를 구현하면 Role 체크가 가능하다.
// return matchRoles(roles, user.roles);
}
}
Example #28
Source File: request-scoped.guard.ts From nestjs-mercurius with MIT License | 6 votes |
@Injectable({ scope: Scope.REQUEST })
export class Guard implements CanActivate {
static COUNTER = 0;
static REQUEST_SCOPED_DATA = [];
constructor(@Inject('REQUEST_ID') private requestId: number) {
Guard.COUNTER++;
}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
Guard.REQUEST_SCOPED_DATA.push(this.requestId);
return true;
}
}
Example #29
Source File: auth-guards.ts From Cromwell with MIT License | 6 votes |
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private reflector: Reflector) { }
async canActivate(context: ExecutionContext): Promise<boolean> {
if (getStoreItem('cmsSettings')?.installed === false) return true;
const request: TRequestWithUser = context.switchToHttp().getRequest();
if (!request.user?.id) return false;
const roles = this.reflector.get<TAuthRole[]>('roles', context.getHandler());
return matchRoles(request.user, roles);
}
}