|
| 1 | +import { copyMethodMetadata } from 'nestjs-cls'; |
| 2 | +import { AuthHost } from './auth-host'; |
| 3 | +import { RequirePermissionOptions } from './auth.interfaces'; |
| 4 | + |
| 5 | +export function RequirePermission<TAuth = any>( |
| 6 | + predicate: (auth: TAuth) => boolean, |
| 7 | + options?: RequirePermissionOptions, |
| 8 | +): MethodDecorator; |
| 9 | + |
| 10 | +export function RequirePermission<TAuth = any>( |
| 11 | + authName: string, |
| 12 | + predicate: (auth: TAuth) => boolean, |
| 13 | + options?: RequirePermissionOptions, |
| 14 | +): MethodDecorator; |
| 15 | + |
| 16 | +export function RequirePermission<TAuth = any>( |
| 17 | + firstParam: any, |
| 18 | + secondParam?: any, |
| 19 | + thirdParam?: any, |
| 20 | +): MethodDecorator { |
| 21 | + let authName: string | undefined; |
| 22 | + let predicate: (auth: TAuth) => boolean; |
| 23 | + let options: RequirePermissionOptions | undefined; |
| 24 | + |
| 25 | + if (typeof firstParam === 'string') { |
| 26 | + authName = firstParam; |
| 27 | + predicate = secondParam as (auth: TAuth) => boolean; |
| 28 | + options = thirdParam; |
| 29 | + } else { |
| 30 | + authName = undefined; |
| 31 | + predicate = firstParam as (auth: TAuth) => boolean; |
| 32 | + options = secondParam; |
| 33 | + } |
| 34 | + options ??= { |
| 35 | + exceptionMessage: 'Permission denied', |
| 36 | + }; |
| 37 | + |
| 38 | + return (( |
| 39 | + _target: any, |
| 40 | + propertyKey: string | symbol, |
| 41 | + descriptor: TypedPropertyDescriptor<(...args: any) => any>, |
| 42 | + ) => { |
| 43 | + const original = descriptor.value; |
| 44 | + if (typeof original !== 'function') { |
| 45 | + throw new Error( |
| 46 | + `The @RequirePermission decorator can be only used on functions, but ${propertyKey.toString()} is not a function.`, |
| 47 | + ); |
| 48 | + } |
| 49 | + descriptor.value = new Proxy(original, { |
| 50 | + apply: function (_, outerThis, args: any[]) { |
| 51 | + const authHost = AuthHost.getInstance(authName); |
| 52 | + |
| 53 | + authHost.requirePermission(predicate, options); |
| 54 | + |
| 55 | + return original.call(outerThis, ...args); |
| 56 | + }, |
| 57 | + }); |
| 58 | + copyMethodMetadata(original, descriptor.value); |
| 59 | + }) as MethodDecorator; |
| 60 | +} |
0 commit comments