@node-c/api-http 1.0.0-alpha4 → 1.0.0-alpha40
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/utils/index.d.ts +1 -0
- package/dist/common/utils/index.js +18 -0
- 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/exceptionFilters/http.exceptionFilters.httpException.js.map +1 -1
- package/dist/interceptors/http.interceptors.authorization.js +5 -2
- package/dist/interceptors/http.interceptors.authorization.js.map +1 -1
- package/dist/interceptors/http.interceptors.error.d.ts +1 -1
- package/dist/interceptors/http.interceptors.error.js +8 -2
- package/dist/interceptors/http.interceptors.error.js.map +1 -1
- package/dist/middlewares/http.middlewares.authentication.d.ts +3 -3
- package/dist/middlewares/http.middlewares.authentication.js +57 -11
- package/dist/middlewares/http.middlewares.authentication.js.map +1 -1
- package/dist/middlewares/http.middlewares.cors.js +1 -1
- package/dist/middlewares/http.middlewares.cors.js.map +1 -1
- package/dist/module/http.api.module.js +14 -3
- package/dist/module/http.api.module.js.map +1 -1
- package/package.json +8 -6
- package/src/common/definitions/common.constants.ts +0 -16
- package/src/common/definitions/common.definitions.ts +0 -10
- package/src/common/definitions/common.errors.ts +0 -13
- package/src/common/definitions/index.ts +0 -2
- package/src/exceptionFilters/http.exceptionFilters.httpException.ts +0 -21
- package/src/exceptionFilters/index.ts +0 -1
- package/src/index.ts +0 -5
- package/src/interceptors/http.interceptors.authorization.ts +0 -82
- package/src/interceptors/http.interceptors.error.ts +0 -50
- package/src/interceptors/index.ts +0 -2
- package/src/middlewares/http.middlewares.authentication.ts +0 -111
- package/src/middlewares/http.middlewares.cors.ts +0 -37
- package/src/middlewares/index.ts +0 -2
- package/src/module/http.api.module.definitions.ts +0 -16
- package/src/module/http.api.module.ts +0 -69
- package/src/module/index.ts +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './utils.checkRoutes';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./utils.checkRoutes"), exports);
|
|
18
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function checkRoutes(route: string, routes: string[]): boolean;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.checkRoutes = checkRoutes;
|
|
4
|
+
function checkRoutes(route, routes) {
|
|
5
|
+
const splitRoute = route.split('/');
|
|
6
|
+
for (const i in routes) {
|
|
7
|
+
const item = routes[i], splitItem = item.split('/');
|
|
8
|
+
if (item === '*' || route === item) {
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
if (item.indexOf(':') !== -1 && splitItem.length === splitRoute.length) {
|
|
12
|
+
let valid = true;
|
|
13
|
+
for (const j in splitItem) {
|
|
14
|
+
const innerItem = splitItem[j], routeItem = splitRoute[j];
|
|
15
|
+
if (routeItem !== innerItem && innerItem.indexOf(':') === -1) {
|
|
16
|
+
valid = false;
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (valid) {
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=utils.checkRoutes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.checkRoutes.js","sourceRoot":"","sources":["../../../src/common/utils/utils.checkRoutes.ts"],"names":[],"mappings":";;AAMA,kCAwBC;AAxBD,SAAgB,WAAW,CAAC,KAAa,EAAE,MAAgB;IACzD,MAAM,UAAU,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACpC,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,EACpB,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC9B,IAAI,IAAI,KAAK,GAAG,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACnC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,IAAI,SAAS,CAAC,MAAM,KAAK,UAAU,CAAC,MAAM,EAAE,CAAC;YACvE,IAAI,KAAK,GAAG,IAAI,CAAC;YACjB,KAAK,MAAM,CAAC,IAAI,SAAS,EAAE,CAAC;gBAC1B,MAAM,SAAS,GAAG,SAAS,CAAC,CAAC,CAAC,EAC5B,SAAS,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;gBAC5B,IAAI,SAAS,KAAK,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;oBAC7D,KAAK,GAAG,KAAK,CAAC;oBACd,MAAM;gBACR,CAAC;YACH,CAAC;YACD,IAAI,KAAK,EAAE,CAAC;gBACV,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
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"}
|
|
@@ -20,12 +20,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
20
20
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
21
21
|
});
|
|
22
22
|
};
|
|
23
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
24
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
25
|
+
};
|
|
23
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
27
|
exports.HTTPAuthorizationInterceptor = void 0;
|
|
25
28
|
const common_1 = require("@nestjs/common");
|
|
26
29
|
const core_1 = require("@node-c/core");
|
|
27
30
|
const domain_iam_1 = require("@node-c/domain-iam");
|
|
28
|
-
const
|
|
31
|
+
const lodash_1 = __importDefault(require("lodash"));
|
|
29
32
|
const definitions_1 = require("../common/definitions");
|
|
30
33
|
let HTTPAuthorizationInterceptor = class HTTPAuthorizationInterceptor {
|
|
31
34
|
constructor(authorizationService, configProvider, moduleName) {
|
|
@@ -70,7 +73,7 @@ let HTTPAuthorizationInterceptor = class HTTPAuthorizationInterceptor {
|
|
|
70
73
|
throw new common_1.HttpException('Forbidden', common_1.HttpStatus.FORBIDDEN);
|
|
71
74
|
}
|
|
72
75
|
for (const key in inputDataToBeMutated) {
|
|
73
|
-
|
|
76
|
+
lodash_1.default.set(req, key, inputDataToBeMutated[key]);
|
|
74
77
|
}
|
|
75
78
|
return next.handle();
|
|
76
79
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.interceptors.authorization.js","sourceRoot":"","sources":["../../src/interceptors/http.interceptors.authorization.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"http.interceptors.authorization.js","sourceRoot":"","sources":["../../src/interceptors/http.interceptors.authorization.ts"],"names":[],"mappings":";;;;;;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C,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,5 +1,5 @@
|
|
|
1
1
|
import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
|
|
2
2
|
import { Observable } from 'rxjs';
|
|
3
3
|
export declare class HTTPErrorInterceptor implements NestInterceptor {
|
|
4
|
-
intercept(
|
|
4
|
+
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>;
|
|
5
5
|
}
|
|
@@ -9,10 +9,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
9
9
|
exports.HTTPErrorInterceptor = void 0;
|
|
10
10
|
const common_1 = require("@nestjs/common");
|
|
11
11
|
const core_1 = require("@node-c/core");
|
|
12
|
+
const rxjs_1 = require("rxjs");
|
|
12
13
|
const operators_1 = require("rxjs/operators");
|
|
13
14
|
const common_errors_1 = require("../common/definitions/common.errors");
|
|
14
15
|
let HTTPErrorInterceptor = class HTTPErrorInterceptor {
|
|
15
|
-
intercept(
|
|
16
|
+
intercept(context, next) {
|
|
16
17
|
return next.handle().pipe((0, operators_1.catchError)(error => {
|
|
17
18
|
console.error(error);
|
|
18
19
|
let message = 'An error has occurred.';
|
|
@@ -50,7 +51,12 @@ let HTTPErrorInterceptor = class HTTPErrorInterceptor {
|
|
|
50
51
|
message = error.message;
|
|
51
52
|
}
|
|
52
53
|
}
|
|
53
|
-
|
|
54
|
+
context
|
|
55
|
+
.switchToHttp()
|
|
56
|
+
.getResponse()
|
|
57
|
+
.status(status)
|
|
58
|
+
.json({ error: message instanceof Array ? message.join('\n') : message });
|
|
59
|
+
return new rxjs_1.Observable();
|
|
54
60
|
}));
|
|
55
61
|
}
|
|
56
62
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.interceptors.error.js","sourceRoot":"","sources":["../../src/interceptors/http.interceptors.error.ts"],"names":[],"mappings":";;;;;;;;;AAAA,
|
|
1
|
+
{"version":3,"file":"http.interceptors.error.js","sourceRoot":"","sources":["../../src/interceptors/http.interceptors.error.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAA4F;AAE5F,uCAAgD;AAEhD,+BAAkC;AAClC,8CAA4C;AAE5C,uEAAkE;AAG3D,IAAM,oBAAoB,GAA1B,MAAM,oBAAoB;IAC/B,SAAS,CAAC,OAAyB,EAAE,IAAiB;QACpD,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CACvB,IAAA,sBAAU,EAAC,KAAK,CAAC,EAAE;YACjB,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACrB,IAAI,OAAO,GAAsB,wBAAwB,CAAC;YAC1D,IAAI,MAAM,GAAG,GAAG,CAAC;YACjB,IAAI,KAAK,YAAY,uBAAgB,IAAI,KAAK,YAAY,2BAAW,EAAE,CAAC;gBACtE,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;oBAClB,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;gBAC1B,CAAC;gBACD,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;oBACf,IAAI,WAAW,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;wBAC9B,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,SAAmB,CAAC;oBAC1C,CAAC;yBAAM,IAAI,YAAY,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;wBACtC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,UAAoB,CAAC;oBAC3C,CAAC;yBAAM,CAAC;wBACN,MAAM,GAAG,GAAG,CAAC;oBACf,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,MAAM,GAAG,GAAG,CAAC;gBACf,CAAC;YACH,CAAC;iBAAM,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;gBAC1B,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;gBAC3B,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;oBACxB,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC;gBAC/B,CAAC;gBACD,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;oBACrB,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;gBAC7B,CAAC;YACH,CAAC;iBAAM,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;gBAClC,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;oBAClB,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;gBAC1B,CAAC;YACH,CAAC;YACD,OAAO;iBACJ,YAAY,EAAE;iBACd,WAAW,EAAE;iBACb,MAAM,CAAC,MAAM,CAAC;iBACd,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5E,OAAO,IAAI,iBAAU,EAAE,CAAC;QAC1B,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF,CAAA;AA5CY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,mBAAU,GAAE;GACA,oBAAoB,CA4ChC"}
|
|
@@ -6,8 +6,8 @@ import { RequestWithLocals } from '../common/definitions';
|
|
|
6
6
|
export declare class HTTPAuthenticationMiddleware<User extends object> implements NestMiddleware {
|
|
7
7
|
protected configProvider: ConfigProviderService;
|
|
8
8
|
protected moduleName: string;
|
|
9
|
-
protected tokenManager
|
|
10
|
-
protected usersService
|
|
11
|
-
constructor(configProvider: ConfigProviderService, moduleName: string, tokenManager
|
|
9
|
+
protected tokenManager?: IAMTokenManagerService<UserTokenEnityFields> | undefined;
|
|
10
|
+
protected usersService?: IAMUsersService<User> | undefined;
|
|
11
|
+
constructor(configProvider: ConfigProviderService, moduleName: string, tokenManager?: IAMTokenManagerService<UserTokenEnityFields> | undefined, usersService?: IAMUsersService<User> | undefined);
|
|
12
12
|
use(req: RequestWithLocals<unknown>, res: Response, next: NextFunction): void;
|
|
13
13
|
}
|
|
@@ -20,13 +20,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
20
20
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
21
21
|
});
|
|
22
22
|
};
|
|
23
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
24
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
25
|
+
};
|
|
23
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
27
|
exports.HTTPAuthenticationMiddleware = void 0;
|
|
28
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
25
29
|
const common_1 = require("@nestjs/common");
|
|
26
30
|
const core_1 = require("@node-c/core");
|
|
27
31
|
const domain_iam_1 = require("@node-c/domain-iam");
|
|
28
|
-
const general_tools_1 = require("@ramster/general-tools");
|
|
29
32
|
const definitions_1 = require("../common/definitions");
|
|
33
|
+
const utils_1 = require("../common/utils");
|
|
30
34
|
let HTTPAuthenticationMiddleware = class HTTPAuthenticationMiddleware {
|
|
31
35
|
constructor(configProvider, moduleName, tokenManager, usersService) {
|
|
32
36
|
this.configProvider = configProvider;
|
|
@@ -36,8 +40,9 @@ let HTTPAuthenticationMiddleware = class HTTPAuthenticationMiddleware {
|
|
|
36
40
|
}
|
|
37
41
|
use(req, res, next) {
|
|
38
42
|
(() => __awaiter(this, void 0, void 0, function* () {
|
|
39
|
-
var _a;
|
|
40
|
-
const { anonymousAccessRoutes } = this.configProvider.config.api[this.moduleName];
|
|
43
|
+
var _a, _b, _c;
|
|
44
|
+
const { anonymousAccessRoutes, apiKey, apiSecret, apiSecretAlgorithm } = this.configProvider.config.api[this.moduleName];
|
|
45
|
+
const requestMethod = req.method.toLowerCase();
|
|
41
46
|
if (!req.locals) {
|
|
42
47
|
req.locals = {};
|
|
43
48
|
}
|
|
@@ -45,8 +50,8 @@ let HTTPAuthenticationMiddleware = class HTTPAuthenticationMiddleware {
|
|
|
45
50
|
const originalUrl = req.originalUrl.split('?')[0];
|
|
46
51
|
let isAnonymous = false;
|
|
47
52
|
for (const route in anonymousAccessRoutes) {
|
|
48
|
-
if ((0,
|
|
49
|
-
anonymousAccessRoutes[route].find(method => method ===
|
|
53
|
+
if ((0, utils_1.checkRoutes)(originalUrl, [route]) &&
|
|
54
|
+
anonymousAccessRoutes[route].find(method => method === requestMethod)) {
|
|
50
55
|
isAnonymous = true;
|
|
51
56
|
break;
|
|
52
57
|
}
|
|
@@ -58,6 +63,45 @@ let HTTPAuthenticationMiddleware = class HTTPAuthenticationMiddleware {
|
|
|
58
63
|
}
|
|
59
64
|
}
|
|
60
65
|
const { tokenManager, usersService } = this;
|
|
66
|
+
if (apiKey) {
|
|
67
|
+
const [apiKeyFromHeader, requestSignature] = ((_b = (_a = req.headers.authorization) === null || _a === void 0 ? void 0 : _a.replace(/^ApiKey\s/, '')) === null || _b === void 0 ? void 0 : _b.split(' ')) || [];
|
|
68
|
+
if (apiKey !== apiKeyFromHeader) {
|
|
69
|
+
console.error(`${(apiKeyFromHeader === null || apiKeyFromHeader === void 0 ? void 0 : apiKeyFromHeader.length) ? 'Invalid' : 'Missing'} api key in the authorization header.`);
|
|
70
|
+
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
71
|
+
}
|
|
72
|
+
if (apiSecret && apiSecretAlgorithm) {
|
|
73
|
+
if (!requestSignature) {
|
|
74
|
+
console.error('Missing request signature in the authorization header.');
|
|
75
|
+
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
76
|
+
}
|
|
77
|
+
let signatureContent = '';
|
|
78
|
+
if (requestMethod === 'get' && req.query && Object.keys(req.query).length) {
|
|
79
|
+
signatureContent = JSON.stringify(req.query);
|
|
80
|
+
}
|
|
81
|
+
else if ((requestMethod === 'patch' || requestMethod === 'post' || requestMethod === 'put') &&
|
|
82
|
+
req.body &&
|
|
83
|
+
Object.keys(req.body).length) {
|
|
84
|
+
signatureContent = JSON.stringify(req.body);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
signatureContent = req.originalUrl.split('?')[0];
|
|
88
|
+
}
|
|
89
|
+
const calcualtedSignature = crypto_1.default
|
|
90
|
+
.createHmac(apiSecretAlgorithm, apiSecret)
|
|
91
|
+
.update(signatureContent)
|
|
92
|
+
.digest('hex');
|
|
93
|
+
if (calcualtedSignature !== requestSignature) {
|
|
94
|
+
console.error(`Invalid request signature in the authorization header. Expected: ${calcualtedSignature}. Provided: ${requestSignature}`);
|
|
95
|
+
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
next();
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
else if (!tokenManager) {
|
|
102
|
+
console.error('Missing api key in the configuration and no tokenManager set up.');
|
|
103
|
+
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
104
|
+
}
|
|
61
105
|
let tokens = [];
|
|
62
106
|
let authToken = req.headers.authorization;
|
|
63
107
|
let authTokenIsNew = false;
|
|
@@ -82,7 +126,7 @@ let HTTPAuthenticationMiddleware = class HTTPAuthenticationMiddleware {
|
|
|
82
126
|
try {
|
|
83
127
|
const tokenRes = yield tokenManager.verifyAccessToken(authToken, {
|
|
84
128
|
deleteFromStoreIfExpired: true,
|
|
85
|
-
identifierDataField: 'userId',
|
|
129
|
+
identifierDataField: usersService ? 'userId' : undefined,
|
|
86
130
|
persistNewToken: true,
|
|
87
131
|
purgeStoreOnRenew: true,
|
|
88
132
|
refreshToken,
|
|
@@ -103,12 +147,14 @@ let HTTPAuthenticationMiddleware = class HTTPAuthenticationMiddleware {
|
|
|
103
147
|
res.cookie('sid', authToken);
|
|
104
148
|
}
|
|
105
149
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
150
|
+
if (usersService) {
|
|
151
|
+
const userId = (_c = tokenContent === null || tokenContent === void 0 ? void 0 : tokenContent.data) === null || _c === void 0 ? void 0 : _c.userId;
|
|
152
|
+
if (!userId) {
|
|
153
|
+
console.error('Missing userId in the tokenContent data.');
|
|
154
|
+
throw new common_1.HttpException('Unauthorized', common_1.HttpStatus.UNAUTHORIZED);
|
|
155
|
+
}
|
|
156
|
+
req.locals.user = yield usersService.getUserWithPermissionsData({ filters: { id: userId } });
|
|
110
157
|
}
|
|
111
|
-
req.locals.user = yield usersService.getUserWithPermissionsData({ filters: { id: userId } });
|
|
112
158
|
next();
|
|
113
159
|
}))().then(() => true, err => {
|
|
114
160
|
console.error(err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.middlewares.authentication.js","sourceRoot":"","sources":["../../src/middlewares/http.middlewares.authentication.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"http.middlewares.authentication.js","sourceRoot":"","sources":["../../src/middlewares/http.middlewares.authentication.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAA4B;AAE5B,2CAA+F;AAE/F,uCAAuE;AACvE,mDAAwH;AAIxH,uDAAqE;AACrE,2CAA8C;AAGvC,IAAM,4BAA4B,GAAlC,MAAM,4BAA4B;IACvC,YAEY,cAAqC,EAGrC,UAAkB,EAGlB,YAA2D,EAG3D,YAAoC;QATpC,mBAAc,GAAd,cAAc,CAAuB;QAGrC,eAAU,GAAV,UAAU,CAAQ;QAGlB,iBAAY,GAAZ,YAAY,CAA+C;QAG3D,iBAAY,GAAZ,YAAY,CAAwB;IAC7C,CAAC;IAEJ,GAAG,CAAC,GAA+B,EAAE,GAAa,EAAE,IAAkB;QACpE,CAAC,GAAS,EAAE;;YACV,MAAM,E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AAZ,YAAY,CAAE,IAAI,0CAAE,MAAM,CAAC;gBAC1C,IAAI,CAAC,MAAM,EAAE,CAAC;oBACZ,OAAO,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAC;oBAC1D,MAAM,IAAI,sBAAa,CAAC,cAAc,EAAE,mBAAU,CAAC,YAAY,CAAC,CAAC;gBACnE,CAAC;gBACD,GAAG,CAAC,MAAO,CAAC,IAAI,GAAG,MAAM,YAAY,CAAC,0BAA0B,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;YAChG,CAAC;YACD,IAAI,EAAE,CAAC;QACT,CAAC,CAAA,CAAC,EAAE,CAAC,IAAI,CACP,GAAG,EAAE,CAAC,IAAI,EACV,GAAG,CAAC,EAAE;YACJ,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACnB,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,mBAAU,CAAC,qBAAqB,CAAC,CAAC,GAAG,EAAE,CAAC;QAC5E,CAAC,CACF,CAAC;IACJ,CAAC;CACF,CAAA;AAhJY,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,UAMtB,mCAAsB;QAGtB,4BAAe;GAZ/B,4BAA4B,CAgJxC"}
|
|
@@ -28,9 +28,9 @@ let HTTPCORSMiddleware = class HTTPCORSMiddleware {
|
|
|
28
28
|
res.set('Access-Control-Allow-Origin', origin);
|
|
29
29
|
}
|
|
30
30
|
res.set('Access-Control-Allow-Headers', 'accept,accept-encoding,accept-language,authorization,connection,content-type,host,origin,referer,user-agent');
|
|
31
|
-
res.set('Access-Control-Expose-Headers', 'Authorization');
|
|
32
31
|
res.set('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,PATCH,DELETE');
|
|
33
32
|
res.set('Access-Control-Allow-Credentials', 'true');
|
|
33
|
+
res.set('Access-Control-Expose-Headers', 'Authorization');
|
|
34
34
|
if (req.method.toLowerCase() === 'options') {
|
|
35
35
|
res.status(common_1.HttpStatus.OK).end();
|
|
36
36
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.middlewares.cors.js","sourceRoot":"","sources":["../../src/middlewares/http.middlewares.cors.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAgF;AAEhF,uCAAuE;AAGvE,uDAAqE;AAG9D,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAC7B,YAEY,cAAqC,EAGrC,UAAkB;QAHlB,mBAAc,GAAd,cAAc,CAAuB;QAGrC,eAAU,GAAV,UAAU,CAAQ;IAC3B,CAAC;IAEJ,GAAG,CAAC,GAA+B,EAAE,GAAa,EAAE,IAAkB;QACpE,MAAM,cAAc,GAAI,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,GAAI,CAAC,IAAI,CAAC,UAAU,CAAsB,CAAC,cAAc,CAAC;QAC7G,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,MAAgB,CAAC;QAC5C,IAAI,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YACrC,GAAG,CAAC,GAAG,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;QACjD,CAAC;QACD,GAAG,CAAC,GAAG,CACL,8BAA8B,EAC9B,6GAA6G,CAC9G,CAAC;QACF,GAAG,CAAC,GAAG,CAAC
|
|
1
|
+
{"version":3,"file":"http.middlewares.cors.js","sourceRoot":"","sources":["../../src/middlewares/http.middlewares.cors.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAA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|
@@ -18,9 +18,11 @@ var HTTPAPIModule_1;
|
|
|
18
18
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
19
19
|
exports.HTTPAPIModule = void 0;
|
|
20
20
|
const common_1 = require("@nestjs/common");
|
|
21
|
-
const core_1 = require("@
|
|
21
|
+
const core_1 = require("@nestjs/core");
|
|
22
|
+
const core_2 = require("@node-c/core");
|
|
22
23
|
const cookie_parser_1 = __importDefault(require("cookie-parser"));
|
|
23
24
|
const express_1 = __importDefault(require("express"));
|
|
25
|
+
const morgan_1 = __importDefault(require("morgan"));
|
|
24
26
|
const definitions_1 = require("../common/definitions");
|
|
25
27
|
const exceptionFilters_1 = require("../exceptionFilters");
|
|
26
28
|
const interceptors_1 = require("../interceptors");
|
|
@@ -34,6 +36,9 @@ let HTTPAPIModule = HTTPAPIModule_1 = class HTTPAPIModule {
|
|
|
34
36
|
consumer.apply(express_1.default.urlencoded({ verify: HTTPAPIModule_1.rawBodyBuffer, extended: true })).forRoutes('*');
|
|
35
37
|
consumer.apply(express_1.default.json({ verify: HTTPAPIModule_1.rawBodyBuffer })).forRoutes('*');
|
|
36
38
|
consumer.apply((0, cookie_parser_1.default)()).forRoutes('*');
|
|
39
|
+
consumer
|
|
40
|
+
.apply((0, morgan_1.default)(`[${this.moduleName}]: :method :url :status :res[content-length] - :response-time ms`))
|
|
41
|
+
.forRoutes('*');
|
|
37
42
|
consumer.apply(middlewares_1.HTTPCORSMiddleware).forRoutes('*');
|
|
38
43
|
consumer.apply(middlewares_1.HTTPAuthenticationMiddleware).forRoutes('*');
|
|
39
44
|
}
|
|
@@ -45,11 +50,17 @@ let HTTPAPIModule = HTTPAPIModule_1 = class HTTPAPIModule {
|
|
|
45
50
|
static register(options) {
|
|
46
51
|
const { folderData, imports: additionalImports, moduleClass } = options;
|
|
47
52
|
const { atEnd: importsAtEnd, atStart: importsAtStart } = additionalImports || {};
|
|
48
|
-
const { controllers, services } = (0,
|
|
53
|
+
const { controllers, services } = (0, core_2.loadDynamicModules)(folderData);
|
|
49
54
|
return {
|
|
50
55
|
module: moduleClass,
|
|
51
56
|
imports: [...(importsAtStart || []), ...(importsAtEnd || [])],
|
|
52
57
|
providers: [
|
|
58
|
+
{
|
|
59
|
+
provide: core_1.APP_PIPE,
|
|
60
|
+
useValue: new common_1.ValidationPipe({
|
|
61
|
+
whitelist: true
|
|
62
|
+
})
|
|
63
|
+
},
|
|
53
64
|
{
|
|
54
65
|
provide: definitions_1.Constants.API_MODULE_NAME,
|
|
55
66
|
useValue: options.moduleName
|
|
@@ -77,6 +88,6 @@ let HTTPAPIModule = HTTPAPIModule_1 = class HTTPAPIModule {
|
|
|
77
88
|
exports.HTTPAPIModule = HTTPAPIModule;
|
|
78
89
|
exports.HTTPAPIModule = HTTPAPIModule = HTTPAPIModule_1 = __decorate([
|
|
79
90
|
__param(1, (0, common_1.Inject)(definitions_1.Constants.API_MODULE_NAME)),
|
|
80
|
-
__metadata("design:paramtypes", [
|
|
91
|
+
__metadata("design:paramtypes", [core_2.ConfigProviderService, String])
|
|
81
92
|
], HTTPAPIModule);
|
|
82
93
|
//# sourceMappingURL=http.api.module.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.api.module.js","sourceRoot":"","sources":["../../src/module/http.api.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,
|
|
1
|
+
{"version":3,"file":"http.api.module.js","sourceRoot":"","sources":["../../src/module/http.api.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,2CAA2G;AAC3G,uCAAwC;AAExC,uCAAyE;AAEzE,kEAAyC;AACzC,sDAA4C;AAC5C,oDAA4B;AAI5B,uDAAqE;AACrE,0DAA0D;AAC1D,kDAAqF;AACrF,gDAAkF;AAElF,IAAa,aAAa,qBAA1B,MAAa,aAAa;IACxB,YAEY,cAAqC,EAGrC,UAAkB;QAHlB,mBAAc,GAAd,cAAc,CAAuB;QAGrC,eAAU,GAAV,UAAU,CAAQ;IAC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
2
|
"name": "@node-c/api-http",
|
|
3
|
-
"version": "1.0.0-
|
|
3
|
+
"version": "1.0.0-alpha40",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"build": "tsc -p tsconfig.build.json",
|
|
8
|
+
"build:clean": "rm -rf dist/* && rm -f *.tsbuildinfo && npm run build",
|
|
8
9
|
"check-types": "tsc -p tsconfig.build.json --noEmit",
|
|
9
10
|
"dev": "tsc -p tsconfig.build.json --watch",
|
|
10
|
-
"publish-package": "
|
|
11
|
+
"publish-package": "npm run build:clean && npm publish --access public",
|
|
11
12
|
"test": "vitest --config src/vitest.config.ts",
|
|
12
13
|
"test:coverage": "vitest --config src/vitest.config.ts --coverage"
|
|
13
14
|
},
|
|
14
15
|
"dependencies": {
|
|
15
16
|
"@nestjs/common": "^10.4.12",
|
|
16
|
-
"@ramster/general-tools": "^2.3.0",
|
|
17
17
|
"cookie-parser": "^1.4.7",
|
|
18
18
|
"express": "^4.21.2",
|
|
19
|
+
"lodash": "^4.17.21",
|
|
19
20
|
"rxjs": "^7.8.1"
|
|
20
21
|
},
|
|
21
22
|
"devDependencies": {
|
|
22
23
|
"@types/cookie-parser": "^1.4.8",
|
|
23
|
-
"@types/express": "^5.0.0"
|
|
24
|
+
"@types/express": "^5.0.0",
|
|
25
|
+
"@types/lodash": "^4.17.19"
|
|
24
26
|
},
|
|
25
27
|
"peerDependencies": {
|
|
26
|
-
"@node-c/core": "^1.0.0-
|
|
27
|
-
"@node-c/domain-iam": "^1.0.0-
|
|
28
|
+
"@node-c/core": "^1.0.0-alpha40",
|
|
29
|
+
"@node-c/domain-iam": "^1.0.0-alpha40"
|
|
28
30
|
}
|
|
29
31
|
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
export enum Constants {
|
|
2
|
-
// eslint-disable-next-line no-unused-vars
|
|
3
|
-
API_MODULE_AUTHORIZATION_SERVICE = 'API_MODULE_AUTHORIZATION_SERVICE',
|
|
4
|
-
// eslint-disable-next-line no-unused-vars
|
|
5
|
-
API_MODULE_NAME = 'API_MODULE_NAME',
|
|
6
|
-
// eslint-disable-next-line no-unused-vars
|
|
7
|
-
AUTHENTICATION_MIDDLEWARE_TOKEN_MANAGER_SERVICE = 'AUTHENTICATION_MIDDLEWARE_TOKEN_MANAGER_SERVICE',
|
|
8
|
-
// eslint-disable-next-line no-unused-vars
|
|
9
|
-
AUTHENTICATION_MIDDLEWARE_USERS_SERVICE = 'AUTHENTICATION_MIDDLEWARE_USERS_SERVICE',
|
|
10
|
-
// eslint-disable-next-line no-unused-vars
|
|
11
|
-
AUTHORIZATION_INTERCEPTOR = 'AUTHORIZATION_INTERCEPTOR',
|
|
12
|
-
// eslint-disable-next-line no-unused-vars
|
|
13
|
-
ERROR_INTERCEPTOR = 'ERROR_INTERCEPTOR',
|
|
14
|
-
// eslint-disable-next-line no-unused-vars
|
|
15
|
-
HTTP_EXCEPTION_FILTER = 'HTTP_EXCEPTION_FILTER'
|
|
16
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { GenericObject } from '@node-c/core';
|
|
2
|
-
|
|
3
|
-
export class ServerError implements Error {
|
|
4
|
-
data: { statusCode: number } | GenericObject;
|
|
5
|
-
message: string;
|
|
6
|
-
name: string;
|
|
7
|
-
|
|
8
|
-
constructor(message: string, data?: GenericObject) {
|
|
9
|
-
this.message = message;
|
|
10
|
-
this.name = 'ServerError';
|
|
11
|
-
this.data = data || {};
|
|
12
|
-
}
|
|
13
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
|
|
2
|
-
import { Response } from 'express';
|
|
3
|
-
|
|
4
|
-
// The purpose of the class is to handle HttpExceptions that are not caught by the HTTPErrorInterceptor.
|
|
5
|
-
@Catch(HttpException)
|
|
6
|
-
export class HttpExceptionFilter implements ExceptionFilter {
|
|
7
|
-
catch(exception: HttpException, host: ArgumentsHost): void {
|
|
8
|
-
const ctx = host.switchToHttp();
|
|
9
|
-
const response = ctx.getResponse<Response>();
|
|
10
|
-
const status = exception.getStatus();
|
|
11
|
-
// else if (error instanceof BadRequestException) {
|
|
12
|
-
// const { statusCode, message: errorText } = error.getResponse() as unknown
|
|
13
|
-
// status = statusCode
|
|
14
|
-
// message = errorText || message
|
|
15
|
-
// }
|
|
16
|
-
response.status(status).json({
|
|
17
|
-
statusCode: status,
|
|
18
|
-
message: exception.message
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './http.exceptionFilters.httpException';
|
package/src/index.ts
DELETED
|
@@ -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,50 +0,0 @@
|
|
|
1
|
-
import { CallHandler, ExecutionContext, HttpException, Injectable, NestInterceptor } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
import { ApplicationError } from '@node-c/core';
|
|
4
|
-
|
|
5
|
-
import { Observable } from 'rxjs';
|
|
6
|
-
import { catchError } from 'rxjs/operators';
|
|
7
|
-
|
|
8
|
-
import { ServerError } from '../common/definitions/common.errors';
|
|
9
|
-
|
|
10
|
-
@Injectable()
|
|
11
|
-
export class HTTPErrorInterceptor implements NestInterceptor {
|
|
12
|
-
intercept(_context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
13
|
-
return next.handle().pipe(
|
|
14
|
-
catchError(error => {
|
|
15
|
-
console.error(error);
|
|
16
|
-
let message = 'An error has occurred.';
|
|
17
|
-
let status = 500;
|
|
18
|
-
if (error instanceof ApplicationError || error instanceof ServerError) {
|
|
19
|
-
if (error.message) {
|
|
20
|
-
message = error.message;
|
|
21
|
-
}
|
|
22
|
-
if (error.data) {
|
|
23
|
-
if ('errorCode' in error.data) {
|
|
24
|
-
status = error.data.errorCode as number;
|
|
25
|
-
} else if ('statusCode' in error.data) {
|
|
26
|
-
status = error.data.statusCode as number;
|
|
27
|
-
} else {
|
|
28
|
-
status = 400;
|
|
29
|
-
}
|
|
30
|
-
} else {
|
|
31
|
-
status = 400;
|
|
32
|
-
}
|
|
33
|
-
} else if (error.response) {
|
|
34
|
-
const { response } = error;
|
|
35
|
-
if (response.statusCode) {
|
|
36
|
-
status = response.statusCode;
|
|
37
|
-
}
|
|
38
|
-
if (response.message) {
|
|
39
|
-
message = response.message;
|
|
40
|
-
}
|
|
41
|
-
} else if (error instanceof Error) {
|
|
42
|
-
if (error.message) {
|
|
43
|
-
message = error.message;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
throw new HttpException({ message, statusCode: status }, status);
|
|
47
|
-
})
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
@@ -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
|
-
}
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { HttpStatus, Inject, Injectable, NestMiddleware } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
import { AppConfigAPIHTTP, ConfigProviderService } from '@node-c/core';
|
|
4
|
-
import { NextFunction, Response } from 'express';
|
|
5
|
-
|
|
6
|
-
import { Constants, RequestWithLocals } from '../common/definitions';
|
|
7
|
-
|
|
8
|
-
@Injectable()
|
|
9
|
-
export class HTTPCORSMiddleware implements NestMiddleware {
|
|
10
|
-
constructor(
|
|
11
|
-
// eslint-disable-next-line no-unused-vars
|
|
12
|
-
protected configProvider: ConfigProviderService,
|
|
13
|
-
@Inject(Constants.API_MODULE_NAME)
|
|
14
|
-
// eslint-disable-next-line no-unused-vars
|
|
15
|
-
protected moduleName: string
|
|
16
|
-
) {}
|
|
17
|
-
|
|
18
|
-
use(req: RequestWithLocals<unknown>, res: Response, next: NextFunction): void {
|
|
19
|
-
const allowedOrigins = (this.configProvider.config.api![this.moduleName] as AppConfigAPIHTTP).allowedOrigins;
|
|
20
|
-
const origin = req.headers.origin as string;
|
|
21
|
-
if (allowedOrigins?.includes(origin)) {
|
|
22
|
-
res.set('Access-Control-Allow-Origin', origin);
|
|
23
|
-
}
|
|
24
|
-
res.set(
|
|
25
|
-
'Access-Control-Allow-Headers',
|
|
26
|
-
'accept,accept-encoding,accept-language,authorization,connection,content-type,host,origin,referer,user-agent'
|
|
27
|
-
);
|
|
28
|
-
res.set('Access-Control-Expose-Headers', 'Authorization');
|
|
29
|
-
res.set('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,PATCH,DELETE');
|
|
30
|
-
res.set('Access-Control-Allow-Credentials', 'true');
|
|
31
|
-
if (req.method.toLowerCase() === 'options') {
|
|
32
|
-
res.status(HttpStatus.OK).end();
|
|
33
|
-
return;
|
|
34
|
-
}
|
|
35
|
-
next();
|
|
36
|
-
}
|
|
37
|
-
}
|
package/src/middlewares/index.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { ModuleMetadata } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
import { GenericObject } from '@node-c/core';
|
|
4
|
-
|
|
5
|
-
export interface HTTPAPIModuleOptions {
|
|
6
|
-
controllers?: ModuleMetadata['controllers'];
|
|
7
|
-
exports?: ModuleMetadata['exports'];
|
|
8
|
-
folderData: GenericObject<unknown>;
|
|
9
|
-
imports?: {
|
|
10
|
-
atEnd?: ModuleMetadata['imports'];
|
|
11
|
-
atStart?: ModuleMetadata['imports'];
|
|
12
|
-
};
|
|
13
|
-
moduleClass: unknown;
|
|
14
|
-
moduleName: string;
|
|
15
|
-
providers?: ModuleMetadata['providers'];
|
|
16
|
-
}
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import { DynamicModule, Inject, MiddlewareConsumer, ModuleMetadata } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
import { ConfigProviderService, loadDynamicModules } from '@node-c/core';
|
|
4
|
-
|
|
5
|
-
import cookieParser from 'cookie-parser';
|
|
6
|
-
import express, { Response } from 'express';
|
|
7
|
-
|
|
8
|
-
import { HTTPAPIModuleOptions } from './http.api.module.definitions';
|
|
9
|
-
|
|
10
|
-
import { Constants, RequestWithLocals } from '../common/definitions';
|
|
11
|
-
import { HttpExceptionFilter } from '../exceptionFilters';
|
|
12
|
-
import { HTTPAuthorizationInterceptor, HTTPErrorInterceptor } from '../interceptors';
|
|
13
|
-
import { HTTPAuthenticationMiddleware, HTTPCORSMiddleware } from '../middlewares';
|
|
14
|
-
|
|
15
|
-
export class HTTPAPIModule {
|
|
16
|
-
constructor(
|
|
17
|
-
// eslint-disable-next-line no-unused-vars
|
|
18
|
-
protected configProvider: ConfigProviderService,
|
|
19
|
-
@Inject(Constants.API_MODULE_NAME)
|
|
20
|
-
// eslint-disable-next-line no-unused-vars
|
|
21
|
-
protected moduleName: string
|
|
22
|
-
) {}
|
|
23
|
-
|
|
24
|
-
configure(consumer: MiddlewareConsumer): void {
|
|
25
|
-
consumer.apply(express.urlencoded({ verify: HTTPAPIModule.rawBodyBuffer, extended: true })).forRoutes('*');
|
|
26
|
-
consumer.apply(express.json({ verify: HTTPAPIModule.rawBodyBuffer })).forRoutes('*');
|
|
27
|
-
consumer.apply(cookieParser()).forRoutes('*');
|
|
28
|
-
consumer.apply(HTTPCORSMiddleware).forRoutes('*');
|
|
29
|
-
consumer.apply(HTTPAuthenticationMiddleware).forRoutes('*');
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
static rawBodyBuffer(req: RequestWithLocals<unknown>, _res: Response, buffer: Buffer): void {
|
|
33
|
-
if (buffer && buffer.length) {
|
|
34
|
-
req.rawBody = buffer.toString();
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
static register(options: HTTPAPIModuleOptions): DynamicModule {
|
|
39
|
-
const { folderData, imports: additionalImports, moduleClass } = options;
|
|
40
|
-
const { atEnd: importsAtEnd, atStart: importsAtStart } = additionalImports || {};
|
|
41
|
-
const { controllers, services } = loadDynamicModules(folderData);
|
|
42
|
-
return {
|
|
43
|
-
module: moduleClass as DynamicModule['module'],
|
|
44
|
-
imports: [...(importsAtStart || []), ...(importsAtEnd || [])],
|
|
45
|
-
providers: [
|
|
46
|
-
{
|
|
47
|
-
provide: Constants.API_MODULE_NAME,
|
|
48
|
-
useValue: options.moduleName
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
provide: Constants.AUTHORIZATION_INTERCEPTOR,
|
|
52
|
-
useClass: HTTPAuthorizationInterceptor
|
|
53
|
-
},
|
|
54
|
-
{
|
|
55
|
-
provide: Constants.ERROR_INTERCEPTOR,
|
|
56
|
-
useClass: HTTPErrorInterceptor
|
|
57
|
-
},
|
|
58
|
-
{
|
|
59
|
-
provide: Constants.HTTP_EXCEPTION_FILTER,
|
|
60
|
-
useClass: HttpExceptionFilter
|
|
61
|
-
},
|
|
62
|
-
...(options.providers || []),
|
|
63
|
-
...(services || [])
|
|
64
|
-
],
|
|
65
|
-
controllers: [...(controllers || []), ...(options.controllers || [])] as unknown as ModuleMetadata['controllers'],
|
|
66
|
-
exports: [...(services || []), ...(options.exports || [])]
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
}
|
package/src/module/index.ts
DELETED