-
-
Notifications
You must be signed in to change notification settings - Fork 281
/
useAuth.ts
55 lines (52 loc) · 1.37 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
import {
applyDecorators,
decorateMethodsOf,
DecoratorParameters,
getDecoratorType,
Store,
StoreFn,
Type,
UnsupportedDecoratorType
} from "@tsed/core";
import {AuthOptions, IAuthOptions} from "./authOptions";
import {UseBefore} from "./useBefore";
/**
* 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
* @endpoint
*/
export function UseAuth(guardAuth: Type<any>, options: IAuthOptions = {}): Function {
return <T>(...args: DecoratorParameters): TypedPropertyDescriptor<T> | void => {
switch (getDecoratorType(args, true)) {
case "method":
return applyDecorators(
StoreFn((store: Store) => {
if (!store.has(guardAuth)) {
return UseBefore(guardAuth);
}
}),
AuthOptions(guardAuth, options)
)(...args);
case "class":
decorateMethodsOf(args[0], UseAuth(guardAuth, options));
break;
default:
throw new UnsupportedDecoratorType(UseAuth, args);
}
};
}