/
authOptions.ts
65 lines (58 loc) · 1.62 KB
/
authOptions.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
57
58
59
60
61
62
63
64
65
import {decorateMethodsOf, DecoratorParameters, getDecoratorType, Store, StoreFn, Type, UnsupportedDecoratorType} from "@tsed/core";
export interface IAuthOptions {
responses?: {
[statusCode: string]: {
description: string;
};
};
security?: {
[securityName: string]: string[];
}[];
[key: string]: any;
}
/**
* Change authentication options.
*
* ```typescript
* @Controller('/mypath')
* @UseAuth(MyAuthStrategy, {role: ''})
* class MyCtrl {
*
* @Get('/')
* @AuthOptions(MyAuthStrategy, {role: 'admin'})
* public getResource(){}
* }
* ```
*
* @param guardAuth
* @param options {Object} Object passed to the customer auth strategy
* @returns {Function}
* @decorator
* @decorator
* @operation
*/
export function AuthOptions(guardAuth: Type<any>, options: IAuthOptions = {}): Function {
return <T>(...args: DecoratorParameters): TypedPropertyDescriptor<T> | void => {
switch (getDecoratorType(args, true)) {
case "method":
return StoreFn((store: Store) => {
if (options.responses) {
const {responses} = options;
store.merge("responses", responses, true);
delete options.responses;
}
if (options.security) {
const {security} = options;
store.merge("operation", {security}, true);
delete options.security;
}
store.merge(guardAuth, options, true);
})(...args);
case "class":
decorateMethodsOf(args[0], AuthOptions(guardAuth, options));
break;
default:
throw new UnsupportedDecoratorType(AuthOptions, args);
}
};
}