Skip to content

Commit

Permalink
πŸ›‚ Introduce @Permission decorator
Browse files Browse the repository at this point in the history
This decorator can accept permission conditions required
to access the resource. For example:

`@Permission({ type: 'plan', permission: 'editPlanData' })`

Non-global permissions also take id argument of the query
into account to check access permissions.
  • Loading branch information
Pl217 committed Nov 4, 2021
1 parent 98f47f2 commit ed74abf
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/common-libs/auth/permission-decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { actionIsPermitted } from '@unocha/hpc-api-core/src/auth';
import { RequiredPermissionsCondition } from '@unocha/hpc-api-core/src/auth/permissions';
import { Context } from '@unocha/hpc-api-core/src/lib/context';
import { ForbiddenError } from '@unocha/hpc-api-core/src/util/error';
import { createMethodDecorator, ResolverData } from 'type-graphql';

type RequiredPermissions = (
resolverData: ResolverData<Context>
) => Promise<RequiredPermissionsCondition<never>>;

// eslint-disable-next-line @typescript-eslint/naming-convention
export function Permission(
requiredPermissions: RequiredPermissions
): MethodDecorator {
return createMethodDecorator(
async (resolverData: ResolverData<Context>, next) => {
const permissions = await requiredPermissions(resolverData);
const { context } = resolverData;

if (!(await actionIsPermitted(permissions, context))) {
throw new ForbiddenError('No permission to perform this action');
}

return next();
}
);
}

0 comments on commit ed74abf

Please sign in to comment.