@nestjs-kitchen/authz 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/authz.provider.d.ts +1 -3
  2. package/dist/authz.provider.js +29 -48
  3. package/dist/constants.d.ts +6 -8
  4. package/dist/constants.js +13 -46
  5. package/dist/errors.d.ts +3 -5
  6. package/dist/errors.js +35 -60
  7. package/dist/index.d.ts +5 -21
  8. package/dist/index.js +16 -45
  9. package/dist/jwt/extract-jwt.d.ts +4 -7
  10. package/dist/jwt/extract-jwt.js +138 -158
  11. package/dist/jwt/index.d.ts +2 -16
  12. package/dist/jwt/index.js +7 -30
  13. package/dist/jwt/jwt-authz-als.middleware.d.ts +6 -16
  14. package/dist/jwt/jwt-authz-als.middleware.js +44 -81
  15. package/dist/jwt/jwt-authz.guard.d.ts +8 -21
  16. package/dist/jwt/jwt-authz.guard.js +130 -175
  17. package/dist/jwt/jwt-authz.interface.d.ts +16 -25
  18. package/dist/jwt/jwt-authz.interface.js +69 -92
  19. package/dist/jwt/jwt-authz.module.d.ts +19 -31
  20. package/dist/jwt/jwt-authz.module.js +250 -299
  21. package/dist/jwt/jwt-authz.service.d.ts +6 -17
  22. package/dist/jwt/jwt-authz.service.js +116 -162
  23. package/dist/jwt/jwt-authz.strategy.d.ts +5 -17
  24. package/dist/jwt/jwt-authz.strategy.js +132 -192
  25. package/dist/session/index.d.ts +1 -12
  26. package/dist/session/index.js +5 -27
  27. package/dist/session/session-authz-als.middleware.d.ts +5 -12
  28. package/dist/session/session-authz-als.middleware.js +98 -130
  29. package/dist/session/session-authz.guard.d.ts +6 -15
  30. package/dist/session/session-authz.guard.js +98 -135
  31. package/dist/session/session-authz.interface.d.ts +5 -12
  32. package/dist/session/session-authz.interface.js +19 -42
  33. package/dist/session/session-authz.module.d.ts +18 -26
  34. package/dist/session/session-authz.module.js +241 -290
  35. package/dist/session/session-authz.service.d.ts +5 -13
  36. package/dist/session/session-authz.service.js +69 -105
  37. package/dist/session/session-authz.strategy.d.ts +4 -12
  38. package/dist/session/session-authz.strategy.js +68 -105
  39. package/dist/user.decorator.d.ts +3 -6
  40. package/dist/user.decorator.js +26 -35
  41. package/dist/utils/cookie-parsers.d.ts +3 -6
  42. package/dist/utils/cookie-parsers.js +66 -74
  43. package/dist/utils/create-authz-decorator-factory.d.ts +3 -9
  44. package/dist/utils/create-authz-decorator-factory.js +32 -54
  45. package/dist/utils/create-set-cookie-fn.d.ts +3 -9
  46. package/dist/utils/create-set-cookie-fn.js +23 -45
  47. package/dist/utils/generics.d.ts +4 -6
  48. package/dist/utils/generics.js +37 -63
  49. package/dist/utils/get-allow-anonymous.d.ts +2 -9
  50. package/dist/utils/get-allow-anonymous.js +7 -29
  51. package/dist/utils/get-als-store.d.ts +2 -5
  52. package/dist/utils/get-als-store.js +11 -34
  53. package/dist/utils/get-context-authz-meta-params-list.d.ts +2 -9
  54. package/dist/utils/get-context-authz-meta-params-list.js +16 -35
  55. package/dist/utils/get-passport-property.d.ts +1 -3
  56. package/dist/utils/get-passport-property.js +8 -30
  57. package/dist/utils/index.d.ts +11 -16
  58. package/dist/utils/index.js +26 -40
  59. package/dist/utils/merge-dynamic-module-configs.d.ts +2 -5
  60. package/dist/utils/merge-dynamic-module-configs.js +14 -49
  61. package/dist/utils/msgpackrs.d.ts +2 -4
  62. package/dist/utils/msgpackrs.js +11 -35
  63. package/dist/utils/types.d.ts +23 -26
  64. package/dist/utils/types.js +2 -15
  65. package/package.json +7 -7
@@ -1,21 +1,14 @@
1
- import * as _nestjs_core from '@nestjs/core';
2
- import { SessionAuthzOptions, SessionOptions, SessionAuthzModuleOptions } from './session-authz.interface.js';
3
- import { AuthzProviderClass } from '../authz.provider.js';
4
- import { AbstractConstructor, RoutesOptions, AuthzModuleBaseOptions, AuthzModuleRoutesOptions, AuthzDecoParams, MethodParameters, ApplyDecorators, CookieOptionsWithSecret, DeepReadonly } from '../utils/types.js';
5
1
  import { AsyncLocalStorage } from 'node:async_hooks';
6
- import * as _nestjs_common from '@nestjs/common';
7
- import { MiddlewareConsumer, Type, DynamicModule } from '@nestjs/common';
8
- import { AuthzError } from '../errors.js';
9
- import { SessionAlsType } from './session-authz-als.middleware.js';
10
- import 'express-session';
11
- import '@nestjs/common/interfaces';
12
- import 'express';
13
-
14
- declare const ASYNC_OPTIONS_TYPE: _nestjs_common.ConfigurableModuleAsyncOptions<SessionAuthzModuleOptions, "createSessionAuthzModuleOptions"> & Partial<{
2
+ import { DynamicModule, MiddlewareConsumer, type Type } from '@nestjs/common';
3
+ import { AuthzProviderClass } from '../authz.provider';
4
+ import { AuthzError } from '../errors';
5
+ import { type AbstractConstructor, type AuthzModuleRoutesOptions, type RoutesOptions } from '../utils';
6
+ import { type SessionAlsType } from './session-authz-als.middleware';
7
+ import { type SessionAuthzModuleOptions, type SessionAuthzOptions } from './session-authz.interface';
8
+ declare const ASYNC_OPTIONS_TYPE: import("@nestjs/common").ConfigurableModuleAsyncOptions<SessionAuthzModuleOptions, "createSessionAuthzModuleOptions"> & Partial<{
15
9
  authzProvider?: Type<AuthzProviderClass<unknown, unknown>>;
16
- } & AuthzModuleRoutesOptions>;
17
- declare const OPTIONS_TYPE: Partial<AuthzModuleBaseOptions> & {
18
- session: SessionOptions & {
10
+ } & AuthzModuleRoutesOptions>, OPTIONS_TYPE: Partial<import("../utils").AuthzModuleBaseOptions> & {
11
+ session: import("./session-authz.interface").SessionOptions & {
19
12
  keepSessionInfo?: boolean;
20
13
  };
21
14
  } & Partial<{
@@ -28,7 +21,7 @@ declare const OPTIONS_TYPE: Partial<AuthzModuleBaseOptions> & {
28
21
  * @param authzProvider - The implementation class of `AuthzProviderClass`
29
22
  * @returns \{AuthzModule, AuthzGuard, AuthzService}
30
23
  */
31
- declare const cereateSessionAuthzModule: <P, U, T extends AuthzProviderClass<P, U>>(authzProvider: AbstractConstructor<T, P, U>) => {
24
+ export declare const cereateSessionAuthzModule: <P, U, T extends AuthzProviderClass<P, U>>(authzProvider: AbstractConstructor<T, P, U>) => {
32
25
  /**
33
26
  * A dynamic module used to configure session based authentication and authorization features for the application.
34
27
  *
@@ -97,7 +90,7 @@ declare const cereateSessionAuthzModule: <P, U, T extends AuthzProviderClass<P,
97
90
  * ```
98
91
  */
99
92
  AuthzGuard: Type<Omit<{
100
- readonly reflector: _nestjs_core.Reflector;
93
+ readonly reflector: import("@nestjs/core").Reflector;
101
94
  readonly authzProvider: AuthzProviderClass<unknown, unknown>;
102
95
  readonly sessionAuthzOptions: SessionAuthzOptions;
103
96
  readonly als: AsyncLocalStorage<SessionAlsType<unknown, unknown>>;
@@ -106,11 +99,11 @@ declare const cereateSessionAuthzModule: <P, U, T extends AuthzProviderClass<P,
106
99
  session: boolean;
107
100
  };
108
101
  handleRequest<T_1>(_err: unknown, user: T_1, info?: AuthzError): T_1;
109
- canActivate(context: _nestjs_common.ExecutionContext): Promise<boolean>;
102
+ canActivate(context: import("@nestjs/common").ExecutionContext): Promise<boolean>;
110
103
  logIn<TRequest extends {
111
104
  logIn: Function;
112
105
  } = any>(request: TRequest): Promise<void>;
113
- getRequest(context: _nestjs_common.ExecutionContext): any;
106
+ getRequest(context: import("@nestjs/common").ExecutionContext): any;
114
107
  }, "als" | "reflector" | "authzProvider" | "sessionAuthzOptions">> & {
115
108
  /**
116
109
  * Verifies the user's authorization for specific meta data.
@@ -129,7 +122,7 @@ declare const cereateSessionAuthzModule: <P, U, T extends AuthzProviderClass<P,
129
122
  * }
130
123
  * ```
131
124
  */
132
- Verify: (...args: AuthzDecoParams<MethodParameters<T, "authorize">[1]>) => ApplyDecorators;
125
+ Verify: (...args: import("../utils").AuthzDecoParams<import("../utils").MethodParameters<T, "authorize">[1]>) => import("../utils").ApplyDecorators;
133
126
  /**
134
127
  * Skips authentication & authorization checks for specific routes.
135
128
  *
@@ -164,7 +157,7 @@ declare const cereateSessionAuthzModule: <P, U, T extends AuthzProviderClass<P,
164
157
  * }
165
158
  * ```
166
159
  */
167
- Apply: (...rest: Parameters<(...args: AuthzDecoParams<MethodParameters<T, "authorize">[1]>) => ApplyDecorators>) => <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
160
+ Apply: (...rest: Parameters<(...args: import("../utils").AuthzDecoParams<import("../utils").MethodParameters<T, "authorize">[1]>) => import("../utils").ApplyDecorators>) => <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
168
161
  };
169
162
  /**
170
163
  * A custom servcie to provide methods to handle authentication and authorization.
@@ -174,9 +167,8 @@ declare const cereateSessionAuthzModule: <P, U, T extends AuthzProviderClass<P,
174
167
  readonly als: AsyncLocalStorage<SessionAlsType<P, U>>;
175
168
  logIn(user: U): Promise<void>;
176
169
  logOut(): Promise<void>;
177
- setCookie(name: string, value: string, options?: CookieOptionsWithSecret | undefined): void;
178
- getUser(): DeepReadonly<U> | undefined;
170
+ setCookie(name: string, value: string, options?: import("../utils").CookieOptionsWithSecret | undefined): void;
171
+ getUser(): import("../utils").DeepReadonly<U> | undefined;
179
172
  }, "als" | "authzProvider">>;
180
173
  };
181
-
182
- export { cereateSessionAuthzModule };
174
+ export {};
@@ -1,299 +1,250 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
12
7
  };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
20
10
  };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
31
- var session_authz_module_exports = {};
32
- __export(session_authz_module_exports, {
33
- cereateSessionAuthzModule: () => cereateSessionAuthzModule
34
- });
35
- module.exports = __toCommonJS(session_authz_module_exports);
36
- var import_node_async_hooks = require("node:async_hooks");
37
- var import_common = require("@nestjs/common");
38
- var import_express_session = __toESM(require("express-session"));
39
- var import_uid = require("uid");
40
- var import_constants = require("../constants");
41
- var import_errors = require("../errors");
42
- var import_utils = require("../utils");
43
- var import_session_authz_als = require("./session-authz-als.middleware");
44
- var import_session_authz = require("./session-authz.guard");
45
- var import_session_authz2 = require("./session-authz.interface");
46
- var import_session_authz3 = require("./session-authz.service");
47
- var import_session_authz4 = require("./session-authz.strategy");
48
- function _ts_decorate(decorators, target, key, desc) {
49
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
50
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
51
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
52
- return c > 3 && r && Object.defineProperty(target, key, r), r;
53
- }
54
- __name(_ts_decorate, "_ts_decorate");
55
- function _ts_metadata(k, v) {
56
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
57
- }
58
- __name(_ts_metadata, "_ts_metadata");
59
- function _ts_param(paramIndex, decorator) {
60
- return function(target, key) {
61
- decorator(target, key, paramIndex);
62
- };
63
- }
64
- __name(_ts_param, "_ts_param");
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.cereateSessionAuthzModule = void 0;
19
+ const node_async_hooks_1 = require("node:async_hooks");
20
+ const common_1 = require("@nestjs/common");
21
+ const express_session_1 = __importDefault(require("express-session"));
22
+ const uid_1 = require("uid");
23
+ const constants_1 = require("../constants");
24
+ const errors_1 = require("../errors");
25
+ const utils_1 = require("../utils");
26
+ const session_authz_als_middleware_1 = require("./session-authz-als.middleware");
27
+ const session_authz_guard_1 = require("./session-authz.guard");
28
+ const session_authz_interface_1 = require("./session-authz.interface");
29
+ const session_authz_service_1 = require("./session-authz.service");
30
+ const session_authz_strategy_1 = require("./session-authz.strategy");
65
31
  const store = {
66
- globalInited: 0
32
+ globalInited: 0
67
33
  };
68
- const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, ASYNC_OPTIONS_TYPE, OPTIONS_TYPE } = new import_common.ConfigurableModuleBuilder({
69
- moduleName: "SessionAuthModule"
70
- }).setFactoryMethodName("createSessionAuthzModuleOptions").setExtras({
71
- authzProvider: void 0,
72
- global: false
34
+ const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, ASYNC_OPTIONS_TYPE, OPTIONS_TYPE } = new common_1.ConfigurableModuleBuilder({
35
+ moduleName: 'SessionAuthModule'
36
+ })
37
+ .setFactoryMethodName('createSessionAuthzModuleOptions')
38
+ .setExtras({
39
+ authzProvider: undefined,
40
+ global: false
73
41
  }, (definition, extras) => {
74
- const { authzProvider, global } = extras;
75
- if (!authzProvider) {
76
- throw new import_errors.AuthzError(`InternalError: Missing parameter 'authzProvider' in configuration.`);
77
- }
78
- const routes = (0, import_utils.normalizedArray)(extras.routes) ?? [];
79
- const excludes = (0, import_utils.normalizedArray)(extras.excludes) ?? [];
80
- if (!global && !routes.length) {
81
- throw new import_errors.AuthzError(`InternalError: Missing parameter 'global' or 'routes' in configuration.`);
82
- }
83
- if (store.globalInited) {
84
- throw new import_errors.AuthzError(`InternalError: Cannot initialize mutiple global modules. Only one global module is allowed.`);
85
- }
86
- if (global) {
87
- store.globalInited += 1;
88
- }
89
- return (0, import_utils.mergeDynamicModuleConfigs)(definition, {
90
- global,
91
- providers: [
92
- {
93
- provide: import_constants.ROUTES_OPTIONS,
94
- useValue: {
95
- global,
96
- excludes,
97
- routes
98
- }
99
- }
100
- ],
101
- exports: []
102
- });
103
- }).build();
104
- const cereateSessionAuthzModule = /* @__PURE__ */ __name((authzProvider) => {
105
- var _a;
106
- const id = `${import_constants.PREFIX}${(0, import_uid.uid)()}`;
107
- const SESSION_STRATEGY = `${id}_SESSION_STRATEGY`;
108
- const AUTHZ_PROVIDER = `${id}_AUTHZ_PROVIDER`;
109
- const ALS_PROVIDER = `${id}_ALS_PROVIDER`;
110
- const SESSION_AUTHZ_OPTIONS = `${id}_SESSION_AUTHZ_OPTIONS`;
111
- const SESSION_META_KEY = `${id}_SESSION_META_KEY`;
112
- const SessionAuthzStrategy = (0, import_session_authz4.createSessionAuthzStrategy)([
113
- SESSION_STRATEGY,
114
- AUTHZ_PROVIDER,
115
- ALS_PROVIDER
116
- ]);
117
- const SessionAuthzService = (0, import_session_authz3.createSessionAuthzService)([
118
- AUTHZ_PROVIDER,
119
- ALS_PROVIDER
120
- ]);
121
- const SessionAuthzAlsMiddleware = (0, import_session_authz_als.createSessionAuthzAlsMiddleware)([
122
- ALS_PROVIDER,
123
- SESSION_AUTHZ_OPTIONS
124
- ]);
125
- const als = new import_node_async_hooks.AsyncLocalStorage();
126
- let isStrategyInited = false;
127
- const SessionAuthzGuard = (0, import_session_authz.createSessionAuthzGuard)([
128
- SESSION_STRATEGY,
129
- AUTHZ_PROVIDER,
130
- SESSION_AUTHZ_OPTIONS,
131
- ALS_PROVIDER,
132
- SESSION_META_KEY
133
- ]);
134
- const Verify = (0, import_utils.createAuthzDecoratorFactory)(SESSION_META_KEY);
135
- const NoVerify = /* @__PURE__ */ __name(() => {
136
- return (0, import_common.SetMetadata)(SESSION_META_KEY, {
137
- options: {
138
- public: true,
139
- override: true
140
- }
141
- });
142
- }, "NoVerify");
143
- const Apply = /* @__PURE__ */ __name((...rest) => {
144
- return (0, import_common.applyDecorators)(SessionAuthzGuard.Verify(...rest), (0, import_common.UseGuards)(SessionAuthzGuard));
145
- }, "Apply");
146
- SessionAuthzGuard.Verify = Verify;
147
- SessionAuthzGuard.NoVerify = NoVerify;
148
- SessionAuthzGuard.Apply = Apply;
149
- const getCommonConfigs = /* @__PURE__ */ __name(() => {
150
- const configs = {
151
- providers: [
152
- {
153
- provide: AUTHZ_PROVIDER,
154
- useClass: authzProvider
155
- },
156
- {
157
- provide: ALS_PROVIDER,
158
- useValue: als
159
- },
160
- ...!isStrategyInited ? [
161
- SessionAuthzStrategy
162
- ] : [],
163
- SessionAuthzService
164
- ],
165
- exports: [
166
- AUTHZ_PROVIDER,
167
- ALS_PROVIDER,
168
- SESSION_AUTHZ_OPTIONS,
169
- SessionAuthzService
170
- ]
171
- };
172
- isStrategyInited = true;
173
- return configs;
174
- }, "getCommonConfigs");
175
- let SessionAuthzModule = (_a = class extends ConfigurableModuleClass {
176
- constructor(routesOpt, sessionAuthzOptions) {
177
- super();
178
- __publicField(this, "routesOpt");
179
- __publicField(this, "sessionAuthzOptions");
180
- this.routesOpt = routesOpt, this.sessionAuthzOptions = sessionAuthzOptions;
42
+ const { authzProvider, global } = extras;
43
+ if (!authzProvider) {
44
+ throw new errors_1.AuthzError(`InternalError: Missing parameter 'authzProvider' in configuration.`);
181
45
  }
182
- /**
183
- * Configures authz module.
184
- *
185
- * Note: DO NOT register the same routes in multiple session authz modules, or import the same session authz module in the same module multiple times, express-session middleware will not work properly.
186
- */
187
- static register(options) {
188
- const sessionAuthzOptions = (0, import_session_authz2.normalizedSessionAuthzModuleOptions)(options);
189
- return (0, import_utils.mergeDynamicModuleConfigs)(super.register({
190
- ...options,
191
- authzProvider
192
- }), getCommonConfigs(), {
193
- providers: [
194
- {
195
- provide: SESSION_AUTHZ_OPTIONS,
196
- useValue: sessionAuthzOptions
197
- }
198
- ]
199
- });
46
+ const routes = (0, utils_1.normalizedArray)(extras.routes) ?? [];
47
+ const excludes = (0, utils_1.normalizedArray)(extras.excludes) ?? [];
48
+ if (!global && !routes.length) {
49
+ throw new errors_1.AuthzError(`InternalError: Missing parameter 'global' or 'routes' in configuration.`);
200
50
  }
201
- /**
202
- * Configures authz module asynchronously.
203
- *
204
- * Note: DO NOT register the same routes in multiple session authz modules, express-session middleware will not work properly.
205
- */
206
- static registerAsync(options) {
207
- return (0, import_utils.mergeDynamicModuleConfigs)(super.registerAsync({
208
- ...options,
209
- authzProvider
210
- }), getCommonConfigs(), {
211
- providers: [
212
- {
213
- provide: SESSION_AUTHZ_OPTIONS,
214
- useFactory: /* @__PURE__ */ __name((moduleOptions) => {
215
- return (0, import_session_authz2.normalizedSessionAuthzModuleOptions)(moduleOptions);
216
- }, "useFactory"),
217
- inject: [
218
- MODULE_OPTIONS_TOKEN
219
- ]
220
- }
221
- ]
222
- });
51
+ if (store.globalInited) {
52
+ throw new errors_1.AuthzError(`InternalError: Cannot initialize mutiple global modules. Only one global module is allowed.`);
223
53
  }
224
- configure(consumer) {
225
- consumer.apply((0, import_express_session.default)(this.sessionAuthzOptions.session), SessionAuthzAlsMiddleware).exclude(...this.routesOpt.excludes).forRoutes(...this.routesOpt.global ? [
226
- "*"
227
- ] : this.routesOpt.routes);
54
+ if (global) {
55
+ store.globalInited += 1;
228
56
  }
229
- }, __name(_a, "SessionAuthzModule"), _a);
230
- SessionAuthzModule = _ts_decorate([
231
- (0, import_common.Module)({}),
232
- _ts_param(0, (0, import_common.Inject)(import_constants.ROUTES_OPTIONS)),
233
- _ts_param(1, (0, import_common.Inject)(SESSION_AUTHZ_OPTIONS)),
234
- _ts_metadata("design:type", Function),
235
- _ts_metadata("design:paramtypes", [
236
- typeof RoutesOptions === "undefined" ? Object : RoutesOptions,
237
- typeof SessionAuthzOptions === "undefined" ? Object : SessionAuthzOptions
238
- ])
239
- ], SessionAuthzModule);
240
- return {
241
- /**
242
- * A dynamic module used to configure session based authentication and authorization features for the application.
243
- *
244
- * This module can be configured using 2 static methods:
245
- *
246
- * - `register`
247
- * - `registerAsync`
248
- *
249
- * ### Usage
250
- *
251
- * ```typescript
252
- * ⁣@Module({
253
- * imports: [
254
- * // Import and configure session strategy
255
- * AuthzModule.register({
256
- * session: {
257
- * name: 'custom-session-id-name',
258
- * secret: '1234567890'
259
- * },
260
- * // Define routes that use AuthzGuard
261
- * routes: [BusinessController]
262
- * })
263
- * ],
264
- * controllers: [BusinessController]
265
- * })
266
- * export class BusinessModule {}
267
- * ```
268
- */
269
- AuthzModule: SessionAuthzModule,
270
- /**
271
- * A custom guard that applies authentication to controllers.
272
- *
273
- * This guard also provides 3 utility decorators to apply and modify authorization:
274
- *
275
- * - `@AuthzGuard.Verify`: Used to verify the user's authorization for specific meta data.
276
- * - `@AuthzGuard.NoVerify`: Used to `skip` authentication & authorization checks for specific routes.
277
- * - `@AuthzGuard.Apply`: A simplified version of `@UseGuards(AuthzGuard)` and `@AuthzGuard.Verify`, combining both for convenience.
278
- *
279
- * ### Usage:
280
- *
281
- * ```typescript
282
- * ⁣@UseGuards(AuthzGuard)
283
- * ⁣@Controller(/⁣/ ...)
284
- * export class BusinessController {
285
- * // ...
286
- * }
287
- * ```
288
- */
289
- AuthzGuard: SessionAuthzGuard,
290
- /**
291
- * A custom servcie to provide methods to handle authentication and authorization.
292
- */
293
- AuthzService: SessionAuthzService
294
- };
295
- }, "cereateSessionAuthzModule");
296
- // Annotate the CommonJS export names for ESM import in node:
297
- 0 && (module.exports = {
298
- cereateSessionAuthzModule
299
- });
57
+ return (0, utils_1.mergeDynamicModuleConfigs)(definition, {
58
+ global,
59
+ providers: [
60
+ {
61
+ provide: constants_1.ROUTES_OPTIONS,
62
+ useValue: {
63
+ global,
64
+ excludes,
65
+ routes
66
+ }
67
+ }
68
+ ],
69
+ exports: []
70
+ });
71
+ })
72
+ .build();
73
+ /**
74
+ * Creates a session module along with its associated guard and service,
75
+ * with types inferred from the provided implementation of `AuthzProviderClass`.
76
+ *
77
+ * @param authzProvider - The implementation class of `AuthzProviderClass`
78
+ * @returns \{AuthzModule, AuthzGuard, AuthzService}
79
+ */
80
+ const cereateSessionAuthzModule = (authzProvider) => {
81
+ const id = `${constants_1.PREFIX}${(0, uid_1.uid)()}`;
82
+ // strategy tokens
83
+ const SESSION_STRATEGY = `${id}_SESSION_STRATEGY`;
84
+ // provider tokens
85
+ const AUTHZ_PROVIDER = `${id}_AUTHZ_PROVIDER`;
86
+ const ALS_PROVIDER = `${id}_ALS_PROVIDER`;
87
+ const SESSION_AUTHZ_OPTIONS = `${id}_SESSION_AUTHZ_OPTIONS`;
88
+ // meta keys
89
+ const SESSION_META_KEY = `${id}_SESSION_META_KEY`;
90
+ // strategies
91
+ const SessionAuthzStrategy = (0, session_authz_strategy_1.createSessionAuthzStrategy)([SESSION_STRATEGY, AUTHZ_PROVIDER, ALS_PROVIDER]);
92
+ // providers
93
+ const SessionAuthzService = (0, session_authz_service_1.createSessionAuthzService)([AUTHZ_PROVIDER, ALS_PROVIDER]);
94
+ const SessionAuthzAlsMiddleware = (0, session_authz_als_middleware_1.createSessionAuthzAlsMiddleware)([ALS_PROVIDER, SESSION_AUTHZ_OPTIONS]);
95
+ const als = new node_async_hooks_1.AsyncLocalStorage();
96
+ // each strategy can be only registered once in passport.
97
+ // no need to provide multiple times as
98
+ // 1. they use the same ALS and authzProvider instance.
99
+ // 2. guard use strategy through passport via strategy name.
100
+ let isStrategyInited = false;
101
+ // guards
102
+ const SessionAuthzGuard = (0, session_authz_guard_1.createSessionAuthzGuard)([
103
+ SESSION_STRATEGY,
104
+ AUTHZ_PROVIDER,
105
+ SESSION_AUTHZ_OPTIONS,
106
+ ALS_PROVIDER,
107
+ SESSION_META_KEY
108
+ ]);
109
+ const Verify = (0, utils_1.createAuthzDecoratorFactory)(SESSION_META_KEY);
110
+ const NoVerify = () => {
111
+ return (0, common_1.SetMetadata)(SESSION_META_KEY, {
112
+ options: { public: true, override: true }
113
+ });
114
+ };
115
+ const Apply = (...rest) => {
116
+ return (0, common_1.applyDecorators)(SessionAuthzGuard.Verify(...rest), (0, common_1.UseGuards)(SessionAuthzGuard));
117
+ };
118
+ SessionAuthzGuard.Verify = Verify;
119
+ SessionAuthzGuard.NoVerify = NoVerify;
120
+ SessionAuthzGuard.Apply = Apply;
121
+ const getCommonConfigs = () => {
122
+ const configs = {
123
+ providers: [
124
+ {
125
+ provide: AUTHZ_PROVIDER,
126
+ useClass: authzProvider
127
+ },
128
+ {
129
+ provide: ALS_PROVIDER,
130
+ useValue: als
131
+ },
132
+ ...(!isStrategyInited ? [SessionAuthzStrategy] : []),
133
+ SessionAuthzService
134
+ ],
135
+ exports: [AUTHZ_PROVIDER, ALS_PROVIDER, SESSION_AUTHZ_OPTIONS, SessionAuthzService]
136
+ };
137
+ isStrategyInited = true;
138
+ return configs;
139
+ };
140
+ let SessionAuthzModule = class SessionAuthzModule extends ConfigurableModuleClass {
141
+ /**
142
+ * Configures authz module.
143
+ *
144
+ * Note: DO NOT register the same routes in multiple session authz modules, or import the same session authz module in the same module multiple times, express-session middleware will not work properly.
145
+ */
146
+ static register(options) {
147
+ const sessionAuthzOptions = (0, session_authz_interface_1.normalizedSessionAuthzModuleOptions)(options);
148
+ return (0, utils_1.mergeDynamicModuleConfigs)(super.register({ ...options, authzProvider }), getCommonConfigs(), {
149
+ providers: [
150
+ {
151
+ provide: SESSION_AUTHZ_OPTIONS,
152
+ useValue: sessionAuthzOptions
153
+ }
154
+ ]
155
+ });
156
+ }
157
+ /**
158
+ * Configures authz module asynchronously.
159
+ *
160
+ * Note: DO NOT register the same routes in multiple session authz modules, express-session middleware will not work properly.
161
+ */
162
+ static registerAsync(options) {
163
+ return (0, utils_1.mergeDynamicModuleConfigs)(super.registerAsync({ ...options, authzProvider }), getCommonConfigs(), {
164
+ providers: [
165
+ {
166
+ provide: SESSION_AUTHZ_OPTIONS,
167
+ useFactory: (moduleOptions) => {
168
+ return (0, session_authz_interface_1.normalizedSessionAuthzModuleOptions)(moduleOptions);
169
+ },
170
+ inject: [MODULE_OPTIONS_TOKEN]
171
+ }
172
+ ]
173
+ });
174
+ }
175
+ constructor(routesOpt, sessionAuthzOptions) {
176
+ super();
177
+ this.routesOpt = routesOpt;
178
+ this.sessionAuthzOptions = sessionAuthzOptions;
179
+ }
180
+ configure(consumer) {
181
+ consumer
182
+ .apply((0, express_session_1.default)(this.sessionAuthzOptions.session), SessionAuthzAlsMiddleware)
183
+ .exclude(...this.routesOpt.excludes)
184
+ // nestjs v11 will be compatible with splat wildcard.
185
+ .forRoutes(...(this.routesOpt.global ? ['*'] : this.routesOpt.routes));
186
+ }
187
+ };
188
+ SessionAuthzModule = __decorate([
189
+ (0, common_1.Module)({}),
190
+ __param(0, (0, common_1.Inject)(constants_1.ROUTES_OPTIONS)),
191
+ __param(1, (0, common_1.Inject)(SESSION_AUTHZ_OPTIONS)),
192
+ __metadata("design:paramtypes", [Object, Object])
193
+ ], SessionAuthzModule);
194
+ return {
195
+ /**
196
+ * A dynamic module used to configure session based authentication and authorization features for the application.
197
+ *
198
+ * This module can be configured using 2 static methods:
199
+ *
200
+ * - `register`
201
+ * - `registerAsync`
202
+ *
203
+ * ### Usage
204
+ *
205
+ * ```typescript
206
+ * ⁣@Module({
207
+ * imports: [
208
+ * // Import and configure session strategy
209
+ * AuthzModule.register({
210
+ * session: {
211
+ * name: 'custom-session-id-name',
212
+ * secret: '1234567890'
213
+ * },
214
+ * // Define routes that use AuthzGuard
215
+ * routes: [BusinessController]
216
+ * })
217
+ * ],
218
+ * controllers: [BusinessController]
219
+ * })
220
+ * export class BusinessModule {}
221
+ * ```
222
+ */
223
+ AuthzModule: SessionAuthzModule,
224
+ /**
225
+ * A custom guard that applies authentication to controllers.
226
+ *
227
+ * This guard also provides 3 utility decorators to apply and modify authorization:
228
+ *
229
+ * - `@AuthzGuard.Verify`: Used to verify the user's authorization for specific meta data.
230
+ * - `@AuthzGuard.NoVerify`: Used to `skip` authentication & authorization checks for specific routes.
231
+ * - `@AuthzGuard.Apply`: A simplified version of `@UseGuards(AuthzGuard)` and `@AuthzGuard.Verify`, combining both for convenience.
232
+ *
233
+ * ### Usage:
234
+ *
235
+ * ```typescript
236
+ * ⁣@UseGuards(AuthzGuard)
237
+ * ⁣@Controller(/⁣/ ...)
238
+ * export class BusinessController {
239
+ * // ...
240
+ * }
241
+ * ```
242
+ */
243
+ AuthzGuard: SessionAuthzGuard,
244
+ /**
245
+ * A custom servcie to provide methods to handle authentication and authorization.
246
+ */
247
+ AuthzService: SessionAuthzService
248
+ };
249
+ };
250
+ exports.cereateSessionAuthzModule = cereateSessionAuthzModule;