diff --git a/src/common-libs/auth/permission-decorator.ts b/src/common-libs/auth/permission-decorator.ts new file mode 100644 index 00000000..6b27ecb7 --- /dev/null +++ b/src/common-libs/auth/permission-decorator.ts @@ -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 +) => Promise>; + +// eslint-disable-next-line @typescript-eslint/naming-convention +export function Permission( + requiredPermissions: RequiredPermissions +): MethodDecorator { + return createMethodDecorator( + async (resolverData: ResolverData, 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(); + } + ); +}