-
-
Notifications
You must be signed in to change notification settings - Fork 281
/
useAuth.ts
56 lines (53 loc) · 1.4 KB
/
useAuth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {
decorateMethodsOf,
DecoratorParameters,
decoratorTypeOf,
DecoratorTypes,
Store,
StoreFn,
Type,
UnsupportedDecoratorType,
useDecorators
} from "@tsed/core";
import {AuthOptions} from "./authOptions.js";
import {UseBefore} from "./useBefore.js";
/**
* Use custom authentication strategy on your endpoint.
*
* ```typescript
* @Controller('/mypath')
* @UseAuth(MyAuthStrategy)
* class MyCtrl {
*
* @Get('/')
* @UseAuth(MyAuthStrategy, {role: 'admin'})
* public getResource(){}
* }
* ```
*
* @param guardAuth {Type<any>} A middleware which implement a custom auth strategy
* @param options {Object} Object passed to the customer auth strategy
* @returns {Function}
* @decorator
* @operation
*/
export function UseAuth(guardAuth: Type<any>, options: Record<string, unknown> = {}): Function {
return <T>(...args: DecoratorParameters): TypedPropertyDescriptor<T> | void => {
switch (decoratorTypeOf(args)) {
case DecoratorTypes.METHOD:
return useDecorators(
StoreFn((store: Store) => {
if (!store.has(guardAuth)) {
return UseBefore(guardAuth);
}
}),
AuthOptions(guardAuth, options)
)(...args);
case DecoratorTypes.CLASS:
decorateMethodsOf(args[0], UseAuth(guardAuth, options));
break;
default:
throw new UnsupportedDecoratorType(UseAuth, args);
}
};
}