From d97cbc3ad3c4e113792a2355ab0984b666bc8699 Mon Sep 17 00:00:00 2001 From: Ali Azmoodeh Date: Wed, 11 Jan 2023 21:27:35 +0330 Subject: [PATCH] Version 2.0.2 * Fixed problem in isPhoneNumber function when + is in phone number --- package.json | 2 +- src/util/Generate.ts | 104 +++++++++++++++++----------------- src/util/ReturnJson.ts | 58 +++++++++---------- src/util/Validation.ts | 124 ++++++++++++++++++++--------------------- 4 files changed, 144 insertions(+), 144 deletions(-) diff --git a/package.json b/package.json index 01fcdeb..14826f2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "social-network-server", - "version": "2.0.1", + "version": "2.0.2", "description": "A simple social network with socket.io and rest api in nest.js", "author": "Ali Azmoodeh Valadi", "private": true, diff --git a/src/util/Generate.ts b/src/util/Generate.ts index 67fb2e2..1dfb31a 100644 --- a/src/util/Generate.ts +++ b/src/util/Generate.ts @@ -1,5 +1,5 @@ import jwt from "jsonwebtoken"; -import { JWK, JWE } from "node-jose"; +import {JWK, JWE} from "node-jose"; import * as crypto from "crypto"; import * as dotenv from "dotenv"; import {JsonObject} from "./Types"; @@ -8,75 +8,75 @@ dotenv.config(); export default { - // Generates verification code E.g : 335496 - getVerificationCode(): number { - return Math.floor(100000 + Math.random() * 999999); - }, + // Generates verification code E.g : 335496 + getVerificationCode(): number { + return Math.floor(100000 + Math.random() * 999999); + }, - // Signs jwt - getJwtSign(payload: JsonObject, subject: number | string): string { - const SIGN_OPTIONS = { - subject: subject, - expiresIn: payload.expiresIn, - algorithm: "RS256" - }; + // Signs jwt + getJwtSign(payload: JsonObject, subject: number | string): string { + const SIGN_OPTIONS = { + subject: subject, + expiresIn: payload.expiresIn, + algorithm: "RS256" + }; - return jwt.sign(payload, process.env.PRAIVATE_KEY, SIGN_OPTIONS); - }, + return jwt.sign(payload, process.env.PRAIVATE_KEY, SIGN_OPTIONS); + }, - // The jwt encrypt with JWK library - async getJwtEncrypt(raw, format = "compact", contentAlg = "A256GCM", alg = "RSA-OAEP"): Promise { - let publicKey = await JWK.asKey(process.env.JWT_PUBLIC_KEY, "pem"); - const buffer = Buffer.from(JSON.stringify(raw)); + // The jwt encrypt with JWK library + async getJwtEncrypt(raw, format = "compact", contentAlg = "A256GCM", alg = "RSA-OAEP"): Promise { + let publicKey = await JWK.asKey(process.env.JWT_PUBLIC_KEY, "pem"); + const buffer = Buffer.from(JSON.stringify(raw)); - return await JWE.createEncrypt({ - format: format, - contentAlg: contentAlg, - fields: { - alg: alg - } - }, publicKey).update(buffer).final(); - }, + return await JWE.createEncrypt({ + format: format, + contentAlg: contentAlg, + fields: { + alg: alg + } + }, publicKey).update(buffer).final(); + }, - getHashData(data: string, salt: string | number): string { - let hash = crypto.pbkdf2Sync(data, salt.toString(), - 1000, 64, `sha512`).toString(`hex`); + getHashData(data: string, salt: string | number): string { + let hash = crypto.pbkdf2Sync(data, salt.toString(), + 1000, 64, `sha512`).toString(`hex`); - return hash.trim(); - }, + return hash.trim(); + }, - getRandomHash(randomHashSize: number): string { - const ARRAY_OF_RANDOM_NUMBER = crypto.randomBytes(randomHashSize); + getRandomHash(randomHashSize: number): string { + const ARRAY_OF_RANDOM_NUMBER = crypto.randomBytes(randomHashSize); - let formatValidString = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", - chars = formatValidString.repeat(5), - str = ""; + let formatValidString = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", + chars = formatValidString.repeat(5), + str = ""; - ARRAY_OF_RANDOM_NUMBER.forEach((item, index) => { - str += chars[ARRAY_OF_RANDOM_NUMBER[index]]; - }); + ARRAY_OF_RANDOM_NUMBER.forEach((item, index) => { + str += chars[ARRAY_OF_RANDOM_NUMBER[index]]; + }); - return str.trim(); - }, + return str.trim(); + }, - makeIdForInviteLink(): string { - let result = "", - characters = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", - charactersLength = characters.length; + makeIdForInviteLink(): string { + let result = "", + characters = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", + charactersLength = characters.length; - for (let i = 0; i < 20; i++) - result += characters.charAt(Math.floor(Math.random() * charactersLength)); + for (let i = 0; i < 20; i++) + result += characters.charAt(Math.floor(Math.random() * charactersLength)); - return `+${result}`; - }, + return `+${result}`; + }, - makeIdForPublicLink(id): string { - return `+${id.toString().trim()}`; - } + makeIdForPublicLink(id): string { + return `+${id.toString().trim()}`; + } }; \ No newline at end of file diff --git a/src/util/ReturnJson.ts b/src/util/ReturnJson.ts index 30a91ef..33d6596 100644 --- a/src/util/ReturnJson.ts +++ b/src/util/ReturnJson.ts @@ -1,37 +1,37 @@ -import { Response } from "express"; +import {Response} from "express"; import {IResponse} from "./Types"; // instance of response object express let res: Response; export default { - builder(obj: IResponse, data?: any, option?: object) { - if (!res) - return; - let jsonContent = JSON.parse(JSON.stringify(this.jsonObject(obj, data, option))); - res.status(obj.code); - res.send(jsonContent); - }, - - initializationRes(response: Response) { - res = response; - }, - - jsonObject(obj: IResponse, data?: any, option?: object) { - - let objectBuilder = { - code: obj.code, - message: obj.message, - data: data - }; - - if (option) - return data ? { - ...objectBuilder, - option: option - } : obj; - - return data ? objectBuilder : obj; - } + builder(obj: IResponse, data?: any, option?: object) { + if (!res) + return; + let jsonContent = JSON.parse(JSON.stringify(this.jsonObject(obj, data, option))); + res.status(obj.code); + res.send(jsonContent); + }, + + initializationRes(response: Response) { + res = response; + }, + + jsonObject(obj: IResponse, data?: any, option?: object) { + + let objectBuilder = { + code: obj.code, + message: obj.message, + data: data + }; + + if (option) + return data ? { + ...objectBuilder, + option: option + } : obj; + + return data ? objectBuilder : obj; + } }; \ No newline at end of file diff --git a/src/util/Validation.ts b/src/util/Validation.ts index 15bae51..cde9fe0 100644 --- a/src/util/Validation.ts +++ b/src/util/Validation.ts @@ -1,89 +1,89 @@ -import { TokenExpiredError, JsonWebTokenError } from "jsonwebtoken"; +import {TokenExpiredError, JsonWebTokenError} from "jsonwebtoken"; import jwt from "jsonwebtoken"; -import { JWK, parse } from "node-jose"; +import {JWK, parse} from "node-jose"; import Json from "../util/ReturnJson"; import Response from "../util/Response"; import * as dotenv from "dotenv"; -import { ValidationException } from "../exception/ValidationException"; +import {ValidationException} from "../exception/ValidationException"; dotenv.config(); export default { - // Checks phone number E.g : 09030207892 return true - isPhoneNumber(data: string): boolean { - return /^\d+$/.test(data); - }, + // Checks phone number E.g : 09030207892 return true + isPhoneNumber(data: string): boolean { + return /\+?^\d+$/.test(data); + }, - requestEndpointHandler(requestMethod: string): string { - const arrayOfHttpMethods = [ - "/api/auth/generate/user", - "/api/auth/verify/authCode" - ]; + requestEndpointHandler(requestMethod: string): string { + const arrayOfHttpMethods = [ + "/api/auth/generate/user", + "/api/auth/verify/authCode" + ]; - // Searching in string to ensure exactly string - // In some case it was break something like this: /api/channel/1452/us - return arrayOfHttpMethods.includes(requestMethod) ? "" : requestMethod.match(/\d+/g)?.length > 0 ? "AuthRoute" : ""; - }, + // Searching in string to ensure exactly string + // In some case it was break something like this: /api/channel/1452/us + return arrayOfHttpMethods.includes(requestMethod) ? "" : requestMethod.match(/\d+/g)?.length > 0 ? "AuthRoute" : ""; + }, - // Verify jwt and check jwt expired time - async getJwtVerify(token): Promise { + // Verify jwt and check jwt expired time + async getJwtVerify(token): Promise { - return new Promise(async res => { + return new Promise(async res => { - try { - jwt.verify(token, process.env.PUBLIC_KEY, {}, (err, decoded) => { + try { + jwt.verify(token, process.env.PUBLIC_KEY, {}, (err, decoded) => { - if (err instanceof TokenExpiredError) { - res("TOKEN_EXP"); - return Json.builder(Response.HTTP_UNAUTHORIZED_TOKEN_EXP); - } + if (err instanceof TokenExpiredError) { + res("TOKEN_EXP"); + return Json.builder(Response.HTTP_UNAUTHORIZED_TOKEN_EXP); + } - if (err instanceof JsonWebTokenError) { - res("IN_VALID_TOKEN"); - return Json.builder(Response.HTTP_UNAUTHORIZED_INVALID_TOKEN); - } + if (err instanceof JsonWebTokenError) { + res("IN_VALID_TOKEN"); + return Json.builder(Response.HTTP_UNAUTHORIZED_INVALID_TOKEN); + } + + res(decoded); + }); + } catch (e) { + ValidationException(e); + } - res(decoded); }); - } catch (e) { - ValidationException(e); - } - }); + }, - }, + // The jwt decrypt with JWK library and return jwt + async getJwtDecrypt(encryptedBody) { + try { + let keystore = JWK.createKeyStore(); + await keystore.add(await JWK.asKey(process.env.JWE_PRAIVATE_KEY, "pem")); + let outPut = parse.compact(encryptedBody); + let decryptedVal = await outPut.perform(keystore); + let token = Buffer.from(decryptedVal.plaintext).toString(); - // The jwt decrypt with JWK library and return jwt - async getJwtDecrypt(encryptedBody) { - try { - let keystore = JWK.createKeyStore(); - await keystore.add(await JWK.asKey(process.env.JWE_PRAIVATE_KEY, "pem")); - let outPut = parse.compact(encryptedBody); - let decryptedVal = await outPut.perform(keystore); - let token = Buffer.from(decryptedVal.plaintext).toString(); + if (!decryptedVal?.plaintext) + return Json.builder(Response.HTTP_UNAUTHORIZED_INVALID_TOKEN); - if (!decryptedVal?.plaintext) - return Json.builder(Response.HTTP_UNAUTHORIZED_INVALID_TOKEN); + return token.replace(/["]+/g, ""); - return token.replace(/["]+/g, ""); + } catch (e) { + ValidationException(e); + } + }, - } catch (e) { - ValidationException(e); - } - }, - - - // Returns split jwt without bearer - getSplitBearerJwt(bearerHeader) { - try { - let token = bearerHeader.split(" ")[1]; - if (token && bearerHeader) - return token; - return false; - } catch (e) { - ValidationException(e); + + // Returns split jwt without bearer + getSplitBearerJwt(bearerHeader) { + try { + let token = bearerHeader.split(" ")[1]; + if (token && bearerHeader) + return token; + return false; + } catch (e) { + ValidationException(e); + } } - } };