Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const rolePermissions: string[] =
this.reflector.get('roles', context.getHandler()) ||
this.reflector.get('roles', context.getClass());
const realmPermissions: string[] =
this.reflector.get('realm', context.getHandler()) ||
this.reflector.get('realm', context.getClass());
const isPublic =
!rolePermissions || rolePermissions.length === 0 || rolePermissions.indexOf(DefaultRoles.public) >= 0;
// Get request data
let request = context.switchToHttp().getRequest();
if (!request) {
const ctx = GqlExecutionContext.create(context);
request = ctx.getContext().req;
}
const headerRealm: string = request.headers.realm || request.query.realm;
if (!isPublic && !headerRealm) {
throw new HttpException('Resource is not public, you must provide "realm" in request headers', 400);
}
const headerAuth: string[] = request.headers.authorization
? request.headers.authorization.split(' ')
: [request.query.token];
if (headerAuth && headerAuth.length > 0 && headerRealm) {
const jwtToken = headerAuth[headerAuth.length - 1] || request.query.token;
if (realmPermissions && realmPermissions.length > 0 && realmPermissions.indexOf(headerRealm) === -1) {
export function getRequestFromContext(context: ExecutionContext): GraphqlRequest {
const request = context.switchToHttp().getRequest();
// Graphql endpoints need a context creation
if (!request) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
// Interestingly, graphql field resolvers pass through the guards again. I suppose that's good?
// These executions however provide different inputs than a fresh Http or GQL request.
// In order to authenticate these, we can retrieve the original request from the context
// that we configured in the GraphQL options in app.module.
// I assign a user to every request in a middleware not shown here
if (!request.user) {
const [parent, ctx, info]: [any, any, GraphQLResolveInfo] = context.getArgs();
// Checking if this looks like a GQL subquery, is this hacky?
if (parent && info && info.parentType) {
return ctx.req;
}
}
async canActivate(context: ExecutionContext): Promise {
const request = context.switchToHttp().getRequest();
if (request) {
if (!request.headers.authorization) {
return false;
}
request.me = await this.validateToken(request.headers.authorization);
return this.validateRole(request.me, context);
} else {
const ctx: any = GqlExecutionContext.create(context).getContext();
if (!ctx.headers.authorization) {
return false;
}
ctx.me = await this.validateToken(ctx.headers.authorization);
return this.validateRole(ctx.me, context);
}
}
async canActivate(context: ExecutionContext) {
const allowedRoles = this.reflector.get(ROLE_KEY, context.getHandler());
if (!allowedRoles) {
return true;
}
const executionContext = GqlExecutionContext.create(context);
const { req } = executionContext.getContext();
const args = executionContext.getArgs();
const info = executionContext.getInfo();
const user: User = req.user;
if (!user) {
throw new InternalServerErrorException(
'Could not find user under execution context. Please make sure AuthenticationGuard are defined first.',
);
}
user.roles = await this.userRoleService.find({ where: { user: { id: user.id } } });
if (user.roles) {
const result = await Promise.all(
allowedRoles.map(role => {
async canActivate(context: ExecutionContext): Promise {
const gqlCtx = GqlExecutionContext.create(context);
const user = gqlCtx.getContext().user;
if (user && user.username === 'sadmin') return true;
let userPerm: string[] = [];
if (user && user.roles.length) {
user.roles.forEach(role => {
user.personalPermissions.filter(pp => pp.status === 'decrease').forEach(pp => {
role.permissions.splice(role.permissions.indexOf(role.permissions.find(p => p.id === pp.permission.id)), 1);
});
if (role.permissions && role.permissions.length) {
role.permissions.forEach(permission => {
userPerm.push(permission.identify);
});
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
const request = ctx.getContext().req;
return request;
}
const req = context.switchToHttp().getRequest();
if (req) {
const method = req.method;
const url = req.url;
return next
.handle()
.pipe(
tap(() =>
Logger.log(
`${method} ${url} ${Date.now() - now}ms`,
context.getClass().name,
),
),
);
} else {
const ctx: any = GqlExecutionContext.create(context);
const resolverName = ctx.constructorRef.name;
const info = ctx.getInfo();
Logger.log(
`${info.parentType} "${info.fieldName}" ${Date.now() - now}ms`,
resolverName,
);
return next
.handle()
.pipe(
tap(() =>
Logger.log(
`${info.parentType} "${info.fieldName}" ${Date.now() - now}ms`,
resolverName,
),
),
);
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
}
const now = Date.now();
const req = context.switchToHttp().getRequest();
if (req) {
const method = req.method;
const url = req.url;
return call$.pipe(
tap(() =>
Logger.log(
`${method} ${url} ${Date.now() - now}ms`,
context.getClass().name,
),
),
);
} else {
const ctx: any = GqlExecutionContext.create(context);
const resolverName = ctx.constructorRef.name;
const info = ctx.getInfo();
return call$.pipe(
tap(() =>
Logger.log(
`${info.parentType} "${info.fieldName}" ${Date.now() - now}ms`,
resolverName,
),
),
);
}
}
}
intercept(context: ExecutionContext, next: CallHandler): Observable {
if (context.getArgs().length === 4) {
const ctx = GqlExecutionContext.create(context);
const info = ctx.getInfo();
const operation = info.operation.operation.toUpperCase();
const before = Date.now();
const rawArgs = JSON.stringify(ctx.getArgs());
return next
.handle()
.pipe(
tap(() =>
this.logger.log(
`${COLOR_RESET}${operation} ${info.fieldName} ${this.colorizeDiffTime(before)} [Args: ${rawArgs}]`,
),
),
);
}
return next.handle();
}