@nestjs/common#ExecutionContext TypeScript Examples
The following examples show how to use
@nestjs/common#ExecutionContext.
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: auth.guard.ts From bad-cards-game with GNU Affero General Public License v3.0 | 7 votes |
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 #2
Source File: util.ts From nest-keycloak-connect with MIT License | 7 votes |
extractRequest = (context: ExecutionContext): [any, any] => {
let request: any, response: any;
// Check if request is coming from graphql or http
if (context.getType() === 'http') {
// http request
const httpContext = context.switchToHttp();
request = httpContext.getRequest();
response = httpContext.getResponse();
} else if (context.getType<GqlContextType>() === 'graphql') {
let gql: any;
// Check if graphql is installed
try {
gql = require('@nestjs/graphql');
} catch (er) {
throw new Error('@nestjs/graphql is not installed, cannot proceed');
}
// graphql request
const gqlContext = gql.GqlExecutionContext.create(context).getContext();
request = gqlContext.req;
response = gqlContext.res;
}
return [request, response];
}
Example #3
Source File: logging.interceptor.ts From 42_checkIn with GNU General Public License v3.0 | 6 votes |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
return next
.handle()
.pipe(
tap(() =>
this.logger.log(
context.switchToHttp().getRequest().route.path,
context.getHandler().name,
Date.now() - now + 'ms',
),
),
);
}
Example #4
Source File: gcloud-storage-files.interceptor.ts From nestjs-gcloud-storage with MIT License | 6 votes |
export function GCloudStorageFilesInterceptor(
fieldName: string,
localOptions?: MulterOptions,
gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
@Injectable()
class MixinInterceptor implements NestInterceptor {
public interceptor: NestInterceptor;
constructor(private readonly gcloudStorage: GCloudStorageService) {
this.interceptor = new (FilesInterceptor(fieldName, 20, localOptions))();
}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
(await this.interceptor.intercept(context, next)) as Observable<any>;
const request = context.switchToHttp().getRequest();
const files = request[fieldName];
if (!files.length) {
Logger.error(
'GCloudStorageFilesInterceptor',
`Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFilesInterceptor('${fieldName}')?`,
);
return;
}
for (const file of files) file.storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
return next.handle();
}
}
const Interceptor = mixin(MixinInterceptor);
return Interceptor as Type<NestInterceptor>;
}
Example #5
Source File: auth-guards.ts From Cromwell with MIT License | 6 votes |
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);
}
Example #6
Source File: gql-execution-context.ts From nestjs-mercurius with MIT License | 6 votes |
static create(context: ExecutionContext): GqlExecutionContext {
const type = context.getType();
const gqlContext = new GqlExecutionContext(
context.getArgs(),
context.getClass(),
context.getHandler(),
);
gqlContext.setType(type);
return gqlContext;
}
Example #7
Source File: role.guard.ts From nestjs-api-example with MIT License | 6 votes |
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 #8
Source File: is-owner.guard.ts From NestJs-youtube with MIT License | 6 votes |
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);
}
Example #9
Source File: roles.guard.ts From nest-js-boilerplate with MIT License | 6 votes |
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 user = request.user as UserDocument;
return user.role === RolesEnum.admin || roles.includes(user.role);
}
Example #10
Source File: exception.interceptor.ts From domain-driven-hexagon with MIT License | 6 votes |
intercept(
_context: ExecutionContext,
next: CallHandler,
): Observable<ExceptionBase> {
return next.handle().pipe(
catchError(err => {
/**
* Custom exceptions are converted to nest.js exceptions.
* This way we are not tied to a framework or HTTP protocol.
*/
if (err instanceof NotFoundException) {
throw new NestNotFoundException(err.message);
}
if (err instanceof ConflictException) {
throw new NestConflictException(err.message);
}
return throwError(err);
}),
);
}
Example #11
Source File: gql.auth-guard.ts From svvs with MIT License | 6 votes |
/**
* getRequest return ExecutionContext as GqlExecutionContext request
*
* @param context
*/
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context)
return ctx.getContext().req
}
Example #12
Source File: admin-role.guard.ts From nest-js-quiz-manager with MIT License | 6 votes |
async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
if (request?.user) {
const { id } = request.user;
const user = await this.userService.getUserById(id);
return user.role === UserRoles.ADMIN;
}
return false;
}
Example #13
Source File: defaultAuth.guard.template.ts From amplication with Apache License 2.0 | 6 votes |
canActivate(
context: ExecutionContext
): boolean | Promise<boolean> | Observable<any> {
const isPublic = this.reflector.get<boolean>(
IS_PUBLIC_KEY,
context.getHandler()
);
if (isPublic) {
return true;
}
return super.canActivate(context);
}
Example #14
Source File: auth.guard.ts From nestjs-keycloak-admin with MIT License | 6 votes |
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic: boolean = this.reflector.get<boolean>(META_PUBLIC, context.getHandler())
if (isPublic) {
return true
}
const request = extractRequest(context)
const jwt = this.extractJwt(request.headers)
try {
const result = await this.keycloak.connect.grantManager.validateAccessToken(jwt)
if (typeof result === 'string') {
request.user = await this.keycloak.connect.grantManager.userInfo<string, KeycloakUser>(jwt)
request.accessToken = jwt
return true
}
} catch (error) {
this.logger.warn(`Error occurred validating token`, error)
}
throw new UnauthorizedException()
}
Example #15
Source File: collection.guard.ts From aqualink-app with MIT License | 6 votes |
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 #16
Source File: execution-context-host.d.ts From nest-jaeger with MIT License | 6 votes |
export declare class ExecutionContextHost implements ExecutionContext {
private readonly args;
private readonly constructorRef;
private readonly handler;
private contextType;
constructor(args: any[], constructorRef?: Type<any>, handler?: Function);
setType<TContext extends string = ContextType>(type: TContext): void;
getType<TContext extends string = ContextType>(): TContext;
getClass<T = any>(): Type<T>;
getHandler(): Function;
getArgs<T extends Array<any> = any[]>(): T;
getArgByIndex<T = any>(index: number): T;
switchToRpc(): RpcArgumentsHost;
switchToHttp(): HttpArgumentsHost;
switchToWs(): WsArgumentsHost;
}
Example #17
Source File: recaptcha-result.ts From google-recaptcha with MIT License | 6 votes |
RecaptchaResult = createParamDecorator((data, context: ExecutionContext) => {
switch (context.getType<'http' | 'graphql'>()) {
case 'http':
return context.switchToHttp().getRequest().recaptchaValidationResult;
case 'graphql':
const graphqlModule = loadModule('@nestjs/graphql', true);
return graphqlModule.GqlExecutionContext.create(context).getContext().req?.connection?._httpMessage?.req?.recaptchaValidationResult;
default:
return null;
}
})
Example #18
Source File: roles.guard.ts From codeclannigeria-backend with MIT License | 6 votes |
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<UserRole[]>(
UserRole,
context.getHandler()
);
if (!roles || !configuration().isAuthEnabled) return true;
const request = context.switchToHttp().getRequest<Request>();
const { role } = request.user as JwtPayload;
return roles.includes(role);
}
Example #19
Source File: roles.guard.ts From edu-server with MIT License | 6 votes |
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 #20
Source File: tracing-context.decorator.ts From nestjs-jaeger-tracing with MIT License | 6 votes |
Tracing = createParamDecorator(
(key: keyof TracingData, context: ExecutionContext) => {
const contextType = context.getType<GqlContextType>();
let tracingData: TracingData;
if (contextType === 'graphql') {
const ctx = GqlExecutionContext.create(context);
tracingData = ctx.getContext<TracingObject>().tracing;
}
if (contextType === 'http') {
const ctx = context.switchToHttp();
tracingData = ctx.getRequest<TracingObject>().tracing;
}
if (contextType === 'rpc') {
const ctx = context.switchToRpc();
tracingData = ctx.getContext<TracingObject>().tracing;
}
return key ? tracingData && tracingData[key] : tracingData;
},
)
Example #21
Source File: access.guard.ts From nest-casl with MIT License | 6 votes |
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 #22
Source File: local-auth.guard.spec.ts From nestjs-rest-sample with GNU General Public License v3.0 | 6 votes |
describe('LocalAuthGuard', () => {
let guard: LocalAuthGuard;
beforeEach(() => {
guard = new LocalAuthGuard();
});
it('should be defined', () => {
expect(guard).toBeDefined();
});
it('should return true for `canActivate`', async () => {
AuthGuard('local').prototype.canActivate = jest.fn(() =>
Promise.resolve(true),
);
AuthGuard('local').prototype.logIn = jest.fn(() => Promise.resolve());
expect(await guard.canActivate({} as ExecutionContext)).toBe(true);
});
});
Example #23
Source File: roles.guard.ts From pandaid with MIT License | 6 votes |
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 #24
Source File: auth.guard.ts From life-helper-backend with MIT License | 6 votes |
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 #25
Source File: datadog.interceptor.ts From ironfish-api with Mozilla Public License 2.0 | 6 votes |
intercept(
context: ExecutionContext,
next: CallHandler<unknown>,
): Observable<unknown> {
const start = new Date().getTime();
return next.handle().pipe(
tap(() => {
const duration = new Date().getTime() - start;
const request = context.switchToHttp().getRequest<Request>();
if (!request) {
return;
}
this.datadogService.timing('requests.success', duration, {
method: request.method,
path: request.path,
});
}),
catchError((error: Error) => {
let method = 'no-method';
let path = 'no-path';
const request = context.switchToHttp().getRequest<Request>();
if (request) {
method = request.method;
path = request.path;
}
this.datadogService.increment('requests.error', 1, {
method,
path,
type: error.constructor.name,
});
return throwError(() => error);
}),
);
}
Example #26
Source File: system.interceptor.ts From emutypekov with GNU General Public License v3.0 | 6 votes |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.getArgByIndex(0);
this.logger.debug(
`${context.getType()}: ${req.socket.remoteAddress} => Request: ${
req.url
}`,
);
const response: Response = context.switchToHttp().getResponse();
response.setHeader('X-Powered-By', 'EmuTypekov');
response.setHeader('Set-Cookie', 'PHPSESSID=undefined');
return next.handle().pipe(
map((body) => {
return body;
}),
);
}
Example #27
Source File: logging.interceptor.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest()
const method = request.method
const url = request.originalUrl
const requestID = request.headers[REQUEST_ID_TOKEN_HEADER]
this.appLogger.log({ method, requestID, url })
const now = Date.now()
return next.handle().pipe(
tap(() => {
const response = context.switchToHttp().getResponse()
const statusCode = response.statusCode
const responseTime = Date.now() - now
this.appLogger.log({ method, requestID, url, statusCode, responseTime })
})
)
}
Example #28
Source File: roles.guard.ts From nestjs-starter-rest-api with MIT License | 6 votes |
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 #29
Source File: logging.interceptor.ts From Phantom with MIT License | 6 votes |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
const req = context.switchToHttp().getRequest();
const method = req.method;
const url = req.url;
return next
.handle()
.pipe(
tap(() =>
Logger.log(
`${method} ${url} ${Date.now() - now}ms`,
context.getClass().name,
),
),
);
}