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