How to use the apollo-server-express.ForbiddenError function in apollo-server-express

To help you get started, we’ve selected a few apollo-server-express examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chnirt / nestjs-graphql-best-practice / src / config / graphql / schemaDirectives / permission.ts View on Github external
$map: {
									input: '$permissions.code',
									as: 'code',
									in: '$$code'
								}
							},
							_id: 0
						}
					}
				])
				.toArray()

			console.log(userRoles[0].permissions)

			if (userRoles[0].permissions.indexOf(permission) === -1) {
				throw new ForbiddenError('You are not authorized for this resource.')
			}

			// console.log('userRole', userRole)

			return resolve.apply(this, args)
		}
	}
github chnirt / nestjs-graphql-best-practice / src / config / graphql / schemaDirectives / permission.ts View on Github external
throw new AuthenticationError(
					'Authentication token is invalid, please try again.'
				)
			}

			// console.log(currentUser._id, permission)

			const role = await getMongoRepository(Role).find({
				where: {
					userId: currentUser._id,
					'permissions.code': permission
				}
			})

			if (!role) {
				throw new ForbiddenError('You are not authorized for this resource.')
			}

			// console.log('Role', role)

			return resolve.apply(this, args)
		}
	}
github chnirt / nestjs-graphql-best-practice / src / config / graphql / schemaDirectives / path.ts View on Github external
throw new AuthenticationError(
					'Authentication token is invalid, please try again.'
				)
			}

			// console.log(currentUser._id, path)

			const role = await getMongoRepository(Role).find({
				where: {
					userId: currentUser._id,
					path: { $regex: `.*${path}|${path.toLowerCase()}.*` },
				},
			})

			if (!role) {
				throw new ForbiddenError('You are not authorized for this resource.')
			}

			// console.log('Role', role)

			return resolve.apply(this, args)
		}
	}
github timothyarmes / ta-meteor-apollo-starter-kit / app / api / users / server / utils.js View on Github external
utilities.checkLoggedInAndNotVerified = (user) => {
  // User should be logged in at this stage
  if (!user) {
    throw new AuthenticationError('User is not logged in!');
  }

  if (user.emails[0].verified === true) {
    throw new ForbiddenError('Email already verified!');
  }
};
github aerogear-attic / data-sync-server / server / security / services / keycloak / schemaDirectives / hasRole.js View on Github external
field.resolve = async function (root, args, context, info) {
      // must check for a validation error at runtime
      // to ensure an appropriate message is sent back
      log.info(`checking user is authorized to access ${field.name} on parent ${info.parentType.name}. Must have one of [${roles}]`)

      if (error) {
        log.error(`Invalid hasRole directive on field ${field.name} on parent ${info.parentType.name}`, error)
        throw newInternalServerError(context)
      }

      if (!context.auth || !context.auth.isAuthenticated()) {
        const AuthorizationErrorMessage = `Unable to find authentication. Authorization is required for field ${field.name} on parent ${info.parentType.name}. Must have one of the following roles: [${roles}]`
        log.error({ error: AuthorizationErrorMessage })
        throw new ForbiddenError(AuthorizationErrorMessage)
      }

      let foundRole = null // this will be the role the user was successfully authorized on

      foundRole = roles.find((role) => {
        return context.auth.hasRole(role)
      })

      if (!foundRole) {
        const AuthorizationErrorMessage = `user is not authorized for field ${field.name} on parent ${info.parentType.name}. Must have one of the following roles: [${roles}]`
        log.error({ error: AuthorizationErrorMessage, details: context.auth.getTokenContent() })
        throw new ForbiddenError(AuthorizationErrorMessage)
      }

      log.info(`user successfully authorized with role: ${foundRole}`)
github timothyarmes / ta-meteor-apollo-starter-kit / app / api / users / server / utils.js View on Github external
utilities.checkLoggedInAndVerified = (user) => {
  // User should be logged in at this stage
  if (!user) {
    throw new AuthenticationError('User is not logged in!');
  }

  // Make sure email is verified (in case of password service)
  // TODO: use current loggedIn service instead
  const isPasswordService = Object.keys(user.services).indexOf('password') !== -1;
  const isEmailVerified = isPasswordService && user.emails[0].verified === true;
  if (isPasswordService && !isEmailVerified) {
    throw new ForbiddenError('Email is not verified!');
  }
};
github mimecuvalo / helloworld / server / data / graphql / resolvers / authorization.js View on Github external
export const isAdmin = (parent, args, { currentUser }) =>
  authorization.isAuthenticated(currentUser)
    ? authorization.isAdmin(currentUser)
      ? skip
      : new ForbiddenError('I call shenanigans.')
    : new AuthenticationError('Not logged in.');
github origen-chat / api / projects / api / src / server / graphql / Query / channel / resolver.ts View on Github external
> = async (root, args, context) => {
  const viewer = getViewerOrThrowIfUnauthenticated(context);

  const { id: channelId } = args;

  const channel = await context.loaders.channelById.load(channelId);

  if (!channel) {
    throw new NotFoundError({ entity: NotFoundableEntity.Channel });
  }

  if (!channels.canSeeChannel(viewer, channel)) {
    throw new ForbiddenError('forbidden');
  }

  return channel;
};
github birkir / prime / packages / prime-core / src / routes / internal / index.ts View on Github external
const ensureAllowed = async (resources, permissions) => {
        const isAllowed = await acl.isAllowed(user.id, resources, permissions);
        if (!isAllowed) {
          throw new ForbiddenError('Insufficient permissions');
        }
      };
github origen-chat / api / projects / api / src / server / graphql / Workspace / channel / resolver.ts View on Github external
const { id: channelGlobalId } = args;

  const channelId = Number.parseInt(channelGlobalId, 10);

  if (!isViewerAuthenticated(context)) {
    throw new AuthenticationError('unauthenticated');
  }

  const channel = await channels.getChannelById(channelId);

  if (!channel) {
    throw new NotFoundError('channel not found');
  }

  if (!channels.canSeeChannel(context.viewer, channel)) {
    throw new ForbiddenError('forbidden');
  }

  return channel;
};