@jpbs/common 1.0.12 → 1.1.0

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.
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BadRequestError = void 0;
4
+ const http_status_codes_1 = require("http-status-codes");
5
+ const custom_error_1 = require("./custom-error");
6
+ class BadRequestError extends custom_error_1.CustomError {
7
+ constructor(message = "Bad request") {
8
+ super(message);
9
+ this.message = message;
10
+ this.statusCode = http_status_codes_1.StatusCodes.BAD_REQUEST;
11
+ Object.setPrototypeOf(this, BadRequestError.prototype);
12
+ }
13
+ serializeErrors() {
14
+ return [{ message: this.message }];
15
+ }
16
+ }
17
+ exports.BadRequestError = BadRequestError;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CustomError = void 0;
4
+ class CustomError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ Object.setPrototypeOf(this, CustomError.prototype);
8
+ }
9
+ }
10
+ exports.CustomError = CustomError;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EmailError = void 0;
4
+ const http_status_codes_1 = require("http-status-codes");
5
+ const custom_error_1 = require("./custom-error");
6
+ class EmailError extends custom_error_1.CustomError {
7
+ constructor(message) {
8
+ super(message);
9
+ this.statusCode = http_status_codes_1.StatusCodes.INTERNAL_SERVER_ERROR;
10
+ Object.setPrototypeOf(this, EmailError.prototype);
11
+ }
12
+ serializeErrors() {
13
+ return [{ message: this.message }];
14
+ }
15
+ }
16
+ exports.EmailError = EmailError;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NotAuthorizedError = void 0;
4
+ const http_status_codes_1 = require("http-status-codes");
5
+ const custom_error_1 = require("./custom-error");
6
+ class NotAuthorizedError extends custom_error_1.CustomError {
7
+ constructor(message = "Not authorized") {
8
+ super(message);
9
+ this.message = message;
10
+ this.statusCode = http_status_codes_1.StatusCodes.UNAUTHORIZED;
11
+ Object.setPrototypeOf(this, NotAuthorizedError.prototype);
12
+ }
13
+ serializeErrors() {
14
+ return [{ message: this.message }];
15
+ }
16
+ }
17
+ exports.NotAuthorizedError = NotAuthorizedError;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NotFoundError = void 0;
4
+ const http_status_codes_1 = require("http-status-codes");
5
+ const custom_error_1 = require("./custom-error");
6
+ class NotFoundError extends custom_error_1.CustomError {
7
+ constructor(message = "Resource not found") {
8
+ super(message);
9
+ this.message = message;
10
+ this.statusCode = http_status_codes_1.StatusCodes.NOT_FOUND;
11
+ Object.setPrototypeOf(this, NotFoundError.prototype);
12
+ }
13
+ serializeErrors() {
14
+ return [{ message: this.message }];
15
+ }
16
+ }
17
+ exports.NotFoundError = NotFoundError;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequestValidationError = void 0;
4
+ const custom_error_1 = require("./custom-error");
5
+ const http_status_codes_1 = require("http-status-codes");
6
+ class RequestValidationError extends custom_error_1.CustomError {
7
+ constructor(errors) {
8
+ super('Invalid request parameters');
9
+ this.errors = errors;
10
+ this.statusCode = http_status_codes_1.StatusCodes.BAD_REQUEST;
11
+ Object.setPrototypeOf(this, RequestValidationError.prototype);
12
+ }
13
+ serializeErrors() {
14
+ return this.errors.map(err => {
15
+ if (err.type === 'field') {
16
+ return { message: err.msg };
17
+ }
18
+ return { message: err.msg };
19
+ });
20
+ }
21
+ }
22
+ exports.RequestValidationError = RequestValidationError;
package/build/index.js ADDED
@@ -0,0 +1,26 @@
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("./errors/custom-error"), exports);
18
+ __exportStar(require("./errors/notfound-error"), exports);
19
+ __exportStar(require("./errors/notauthorized-error"), exports);
20
+ __exportStar(require("./errors/bad-request-error"), exports);
21
+ __exportStar(require("./errors/request-validation"), exports);
22
+ __exportStar(require("./middlewares/asyncHandler"), exports);
23
+ __exportStar(require("./middlewares/authProtect"), exports);
24
+ __exportStar(require("./middlewares/errorHandler"), exports);
25
+ __exportStar(require("./middlewares/validateRequest"), exports);
26
+ __exportStar(require("./middlewares/verifyGatewayToken"), exports);
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.asyncHandler = void 0;
4
+ const asyncHandler = (fn) => (req, res, next) => {
5
+ Promise.resolve(fn(req, res, next)).catch(next);
6
+ };
7
+ exports.asyncHandler = asyncHandler;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.authenticationGuard = exports.Role = void 0;
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const http_status_codes_1 = require("http-status-codes");
9
+ var Role;
10
+ (function (Role) {
11
+ Role["ADMINISTRATOR"] = "Administrator";
12
+ Role["USER"] = "User";
13
+ })(Role || (exports.Role = Role = {}));
14
+ const authenticationGuard = (jwtSecret) => (req, res, next) => {
15
+ try {
16
+ const token = req.cookies.auth_token;
17
+ if (!token) {
18
+ res.status(http_status_codes_1.StatusCodes.UNAUTHORIZED).json({ error: "Unauthorized" });
19
+ return;
20
+ }
21
+ const decoded = jsonwebtoken_1.default.verify(token, jwtSecret);
22
+ req.currentUser = decoded;
23
+ next();
24
+ }
25
+ catch (error) {
26
+ res.status(http_status_codes_1.StatusCodes.UNAUTHORIZED).json({ error: "Invalid or expired token" });
27
+ }
28
+ };
29
+ exports.authenticationGuard = authenticationGuard;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorHandler = void 0;
4
+ const custom_error_1 = require("../errors/custom-error");
5
+ const http_status_codes_1 = require("http-status-codes");
6
+ const errorHandler = (err, _req, res, _next) => {
7
+ if (err instanceof custom_error_1.CustomError) {
8
+ res.status(err.statusCode).send({ errors: err.serializeErrors() });
9
+ return;
10
+ }
11
+ res.status(http_status_codes_1.StatusCodes.BAD_REQUEST).send({ errors: [{ message: 'Something went wrong' }] });
12
+ };
13
+ exports.errorHandler = errorHandler;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateRequest = exports.validateUpdateUser = exports.validateLogin = exports.validateSignup = void 0;
4
+ const express_validator_1 = require("express-validator");
5
+ const request_validation_1 = require("../errors/request-validation");
6
+ exports.validateSignup = [
7
+ (0, express_validator_1.body)("username").isLength({ min: 3, max: 18 }).withMessage("Username must have between 3 and 18 characters long"),
8
+ (0, express_validator_1.body)("email").isEmail().withMessage("Invalid email format"),
9
+ (0, express_validator_1.body)("password").isLength({ min: 6, max: 18 }).withMessage("Password must have between 6 and 18 characters long"),
10
+ (0, express_validator_1.body)("confirmPassword").custom((value, { req }) => value === req.body.password).withMessage("Passwords do not match")
11
+ ];
12
+ exports.validateLogin = [
13
+ (0, express_validator_1.body)("email").isEmail().withMessage("Invalid email format"),
14
+ (0, express_validator_1.body)("password").notEmpty().withMessage("Password is required")
15
+ ];
16
+ exports.validateUpdateUser = [
17
+ (0, express_validator_1.body)("username").isLength({ min: 3, max: 18 }).withMessage("Username must have between 3 and 18 characters long"),
18
+ (0, express_validator_1.body)("email").isEmail().withMessage("Invalid email format"),
19
+ (0, express_validator_1.body)("role").isIn(["User", "Administrator"]).withMessage("Role must be either 'User' or 'Administrator'")
20
+ ];
21
+ const validateRequest = (req, _res, next) => {
22
+ const errors = (0, express_validator_1.validationResult)(req);
23
+ if (!errors.isEmpty()) {
24
+ throw new request_validation_1.RequestValidationError(errors.array());
25
+ }
26
+ next();
27
+ };
28
+ exports.validateRequest = validateRequest;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.verifyGatewayToken = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const notauthorized_error_1 = require("../errors/notauthorized-error");
9
+ const verifySignature = (data, secret, timestamp, receivedSignature) => {
10
+ const expectedSignature = crypto_1.default.createHmac("sha256", secret).update(`${data}.${timestamp}`).digest("hex");
11
+ return expectedSignature === receivedSignature;
12
+ };
13
+ const verifyGatewayToken = (gatewaySecret) => (req, _res, next) => {
14
+ const timestamp = req.headers["x-api-timestamp"];
15
+ const signature = req.headers["x-api-signature"];
16
+ if (!timestamp || !signature) {
17
+ throw new notauthorized_error_1.NotAuthorizedError("Unauthorized request source: Missing Headers");
18
+ }
19
+ const requestTime = parseInt(timestamp, 10);
20
+ const currentTime = Date.now();
21
+ if (Math.abs(currentTime - requestTime) > 2 * 60 * 1000) {
22
+ throw new notauthorized_error_1.NotAuthorizedError("Unauthorized request source: Expired Request");
23
+ }
24
+ if (!verifySignature(JSON.stringify(req.body), gatewaySecret, timestamp, signature)) {
25
+ throw new notauthorized_error_1.NotAuthorizedError("Unauthorized request source: Invalid Signature");
26
+ }
27
+ next();
28
+ };
29
+ exports.verifyGatewayToken = verifyGatewayToken;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jpbs/common",
3
- "version": "1.0.12",
3
+ "version": "1.1.0",
4
4
  "main": "./build/index.js",
5
5
  "types": "./build/index.d.ts",
6
6
  "files": [