@node-c/api-http 1.0.0-alpha9 → 1.0.0-beta1
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.
- package/dist/common/definitions/common.constants.d.ts +1 -1
- package/dist/common/definitions/common.constants.js +1 -1
- package/dist/common/definitions/common.constants.js.map +1 -1
- package/dist/common/utils/index.d.ts +1 -0
- package/dist/{exceptionFilters → common/utils}/index.js +1 -1
- package/dist/common/utils/index.js.map +1 -0
- package/dist/common/utils/utils.checkRoutes.d.ts +1 -0
- package/dist/common/utils/utils.checkRoutes.js +27 -0
- package/dist/common/utils/utils.checkRoutes.js.map +1 -0
- package/dist/decorators/http.decorators.accessControl.d.ts +9 -0
- package/dist/decorators/http.decorators.accessControl.js +7 -0
- package/dist/decorators/http.decorators.accessControl.js.map +1 -0
- package/dist/decorators/index.d.ts +1 -0
- package/dist/decorators/index.js +18 -0
- package/dist/decorators/index.js.map +1 -0
- package/dist/{exceptionFilters/http.exceptionFilters.httpException.js → filters/http.filtes.exception.js} +1 -1
- package/dist/filters/http.filtes.exception.js.map +1 -0
- package/dist/filters/index.d.ts +1 -0
- package/dist/filters/index.js +18 -0
- package/dist/filters/index.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/interceptors/http.interceptors.accessControl.d.ts +12 -0
- package/dist/interceptors/http.interceptors.accessControl.js +94 -0
- package/dist/interceptors/http.interceptors.accessControl.js.map +1 -0
- package/dist/interceptors/http.interceptors.error.d.ts +3 -0
- package/dist/interceptors/http.interceptors.error.js +11 -3
- package/dist/interceptors/http.interceptors.error.js.map +1 -1
- package/dist/interceptors/index.d.ts +1 -1
- package/dist/interceptors/index.js +1 -1
- package/dist/middlewares/http.middlewares.authorization.d.ts +15 -0
- package/dist/middlewares/http.middlewares.authorization.js +156 -0
- package/dist/middlewares/http.middlewares.authorization.js.map +1 -0
- package/dist/middlewares/http.middlewares.cors.js +1 -1
- package/dist/middlewares/http.middlewares.cors.js.map +1 -1
- package/dist/middlewares/http.middlewares.requestLogging.d.ts +10 -0
- package/dist/middlewares/http.middlewares.requestLogging.js +35 -0
- package/dist/middlewares/http.middlewares.requestLogging.js.map +1 -0
- package/dist/middlewares/index.d.ts +2 -1
- package/dist/middlewares/index.js +2 -1
- package/dist/middlewares/index.js.map +1 -1
- package/dist/module/http.api.module.js +15 -7
- package/dist/module/http.api.module.js.map +1 -1
- package/package.json +12 -7
- package/src/common/definitions/common.constants.ts +1 -1
- package/src/common/utils/index.ts +1 -0
- package/src/common/utils/utils.checkRoutes.ts +31 -0
- package/src/decorators/http.decorators.accessControl.ts +8 -0
- package/src/decorators/index.ts +1 -0
- package/src/filters/index.ts +1 -0
- package/src/index.ts +2 -1
- package/src/interceptors/http.interceptors.accessControl.ts +101 -0
- package/src/interceptors/http.interceptors.error.ts +8 -7
- package/src/interceptors/index.ts +1 -1
- package/src/middlewares/http.middlewares.authorization.ts +155 -0
- package/src/middlewares/http.middlewares.cors.ts +1 -1
- package/src/middlewares/http.middlewares.requestLogging.ts +22 -0
- package/src/middlewares/index.ts +2 -1
- package/src/module/http.api.module.ts +17 -6
- package/dist/exceptionFilters/http.exceptionFilters.httpException.js.map +0 -1
- package/dist/exceptionFilters/index.d.ts +0 -1
- package/dist/exceptionFilters/index.js.map +0 -1
- package/dist/interceptors/http.interceptors.authorization.d.ts +0 -11
- package/dist/interceptors/http.interceptors.authorization.js +0 -87
- package/dist/interceptors/http.interceptors.authorization.js.map +0 -1
- package/dist/middlewares/http.middlewares.authentication.d.ts +0 -13
- package/dist/middlewares/http.middlewares.authentication.js +0 -128
- package/dist/middlewares/http.middlewares.authentication.js.map +0 -1
- package/src/exceptionFilters/index.ts +0 -1
- package/src/interceptors/http.interceptors.authorization.ts +0 -82
- package/src/middlewares/http.middlewares.authentication.ts +0 -111
- /package/dist/{exceptionFilters/http.exceptionFilters.httpException.d.ts → filters/http.filtes.exception.d.ts} +0 -0
- /package/src/{exceptionFilters/http.exceptionFilters.httpException.ts → filters/http.filtes.exception.ts} +0 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { DynamicModule, Inject, MiddlewareConsumer, ModuleMetadata } from '@nestjs/common';
|
|
1
|
+
import { DynamicModule, Inject, MiddlewareConsumer, ModuleMetadata, ValidationPipe } from '@nestjs/common';
|
|
2
|
+
import { APP_PIPE } from '@nestjs/core';
|
|
2
3
|
|
|
3
4
|
import { ConfigProviderService, loadDynamicModules } from '@node-c/core';
|
|
4
5
|
|
|
@@ -8,9 +9,9 @@ import express, { Response } from 'express';
|
|
|
8
9
|
import { HTTPAPIModuleOptions } from './http.api.module.definitions';
|
|
9
10
|
|
|
10
11
|
import { Constants, RequestWithLocals } from '../common/definitions';
|
|
11
|
-
import { HttpExceptionFilter } from '../
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
12
|
+
import { HttpExceptionFilter } from '../filters';
|
|
13
|
+
import { HTTPAccessControlInterceptor, HTTPErrorInterceptor } from '../interceptors';
|
|
14
|
+
import { HTTPAuthorizationMiddleware, HTTPCORSMiddleware, HTTPRequestLoggingMiddleware } from '../middlewares';
|
|
14
15
|
|
|
15
16
|
export class HTTPAPIModule {
|
|
16
17
|
constructor(
|
|
@@ -25,8 +26,10 @@ export class HTTPAPIModule {
|
|
|
25
26
|
consumer.apply(express.urlencoded({ verify: HTTPAPIModule.rawBodyBuffer, extended: true })).forRoutes('*');
|
|
26
27
|
consumer.apply(express.json({ verify: HTTPAPIModule.rawBodyBuffer })).forRoutes('*');
|
|
27
28
|
consumer.apply(cookieParser()).forRoutes('*');
|
|
29
|
+
// configure logging
|
|
30
|
+
consumer.apply(HTTPRequestLoggingMiddleware).forRoutes('*');
|
|
28
31
|
consumer.apply(HTTPCORSMiddleware).forRoutes('*');
|
|
29
|
-
consumer.apply(
|
|
32
|
+
consumer.apply(HTTPAuthorizationMiddleware).forRoutes('*');
|
|
30
33
|
}
|
|
31
34
|
|
|
32
35
|
static rawBodyBuffer(req: RequestWithLocals<unknown>, _res: Response, buffer: Buffer): void {
|
|
@@ -43,13 +46,21 @@ export class HTTPAPIModule {
|
|
|
43
46
|
module: moduleClass as DynamicModule['module'],
|
|
44
47
|
imports: [...(importsAtStart || []), ...(importsAtEnd || [])],
|
|
45
48
|
providers: [
|
|
49
|
+
// configure DTO validation
|
|
50
|
+
{
|
|
51
|
+
provide: APP_PIPE,
|
|
52
|
+
// useClass: ValidationPipe
|
|
53
|
+
useValue: new ValidationPipe({
|
|
54
|
+
whitelist: true
|
|
55
|
+
})
|
|
56
|
+
},
|
|
46
57
|
{
|
|
47
58
|
provide: Constants.API_MODULE_NAME,
|
|
48
59
|
useValue: options.moduleName
|
|
49
60
|
},
|
|
50
61
|
{
|
|
51
62
|
provide: Constants.AUTHORIZATION_INTERCEPTOR,
|
|
52
|
-
useClass:
|
|
63
|
+
useClass: HTTPAccessControlInterceptor
|
|
53
64
|
},
|
|
54
65
|
{
|
|
55
66
|
provide: Constants.ERROR_INTERCEPTOR,
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http.exceptionFilters.httpException.js","sourceRoot":"","sources":["../../src/exceptionFilters/http.exceptionFilters.httpException.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAAsF;AAK/E,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAC9B,KAAK,CAAC,SAAwB,EAAE,IAAmB;QACjD,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAChC,MAAM,QAAQ,GAAG,GAAG,CAAC,WAAW,EAAY,CAAC;QAC7C,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,EAAE,CAAC;QACrC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YAC3B,UAAU,EAAE,MAAM;YAClB,OAAO,EAAE,SAAS,CAAC,OAAO;SAC3B,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAVY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,cAAK,EAAC,sBAAa,CAAC;GACR,mBAAmB,CAU/B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './http.exceptionFilters.httpException';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/exceptionFilters/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wEAAsD"}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
|
|
2
|
-
import { ConfigProviderService } from '@node-c/core';
|
|
3
|
-
import { AuthorizationPoint, IAMAuthorizationService, UserWithPermissionsData } from '@node-c/domain-iam';
|
|
4
|
-
import { Observable } from 'rxjs';
|
|
5
|
-
export declare class HTTPAuthorizationInterceptor<User extends UserWithPermissionsData<unknown, unknown>> implements NestInterceptor {
|
|
6
|
-
protected authorizationService: IAMAuthorizationService<AuthorizationPoint<unknown>>;
|
|
7
|
-
protected configProvider: ConfigProviderService;
|
|
8
|
-
protected moduleName: string;
|
|
9
|
-
constructor(authorizationService: IAMAuthorizationService<AuthorizationPoint<unknown>>, configProvider: ConfigProviderService, moduleName: string);
|
|
10
|
-
intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>>;
|
|
11
|
-
}
|
|
@@ -1,87 +0,0 @@
|
|
|
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;
|
|
7
|
-
};
|
|
8
|
-
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
-
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
-
};
|
|
11
|
-
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
-
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
-
};
|
|
14
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
15
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
16
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
17
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
18
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
19
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
20
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
21
|
-
});
|
|
22
|
-
};
|
|
23
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
-
exports.HTTPAuthorizationInterceptor = void 0;
|
|
25
|
-
const common_1 = require("@nestjs/common");
|
|
26
|
-
const core_1 = require("@node-c/core");
|
|
27
|
-
const domain_iam_1 = require("@node-c/domain-iam");
|
|
28
|
-
const general_tools_1 = require("@ramster/general-tools");
|
|
29
|
-
const definitions_1 = require("../common/definitions");
|
|
30
|
-
let HTTPAuthorizationInterceptor = class HTTPAuthorizationInterceptor {
|
|
31
|
-
constructor(authorizationService, configProvider, moduleName) {
|
|
32
|
-
this.authorizationService = authorizationService;
|
|
33
|
-
this.configProvider = configProvider;
|
|
34
|
-
this.moduleName = moduleName;
|
|
35
|
-
}
|
|
36
|
-
intercept(context, next) {
|
|
37
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
38
|
-
const [req] = context.getArgs();
|
|
39
|
-
const locals = req.locals;
|
|
40
|
-
if (!locals) {
|
|
41
|
-
throw new common_1.HttpException('Forbidden', common_1.HttpStatus.FORBIDDEN);
|
|
42
|
-
}
|
|
43
|
-
else if (locals.isAnonymous) {
|
|
44
|
-
return next.handle();
|
|
45
|
-
}
|
|
46
|
-
const { moduleName } = this;
|
|
47
|
-
const controllerName = context.getClass().name;
|
|
48
|
-
const handlerName = context.getHandler().name;
|
|
49
|
-
const authorizationData = yield this.authorizationService.mapAuthorizationPoints(moduleName);
|
|
50
|
-
let controllerData = authorizationData[controllerName];
|
|
51
|
-
if (!controllerData) {
|
|
52
|
-
controllerData = authorizationData.__all;
|
|
53
|
-
}
|
|
54
|
-
const user = locals.user;
|
|
55
|
-
let handlerData = controllerData[handlerName];
|
|
56
|
-
if (!handlerData) {
|
|
57
|
-
handlerData = controllerData.__all;
|
|
58
|
-
if (!Object.keys(handlerData).length) {
|
|
59
|
-
const { endpointSecurityMode } = this.configProvider.config.api[moduleName];
|
|
60
|
-
if (!endpointSecurityMode || endpointSecurityMode === core_1.EndpointSecurityMode.Strict) {
|
|
61
|
-
console.info(`[${moduleName}][HTTPAuthorizationInterceptor]: No authorization point data for handler ${controllerName}.${handlerName}.`);
|
|
62
|
-
throw new common_1.HttpException('Forbidden', common_1.HttpStatus.FORBIDDEN);
|
|
63
|
-
}
|
|
64
|
-
return next.handle();
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
const { hasAccess, inputDataToBeMutated } = domain_iam_1.IAMAuthorizationService.checkAccess(handlerData, { body: req.body, headers: req.headers, params: req.params, query: req.query }, user);
|
|
68
|
-
if (!hasAccess) {
|
|
69
|
-
console.info(`[${moduleName}][HTTPAuthorizationInterceptor]: No user access to handler ${controllerName}.${handlerName}.`);
|
|
70
|
-
throw new common_1.HttpException('Forbidden', common_1.HttpStatus.FORBIDDEN);
|
|
71
|
-
}
|
|
72
|
-
for (const key in inputDataToBeMutated) {
|
|
73
|
-
(0, general_tools_1.setNested)(req, key, inputDataToBeMutated[key]);
|
|
74
|
-
}
|
|
75
|
-
return next.handle();
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
};
|
|
79
|
-
exports.HTTPAuthorizationInterceptor = HTTPAuthorizationInterceptor;
|
|
80
|
-
exports.HTTPAuthorizationInterceptor = HTTPAuthorizationInterceptor = __decorate([
|
|
81
|
-
(0, common_1.Injectable)(),
|
|
82
|
-
__param(0, (0, common_1.Inject)(definitions_1.Constants.API_MODULE_AUTHORIZATION_SERVICE)),
|
|
83
|
-
__param(2, (0, common_1.Inject)(definitions_1.Constants.API_MODULE_NAME)),
|
|
84
|
-
__metadata("design:paramtypes", [domain_iam_1.IAMAuthorizationService,
|
|
85
|
-
core_1.ConfigProviderService, String])
|
|
86
|
-
], HTTPAuthorizationInterceptor);
|
|
87
|
-
//# sourceMappingURL=http.interceptors.authorization.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http.interceptors.authorization.js","sourceRoot":"","sources":["../../src/interceptors/http.interceptors.authorization.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAQwB;AAExB,uCAA2E;AAC3E,mDAA0G;AAE1G,0DAAmD;AAGnD,uDAAqE;AAG9D,IAAM,4BAA4B,GAAlC,MAAM,4BAA4B;IAGvC,YAGY,oBAA0E,EAE1E,cAAqC,EAGrC,UAAkB;QALlB,yBAAoB,GAApB,oBAAoB,CAAsD;QAE1E,mBAAc,GAAd,cAAc,CAAuB;QAGrC,eAAU,GAAV,UAAU,CAAQ;IAC3B,CAAC;IAEE,SAAS,CAAC,OAAyB,EAAE,IAAiB;;YAC1D,MAAM,CAAC,GAAG,CAAC,GAAuC,OAAO,CAAC,OAAO,EAAE,CAAC;YACpE,MAAM,MAAM,GAAG,GAAG,CAAC,MAAO,CAAC;YAC3B,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,IAAI,sBAAa,CAAC,WAAW,EAAE,mBAAU,CAAC,SAAS,CAAC,CAAC;YAC7D,CAAC;iBAAM,IAAI,MAAM,CAAC,WAAW,E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GAAG,oCAAuB,CAAC,WAAW,CAC7E,WAAW,EACX,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,EAC9E,IAAI,CACL,CAAC;YACF,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,CACV,IAAI,UAAU,8DAA8D,cAAc,IAAI,WAAW,GAAG,CAC7G,CAAC;gBACF,MAAM,IAAI,sBAAa,CAAC,WAAW,EAAE,mBAAU,CAAC,SAAS,CAAC,CAAC;YAC7D,CAAC;YACD,KAAK,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;gBACvC,IAAA,yBAAS,EAAC,GAAG,EAAE,GAAG,EAAE,oBAAoB,CAAC,GAAG,CAAC,CAAC,CAAC;YACjD,CAAC;YACD,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;QACvB,CAAC;KAAA;CACF,CAAA;AA9DY,oEAA4B;uCAA5B,4BAA4B;IADxC,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,eAAM,EAAC,uBAAS,CAAC,gCAAgC,CAAC,CAAA;IAKlD,WAAA,IAAA,eAAM,EAAC,uBAAS,CAAC,eAAe,CAAC,CAAA;qCAHF,oCAAuB;QAE7B,4BAAqB;GARtC,4BAA4B,CA8DxC"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { NestMiddleware } from '@nestjs/common';
|
|
2
|
-
import { ConfigProviderService } from '@node-c/core';
|
|
3
|
-
import { IAMTokenManagerService, IAMUsersService, UserTokenEnityFields } from '@node-c/domain-iam';
|
|
4
|
-
import { NextFunction, Response } from 'express';
|
|
5
|
-
import { RequestWithLocals } from '../common/definitions';
|
|
6
|
-
export declare class HTTPAuthenticationMiddleware<User extends object> implements NestMiddleware {
|
|
7
|
-
protected configProvider: ConfigProviderService;
|
|
8
|
-
protected moduleName: string;
|
|
9
|
-
protected tokenManager: IAMTokenManagerService<UserTokenEnityFields>;
|
|
10
|
-
protected usersService: IAMUsersService<User>;
|
|
11
|
-
constructor(configProvider: ConfigProviderService, moduleName: string, tokenManager: IAMTokenManagerService<UserTokenEnityFields>, usersService: IAMUsersService<User>);
|
|
12
|
-
use(req: RequestWithLocals<unknown>, res: Response, next: NextFunction): void;
|
|
13
|
-
}
|
|
@@ -1,128 +0,0 @@
|
|
|
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;
|
|
7
|
-
};
|
|
8
|
-
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
-
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
-
};
|
|
11
|
-
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
-
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
-
};
|
|
14
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
15
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
16
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
17
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
18
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
19
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
20
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
21
|
-
});
|
|
22
|
-
};
|
|
23
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
-
exports.HTTPAuthenticationMiddleware = void 0;
|
|
25
|
-
const common_1 = require("@nestjs/common");
|
|
26
|
-
const core_1 = require("@node-c/core");
|
|
27
|
-
const domain_iam_1 = require("@node-c/domain-iam");
|
|
28
|
-
const general_tools_1 = require("@ramster/general-tools");
|
|
29
|
-
const definitions_1 = require("../common/definitions");
|
|
30
|
-
let HTTPAuthenticationMiddleware = class HTTPAuthenticationMiddleware {
|
|
31
|
-
constructor(configProvider, moduleName, tokenManager, usersService) {
|
|
32
|
-
this.configProvider = configProvider;
|
|
33
|
-
this.moduleName = moduleName;
|
|
34
|
-
this.tokenManager = tokenManager;
|
|
35
|
-
this.usersService = usersService;
|
|
36
|
-
}
|
|
37
|
-
use(req, res, next) {
|
|
38
|
-
(() => __awaiter(this, void 0, void 0, function* () {
|
|
39
|
-
var _a;
|
|
40
|
-
const { anonymousAccessRoutes } = this.configProvider.config.api[this.moduleName];
|
|
41
|
-
if (!req.locals) {
|
|
42
|
-
req.locals = {};
|
|
43
|
-
}
|
|
44
|
-
if (anonymousAccessRoutes && Object.keys(anonymousAccessRoutes).length) {
|
|
45
|
-
const originalUrl = req.originalUrl.split('?')[0];
|
|
46
|
-
let isAnonymous = false;
|
|
47
|
-
for (const route in anonymousAccessRoutes) {
|
|
48
|
-
if ((0, general_tools_1.checkRoutes)(originalUrl, [route]) &&
|
|
49
|
-
anonymousAccessRoutes[route].find(method => method === req.method.toLowerCase())) {
|
|
50
|
-
isAnonymous = true;
|
|
51
|
-
break;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
if (isAnonymous) {
|
|
55
|
-
req.locals.isAnonymous = true;
|
|
56
|
-
next();
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
const { tokenManager, usersService } = this;
|
|
61
|
-
let tokens = [];
|
|
62
|
-
let authToken = req.headers.authorization;
|
|
63
|
-
let authTokenIsNew = false;
|
|
64
|
-
let refreshToken;
|
|
65
|
-
let tokenContent;
|
|
66
|
-
let useCookie = false;
|
|
67
|
-
if (typeof authToken === 'string' && authToken.length && authToken.match(/^Bearer\s/)) {
|
|
68
|
-
tokens = authToken.split(' ');
|
|
69
|
-
if (tokens.length) {
|
|
70
|
-
authToken = tokens[1];
|
|
71
|
-
refreshToken = tokens[2];
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
else {
|
|
75
|
-
authToken = req.cookies['sid'];
|
|
76
|
-
useCookie = true;
|
|
77
|
-
}
|
|
78
|
-
if (!authToken) {
|
|
79
|
-
console.error('Missing auth token.');
|
|
80
|
-
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
81
|
-
}
|
|
82
|
-
try {
|
|
83
|
-
const tokenRes = yield tokenManager.verifyAccessToken(authToken, {
|
|
84
|
-
deleteFromStoreIfExpired: true,
|
|
85
|
-
identifierDataField: 'userId',
|
|
86
|
-
persistNewToken: true,
|
|
87
|
-
purgeStoreOnRenew: true,
|
|
88
|
-
refreshToken,
|
|
89
|
-
refreshTokenAccessTokenIdentifierDataField: 'accessToken'
|
|
90
|
-
});
|
|
91
|
-
tokenContent = tokenRes.content;
|
|
92
|
-
if (tokenRes.newToken) {
|
|
93
|
-
authTokenIsNew = true;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
catch (e) {
|
|
97
|
-
console.error('Failed to parse the access or refresh token:', e);
|
|
98
|
-
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
99
|
-
}
|
|
100
|
-
if (authTokenIsNew) {
|
|
101
|
-
res.setHeader('Authorization', `Bearer ${authToken}${refreshToken ? ` ${refreshToken}` : ''}`);
|
|
102
|
-
if (useCookie) {
|
|
103
|
-
res.cookie('sid', authToken);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
const userId = (_a = tokenContent === null || tokenContent === void 0 ? void 0 : tokenContent.data) === null || _a === void 0 ? void 0 : _a.userId;
|
|
107
|
-
if (!userId) {
|
|
108
|
-
console.error('Missing userId in the tokenContent data.');
|
|
109
|
-
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
110
|
-
}
|
|
111
|
-
req.locals.user = yield usersService.getUserWithPermissionsData({ filters: { id: userId } });
|
|
112
|
-
next();
|
|
113
|
-
}))().then(() => true, err => {
|
|
114
|
-
console.error(err);
|
|
115
|
-
res.status((err && err.status) || common_1.HttpStatus.INTERNAL_SERVER_ERROR).end();
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
};
|
|
119
|
-
exports.HTTPAuthenticationMiddleware = HTTPAuthenticationMiddleware;
|
|
120
|
-
exports.HTTPAuthenticationMiddleware = HTTPAuthenticationMiddleware = __decorate([
|
|
121
|
-
(0, common_1.Injectable)(),
|
|
122
|
-
__param(1, (0, common_1.Inject)(definitions_1.Constants.API_MODULE_NAME)),
|
|
123
|
-
__param(2, (0, common_1.Inject)(definitions_1.Constants.AUTHENTICATION_MIDDLEWARE_TOKEN_MANAGER_SERVICE)),
|
|
124
|
-
__param(3, (0, common_1.Inject)(definitions_1.Constants.AUTHENTICATION_MIDDLEWARE_USERS_SERVICE)),
|
|
125
|
-
__metadata("design:paramtypes", [core_1.ConfigProviderService, String, domain_iam_1.IAMTokenManagerService,
|
|
126
|
-
domain_iam_1.IAMUsersService])
|
|
127
|
-
], HTTPAuthenticationMiddleware);
|
|
128
|
-
//# sourceMappingURL=http.middlewares.authentication.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http.middlewares.authentication.js","sourceRoot":"","sources":["../../src/middlewares/http.middlewares.authentication.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA+F;AAE/F,uCAAuE;AACvE,mDAAwH;AAExH,0DAAqD;AAIrD,uDAAqE;A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,IAAI,mBAAU,CAAC,qBAAqB,CAAC,CAAC,GAAG,EAAE,CAAC;QAC5E,CAAC,CACF,CAAC;IACJ,CAAC;CACF,CAAA;AAlGY,oEAA4B;uCAA5B,4BAA4B;IADxC,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,eAAM,EAAC,uBAAS,CAAC,eAAe,CAAC,CAAA;IAGjC,WAAA,IAAA,eAAM,EAAC,uBAAS,CAAC,+CAA+C,CAAC,CAAA;IAGjE,WAAA,IAAA,eAAM,EAAC,uBAAS,CAAC,uCAAuC,CAAC,CAAA;qCAPhC,4BAAqB,UAMvB,mCAAsB;QAGtB,4BAAe;GAZ9B,4BAA4B,CAkGxC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './http.exceptionFilters.httpException';
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
CallHandler,
|
|
3
|
-
ExecutionContext,
|
|
4
|
-
HttpException,
|
|
5
|
-
HttpStatus,
|
|
6
|
-
Inject,
|
|
7
|
-
Injectable,
|
|
8
|
-
NestInterceptor
|
|
9
|
-
} from '@nestjs/common';
|
|
10
|
-
|
|
11
|
-
import { ConfigProviderService, EndpointSecurityMode } from '@node-c/core';
|
|
12
|
-
import { AuthorizationPoint, IAMAuthorizationService, UserWithPermissionsData } from '@node-c/domain-iam';
|
|
13
|
-
|
|
14
|
-
import { setNested } from '@ramster/general-tools';
|
|
15
|
-
import { Observable } from 'rxjs';
|
|
16
|
-
|
|
17
|
-
import { Constants, RequestWithLocals } from '../common/definitions';
|
|
18
|
-
|
|
19
|
-
@Injectable()
|
|
20
|
-
export class HTTPAuthorizationInterceptor<User extends UserWithPermissionsData<unknown, unknown>>
|
|
21
|
-
implements NestInterceptor
|
|
22
|
-
{
|
|
23
|
-
constructor(
|
|
24
|
-
@Inject(Constants.API_MODULE_AUTHORIZATION_SERVICE)
|
|
25
|
-
// eslint-disable-next-line no-unused-vars
|
|
26
|
-
protected authorizationService: IAMAuthorizationService<AuthorizationPoint<unknown>>,
|
|
27
|
-
// eslint-disable-next-line no-unused-vars
|
|
28
|
-
protected configProvider: ConfigProviderService,
|
|
29
|
-
@Inject(Constants.API_MODULE_NAME)
|
|
30
|
-
// eslint-disable-next-line no-unused-vars
|
|
31
|
-
protected moduleName: string
|
|
32
|
-
) {}
|
|
33
|
-
|
|
34
|
-
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
|
|
35
|
-
const [req]: [RequestWithLocals<User>, unknown] = context.getArgs();
|
|
36
|
-
const locals = req.locals!;
|
|
37
|
-
if (!locals) {
|
|
38
|
-
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
|
|
39
|
-
} else if (locals.isAnonymous) {
|
|
40
|
-
return next.handle();
|
|
41
|
-
}
|
|
42
|
-
const { moduleName } = this;
|
|
43
|
-
const controllerName = context.getClass().name;
|
|
44
|
-
const handlerName = context.getHandler().name;
|
|
45
|
-
// TODO: cache this in-memory
|
|
46
|
-
const authorizationData = await this.authorizationService.mapAuthorizationPoints(moduleName);
|
|
47
|
-
let controllerData = authorizationData![controllerName];
|
|
48
|
-
if (!controllerData) {
|
|
49
|
-
controllerData = authorizationData.__all;
|
|
50
|
-
}
|
|
51
|
-
const user = locals.user!; // we'll always have this, otherwise the system has not been configured properly
|
|
52
|
-
let handlerData = controllerData[handlerName];
|
|
53
|
-
if (!handlerData) {
|
|
54
|
-
handlerData = controllerData.__all;
|
|
55
|
-
if (!Object.keys(handlerData).length) {
|
|
56
|
-
const { endpointSecurityMode } = this.configProvider.config.api[moduleName];
|
|
57
|
-
if (!endpointSecurityMode || endpointSecurityMode === EndpointSecurityMode.Strict) {
|
|
58
|
-
console.info(
|
|
59
|
-
`[${moduleName}][HTTPAuthorizationInterceptor]: No authorization point data for handler ${controllerName}.${handlerName}.`
|
|
60
|
-
);
|
|
61
|
-
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
|
|
62
|
-
}
|
|
63
|
-
return next.handle();
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
const { hasAccess, inputDataToBeMutated } = IAMAuthorizationService.checkAccess(
|
|
67
|
-
handlerData,
|
|
68
|
-
{ body: req.body, headers: req.headers, params: req.params, query: req.query },
|
|
69
|
-
user
|
|
70
|
-
);
|
|
71
|
-
if (!hasAccess) {
|
|
72
|
-
console.info(
|
|
73
|
-
`[${moduleName}][HTTPAuthorizationInterceptor]: No user access to handler ${controllerName}.${handlerName}.`
|
|
74
|
-
);
|
|
75
|
-
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
|
|
76
|
-
}
|
|
77
|
-
for (const key in inputDataToBeMutated) {
|
|
78
|
-
setNested(req, key, inputDataToBeMutated[key]);
|
|
79
|
-
}
|
|
80
|
-
return next.handle();
|
|
81
|
-
}
|
|
82
|
-
}
|
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
import { HttpException, HttpStatus, Inject, Injectable, NestMiddleware } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
import { AppConfigAPIHTTP, ConfigProviderService } from '@node-c/core';
|
|
4
|
-
import { DecodedTokenContent, IAMTokenManagerService, IAMUsersService, UserTokenEnityFields } from '@node-c/domain-iam';
|
|
5
|
-
|
|
6
|
-
import { checkRoutes } from '@ramster/general-tools';
|
|
7
|
-
|
|
8
|
-
import { NextFunction, Response } from 'express';
|
|
9
|
-
|
|
10
|
-
import { Constants, RequestWithLocals } from '../common/definitions';
|
|
11
|
-
|
|
12
|
-
@Injectable()
|
|
13
|
-
export class HTTPAuthenticationMiddleware<User extends object> implements NestMiddleware {
|
|
14
|
-
constructor(
|
|
15
|
-
// eslint-disable-next-line no-unused-vars
|
|
16
|
-
protected configProvider: ConfigProviderService,
|
|
17
|
-
@Inject(Constants.API_MODULE_NAME)
|
|
18
|
-
// eslint-disable-next-line no-unused-vars
|
|
19
|
-
protected moduleName: string,
|
|
20
|
-
@Inject(Constants.AUTHENTICATION_MIDDLEWARE_TOKEN_MANAGER_SERVICE)
|
|
21
|
-
// eslint-disable-next-line no-unused-vars
|
|
22
|
-
protected tokenManager: IAMTokenManagerService<UserTokenEnityFields>,
|
|
23
|
-
@Inject(Constants.AUTHENTICATION_MIDDLEWARE_USERS_SERVICE)
|
|
24
|
-
// eslint-disable-next-line no-unused-vars
|
|
25
|
-
protected usersService: IAMUsersService<User>
|
|
26
|
-
) {}
|
|
27
|
-
|
|
28
|
-
use(req: RequestWithLocals<unknown>, res: Response, next: NextFunction): void {
|
|
29
|
-
(async () => {
|
|
30
|
-
const { anonymousAccessRoutes } = this.configProvider.config.api![this.moduleName] as AppConfigAPIHTTP;
|
|
31
|
-
if (!req.locals) {
|
|
32
|
-
req.locals = {};
|
|
33
|
-
}
|
|
34
|
-
if (anonymousAccessRoutes && Object.keys(anonymousAccessRoutes).length) {
|
|
35
|
-
const originalUrl = req.originalUrl.split('?')[0];
|
|
36
|
-
let isAnonymous = false;
|
|
37
|
-
for (const route in anonymousAccessRoutes) {
|
|
38
|
-
if (
|
|
39
|
-
checkRoutes(originalUrl, [route]) &&
|
|
40
|
-
anonymousAccessRoutes[route].find(method => method === req.method.toLowerCase())
|
|
41
|
-
) {
|
|
42
|
-
isAnonymous = true;
|
|
43
|
-
break;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if (isAnonymous) {
|
|
47
|
-
req.locals.isAnonymous = true;
|
|
48
|
-
next();
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
const { tokenManager, usersService } = this;
|
|
53
|
-
let tokens: string[] = [];
|
|
54
|
-
let authToken = req.headers.authorization;
|
|
55
|
-
let authTokenIsNew = false;
|
|
56
|
-
let refreshToken: string | undefined;
|
|
57
|
-
let tokenContent: DecodedTokenContent<UserTokenEnityFields> | undefined;
|
|
58
|
-
let useCookie = false;
|
|
59
|
-
if (typeof authToken === 'string' && authToken.length && authToken.match(/^Bearer\s/)) {
|
|
60
|
-
tokens = authToken.split(' ');
|
|
61
|
-
if (tokens.length) {
|
|
62
|
-
authToken = tokens[1];
|
|
63
|
-
refreshToken = tokens[2];
|
|
64
|
-
}
|
|
65
|
-
} else {
|
|
66
|
-
authToken = req.cookies['sid'];
|
|
67
|
-
useCookie = true;
|
|
68
|
-
}
|
|
69
|
-
if (!authToken) {
|
|
70
|
-
console.error('Missing auth token.');
|
|
71
|
-
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
|
|
72
|
-
}
|
|
73
|
-
try {
|
|
74
|
-
const tokenRes = await tokenManager.verifyAccessToken(authToken, {
|
|
75
|
-
deleteFromStoreIfExpired: true,
|
|
76
|
-
identifierDataField: 'userId',
|
|
77
|
-
persistNewToken: true,
|
|
78
|
-
purgeStoreOnRenew: true,
|
|
79
|
-
refreshToken,
|
|
80
|
-
refreshTokenAccessTokenIdentifierDataField: 'accessToken'
|
|
81
|
-
});
|
|
82
|
-
tokenContent = tokenRes.content!;
|
|
83
|
-
if (tokenRes.newToken) {
|
|
84
|
-
authTokenIsNew = true;
|
|
85
|
-
}
|
|
86
|
-
} catch (e) {
|
|
87
|
-
console.error('Failed to parse the access or refresh token:', e);
|
|
88
|
-
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
|
|
89
|
-
}
|
|
90
|
-
if (authTokenIsNew) {
|
|
91
|
-
res.setHeader('Authorization', `Bearer ${authToken}${refreshToken ? ` ${refreshToken}` : ''}`);
|
|
92
|
-
if (useCookie) {
|
|
93
|
-
res.cookie('sid', authToken);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
const userId = tokenContent?.data?.userId;
|
|
97
|
-
if (!userId) {
|
|
98
|
-
console.error('Missing userId in the tokenContent data.');
|
|
99
|
-
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
|
|
100
|
-
}
|
|
101
|
-
req.locals!.user = await usersService.getUserWithPermissionsData({ filters: { id: userId } });
|
|
102
|
-
next();
|
|
103
|
-
})().then(
|
|
104
|
-
() => true,
|
|
105
|
-
err => {
|
|
106
|
-
console.error(err);
|
|
107
|
-
res.status((err && err.status) || HttpStatus.INTERNAL_SERVER_ERROR).end();
|
|
108
|
-
}
|
|
109
|
-
);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
File without changes
|
|
File without changes
|