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 Aug 23, 2021
1 parent aeed03f commit a32d302
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/Context';
import { ForbiddenError } from '@unocha/hpc-api-core/src/util/error';
import { createMethodDecorator, ResolverData } from 'type-graphql';

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

// 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(context, permissions))) {
throw new ForbiddenError('No permission to perform this action');
}

return next();
}
);
}

0 comments on commit a32d302

Please sign in to comment.