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 | import {DynamicModule, Global, LoggerService, Module} from '@nestjs/common';
|
26 | import * as _ from 'lodash';
|
27 | import {APP_GUARD} from '@nestjs/core';
|
28 | import {AuthJwtGuard} from './guard/auth-jwt.guard';
|
29 | import {AuthBasicGuard} from './guard/auth-basic.guard';
|
30 | import {AuthModuleAsyncOptions, AuthModuleOptions} from './interfaces';
|
31 | import {AuthController} from './controller/auth.controller';
|
32 | import {RoleAclGuard} from './guard/role-acl.guard';
|
33 | import {AUTH_MODULE_OPTIONS, AuthActionType} from './constants';
|
34 | import {Log} from '@nest-mods/log';
|
35 | import {UserDetailService} from './service/user-detail.service';
|
36 | import {JwtStrategy} from './strategy/jwt.strategy';
|
37 | import {BasicStrategy} from './strategy/basic.strategy';
|
38 | import {AuthService} from './service/auth.service';
|
39 |
|
40 | const defaultAuthConfig: Partial<AuthModuleOptions> = {
|
41 | useJwt: true,
|
42 | useBasic: true,
|
43 | useACL: true,
|
44 | basicAuth: {
|
45 | defaultAuthAction: AuthActionType.TRY,
|
46 | },
|
47 | jwtAuth: {
|
48 | defaultAuthAction: AuthActionType.TRY,
|
49 | queryTokenKey: 'token',
|
50 | secret: 'DEFAULT_PASSWORD',
|
51 | signOptions: {
|
52 | expiresIn: '7d',
|
53 | audience: 'demo',
|
54 | issuer: 'demo',
|
55 | },
|
56 | },
|
57 | };
|
58 |
|
59 | @Global()
|
60 | @Module({
|
61 | providers: [AuthService, JwtStrategy, BasicStrategy, {
|
62 | provide: APP_GUARD,
|
63 | useClass: AuthBasicGuard,
|
64 | }, {
|
65 | provide: APP_GUARD,
|
66 | useClass: AuthJwtGuard,
|
67 | }, {
|
68 | provide: APP_GUARD,
|
69 | useClass: RoleAclGuard,
|
70 | }],
|
71 | exports: [AuthService],
|
72 | })
|
73 | export class AuthModule {
|
74 | @Log() private static logger: LoggerService;
|
75 |
|
76 | static forRootAsync(options: AuthModuleAsyncOptions): DynamicModule {
|
77 | return {
|
78 | module: AuthModule,
|
79 | imports: options.imports,
|
80 | providers: [{
|
81 | provide: AUTH_MODULE_OPTIONS,
|
82 | inject: options.inject,
|
83 | useFactory: async (...args) => {
|
84 | const opts = await options.useFactory(...args);
|
85 | return _.defaultsDeep(opts, defaultAuthConfig);
|
86 | },
|
87 | }, {
|
88 | provide: UserDetailService,
|
89 | useClass: options.UserDetailService,
|
90 | }],
|
91 | controllers: options.enabledController ? [AuthController] : [],
|
92 | };
|
93 | }
|
94 | }
|