create-express-mongo-ts 1.0.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.
- package/README.md +157 -0
- package/bin/cli.js +217 -0
- package/package.json +43 -0
- package/template/.dockerignore +2 -0
- package/template/.prettierignore +6 -0
- package/template/.prettierrc +8 -0
- package/template/Dockerfile +17 -0
- package/template/README.md +67 -0
- package/template/eslint.config.mts +34 -0
- package/template/jest.config.ts +201 -0
- package/template/keys/README.md +2 -0
- package/template/nodemon.json +5 -0
- package/template/package.json +65 -0
- package/template/src/app.ts +42 -0
- package/template/src/config.ts +31 -0
- package/template/src/core/ApiError.ts +118 -0
- package/template/src/core/ApiResponse.ts +140 -0
- package/template/src/core/asyncHandler.ts +15 -0
- package/template/src/core/authUtils.ts +68 -0
- package/template/src/core/jwtUtils.ts +96 -0
- package/template/src/core/logger.ts +48 -0
- package/template/src/core/utils.ts +12 -0
- package/template/src/database/index.ts +56 -0
- package/template/src/database/models/ApiKeys.ts +62 -0
- package/template/src/database/models/Keystore.ts +45 -0
- package/template/src/database/models/Role.ts +27 -0
- package/template/src/database/models/User.ts +64 -0
- package/template/src/database/repositories/ApiKeyRepo.ts +26 -0
- package/template/src/database/repositories/KeystoreRepo.ts +53 -0
- package/template/src/database/repositories/UserRepo.ts +63 -0
- package/template/src/helpers/generateApiKey.ts +23 -0
- package/template/src/helpers/validator.ts +38 -0
- package/template/src/index.ts +36 -0
- package/template/src/middlewares/authorize.middleware.ts +26 -0
- package/template/src/middlewares/error.middleware.ts +42 -0
- package/template/src/middlewares/permission.middleware.ts +20 -0
- package/template/src/middlewares/validator.middleware.ts +170 -0
- package/template/src/routes/auth/apiKey.ts +29 -0
- package/template/src/routes/auth/authentication.ts +45 -0
- package/template/src/routes/auth/index.ts +14 -0
- package/template/src/routes/auth/schema.ts +34 -0
- package/template/src/routes/auth/signin.ts +47 -0
- package/template/src/routes/auth/signout.ts +20 -0
- package/template/src/routes/auth/signup.ts +49 -0
- package/template/src/routes/auth/token.ts +68 -0
- package/template/src/routes/health/index.ts +14 -0
- package/template/src/routes/index.ts +19 -0
- package/template/src/types/ApiKey.ts +13 -0
- package/template/src/types/Keystore.ts +12 -0
- package/template/src/types/Role.ts +14 -0
- package/template/src/types/User.ts +16 -0
- package/template/src/types/app-requests.d.ts +22 -0
- package/template/src/types/permissions.ts +3 -0
- package/template/tsconfig.json +33 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* For a detailed explanation regarding each configuration property, visit:
|
|
3
|
+
* https://jestjs.io/docs/configuration
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Config } from 'jest';
|
|
7
|
+
|
|
8
|
+
const config: Config = {
|
|
9
|
+
// All imported modules in your tests should be mocked automatically
|
|
10
|
+
// automock: false,
|
|
11
|
+
|
|
12
|
+
// Stop running tests after `n` failures
|
|
13
|
+
// bail: 0,
|
|
14
|
+
|
|
15
|
+
// The directory where Jest should store its cached dependency information
|
|
16
|
+
// cacheDirectory: "/tmp/jest_rs",
|
|
17
|
+
|
|
18
|
+
// Automatically clear mock calls, instances, contexts and results before every test
|
|
19
|
+
clearMocks: true,
|
|
20
|
+
|
|
21
|
+
// Indicates whether the coverage information should be collected while executing the test
|
|
22
|
+
collectCoverage: true,
|
|
23
|
+
|
|
24
|
+
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
|
25
|
+
// collectCoverageFrom: undefined,
|
|
26
|
+
|
|
27
|
+
// The directory where Jest should output its coverage files
|
|
28
|
+
coverageDirectory: 'coverage',
|
|
29
|
+
|
|
30
|
+
// An array of regexp pattern strings used to skip coverage collection
|
|
31
|
+
// coveragePathIgnorePatterns: [
|
|
32
|
+
// "/node_modules/"
|
|
33
|
+
// ],
|
|
34
|
+
|
|
35
|
+
// Indicates which provider should be used to instrument code for coverage
|
|
36
|
+
coverageProvider: 'v8',
|
|
37
|
+
|
|
38
|
+
// A list of reporter names that Jest uses when writing coverage reports
|
|
39
|
+
// coverageReporters: [
|
|
40
|
+
// "json",
|
|
41
|
+
// "text",
|
|
42
|
+
// "lcov",
|
|
43
|
+
// "clover"
|
|
44
|
+
// ],
|
|
45
|
+
|
|
46
|
+
// An object that configures minimum threshold enforcement for coverage results
|
|
47
|
+
// coverageThreshold: undefined,
|
|
48
|
+
|
|
49
|
+
// A path to a custom dependency extractor
|
|
50
|
+
// dependencyExtractor: undefined,
|
|
51
|
+
|
|
52
|
+
// Make calling deprecated APIs throw helpful error messages
|
|
53
|
+
// errorOnDeprecated: false,
|
|
54
|
+
|
|
55
|
+
// The default configuration for fake timers
|
|
56
|
+
// fakeTimers: {
|
|
57
|
+
// "enableGlobally": false
|
|
58
|
+
// },
|
|
59
|
+
|
|
60
|
+
// Force coverage collection from ignored files using an array of glob patterns
|
|
61
|
+
// forceCoverageMatch: [],
|
|
62
|
+
|
|
63
|
+
// A path to a module which exports an async function that is triggered once before all test suites
|
|
64
|
+
// globalSetup: undefined,
|
|
65
|
+
|
|
66
|
+
// A path to a module which exports an async function that is triggered once after all test suites
|
|
67
|
+
// globalTeardown: undefined,
|
|
68
|
+
|
|
69
|
+
// A set of global variables that need to be available in all test environments
|
|
70
|
+
// globals: {},
|
|
71
|
+
|
|
72
|
+
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
|
73
|
+
// maxWorkers: "50%",
|
|
74
|
+
|
|
75
|
+
// An array of directory names to be searched recursively up from the requiring module's location
|
|
76
|
+
// moduleDirectories: [
|
|
77
|
+
// "node_modules"
|
|
78
|
+
// ],
|
|
79
|
+
|
|
80
|
+
// An array of file extensions your modules use
|
|
81
|
+
// moduleFileExtensions: [
|
|
82
|
+
// "js",
|
|
83
|
+
// "mjs",
|
|
84
|
+
// "cjs",
|
|
85
|
+
// "jsx",
|
|
86
|
+
// "ts",
|
|
87
|
+
// "mts",
|
|
88
|
+
// "cts",
|
|
89
|
+
// "tsx",
|
|
90
|
+
// "json",
|
|
91
|
+
// "node"
|
|
92
|
+
// ],
|
|
93
|
+
|
|
94
|
+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
|
95
|
+
// moduleNameMapper: {},
|
|
96
|
+
|
|
97
|
+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
|
98
|
+
// modulePathIgnorePatterns: [],
|
|
99
|
+
|
|
100
|
+
// Activates notifications for test results
|
|
101
|
+
// notify: false,
|
|
102
|
+
|
|
103
|
+
// An enum that specifies notification mode. Requires { notify: true }
|
|
104
|
+
// notifyMode: "failure-change",
|
|
105
|
+
|
|
106
|
+
// A preset that is used as a base for Jest's configuration
|
|
107
|
+
// preset: undefined,
|
|
108
|
+
|
|
109
|
+
// Run tests from one or more projects
|
|
110
|
+
// projects: undefined,
|
|
111
|
+
|
|
112
|
+
// Use this configuration option to add custom reporters to Jest
|
|
113
|
+
// reporters: undefined,
|
|
114
|
+
|
|
115
|
+
// Automatically reset mock state before every test
|
|
116
|
+
// resetMocks: false,
|
|
117
|
+
|
|
118
|
+
// Reset the module registry before running each individual test
|
|
119
|
+
// resetModules: false,
|
|
120
|
+
|
|
121
|
+
// A path to a custom resolver
|
|
122
|
+
// resolver: undefined,
|
|
123
|
+
|
|
124
|
+
// Automatically restore mock state and implementation before every test
|
|
125
|
+
// restoreMocks: false,
|
|
126
|
+
|
|
127
|
+
// The root directory that Jest should scan for tests and modules within
|
|
128
|
+
// rootDir: undefined,
|
|
129
|
+
|
|
130
|
+
// A list of paths to directories that Jest should use to search for files in
|
|
131
|
+
// roots: [
|
|
132
|
+
// "<rootDir>"
|
|
133
|
+
// ],
|
|
134
|
+
|
|
135
|
+
// Allows you to use a custom runner instead of Jest's default test runner
|
|
136
|
+
// runner: "jest-runner",
|
|
137
|
+
|
|
138
|
+
// The paths to modules that run some code to configure or set up the testing environment before each test
|
|
139
|
+
// setupFiles: [],
|
|
140
|
+
|
|
141
|
+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
|
142
|
+
// setupFilesAfterEnv: [],
|
|
143
|
+
|
|
144
|
+
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
|
145
|
+
// slowTestThreshold: 5,
|
|
146
|
+
|
|
147
|
+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
|
148
|
+
// snapshotSerializers: [],
|
|
149
|
+
|
|
150
|
+
// The test environment that will be used for testing
|
|
151
|
+
// testEnvironment: "jest-environment-node",
|
|
152
|
+
|
|
153
|
+
// Options that will be passed to the testEnvironment
|
|
154
|
+
// testEnvironmentOptions: {},
|
|
155
|
+
|
|
156
|
+
// Adds a location field to test results
|
|
157
|
+
// testLocationInResults: false,
|
|
158
|
+
|
|
159
|
+
// The glob patterns Jest uses to detect test files
|
|
160
|
+
// testMatch: [
|
|
161
|
+
// "**/__tests__/**/*.?([mc])[jt]s?(x)",
|
|
162
|
+
// "**/?(*.)+(spec|test).?([mc])[jt]s?(x)"
|
|
163
|
+
// ],
|
|
164
|
+
|
|
165
|
+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
|
166
|
+
// testPathIgnorePatterns: [
|
|
167
|
+
// "/node_modules/"
|
|
168
|
+
// ],
|
|
169
|
+
|
|
170
|
+
// The regexp pattern or array of patterns that Jest uses to detect test files
|
|
171
|
+
// testRegex: [],
|
|
172
|
+
|
|
173
|
+
// This option allows the use of a custom results processor
|
|
174
|
+
// testResultsProcessor: undefined,
|
|
175
|
+
|
|
176
|
+
// This option allows use of a custom test runner
|
|
177
|
+
// testRunner: "jest-circus/runner",
|
|
178
|
+
|
|
179
|
+
// A map from regular expressions to paths to transformers
|
|
180
|
+
// transform: undefined,
|
|
181
|
+
|
|
182
|
+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
|
183
|
+
// transformIgnorePatterns: [
|
|
184
|
+
// "/node_modules/",
|
|
185
|
+
// "\\.pnp\\.[^\\/]+$"
|
|
186
|
+
// ],
|
|
187
|
+
|
|
188
|
+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
|
189
|
+
// unmockedModulePathPatterns: undefined,
|
|
190
|
+
|
|
191
|
+
// Indicates whether each individual test should be reported during the run
|
|
192
|
+
// verbose: undefined,
|
|
193
|
+
|
|
194
|
+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
|
195
|
+
// watchPathIgnorePatterns: [],
|
|
196
|
+
|
|
197
|
+
// Whether to use watchman for file crawling
|
|
198
|
+
// watchman: true,
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
export default config;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "express-mongo-app",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Express + MongoDB application",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"lint:fix": "eslint . --fix",
|
|
8
|
+
"build": "npx tsc -b",
|
|
9
|
+
"dev": "nodemon",
|
|
10
|
+
"start": "npm run build && npm run serve",
|
|
11
|
+
"serve": "node -r dotenv/config dist/index.js",
|
|
12
|
+
"test": "jest",
|
|
13
|
+
"prettier:base": "prettier --parser typescript --single-quote",
|
|
14
|
+
"prettier:check": "npm run prettier:base -- --list-different \"src/**/*.{ts,tsx}\"",
|
|
15
|
+
"prettier:write": "npm run prettier:base -- --write \"src/**/*.{ts,tsx}\"",
|
|
16
|
+
"lint": "eslint \"src/**\""
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"express",
|
|
20
|
+
"mongodb",
|
|
21
|
+
"typescript",
|
|
22
|
+
"rest-api",
|
|
23
|
+
"template"
|
|
24
|
+
],
|
|
25
|
+
"author": "",
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"type": "commonjs",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"bcryptjs": "^3.0.3",
|
|
30
|
+
"cookie-parser": "^1.4.7",
|
|
31
|
+
"cors": "^2.8.5",
|
|
32
|
+
"dotenv": "^17.2.3",
|
|
33
|
+
"express": "^5.1.0",
|
|
34
|
+
"helmet": "^8.1.0",
|
|
35
|
+
"jsonwebtoken": "^9.0.2",
|
|
36
|
+
"lodash": "^4.17.21",
|
|
37
|
+
"mongoose": "^8.20.0",
|
|
38
|
+
"winston": "^3.18.3",
|
|
39
|
+
"winston-daily-rotate-file": "^5.0.0",
|
|
40
|
+
"zod": "^4.1.12"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/bcryptjs": "^2.4.6",
|
|
44
|
+
"@types/cookie-parser": "^1.4.10",
|
|
45
|
+
"@types/cors": "^2.8.19",
|
|
46
|
+
"@types/express": "^5.0.5",
|
|
47
|
+
"@types/helmet": "^0.0.48",
|
|
48
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
49
|
+
"@types/lodash": "^4.17.20",
|
|
50
|
+
"@types/mongoose": "^5.11.96",
|
|
51
|
+
"@types/node": "^24.10.1",
|
|
52
|
+
"@typescript-eslint/eslint-plugin": "^8.48.0",
|
|
53
|
+
"@typescript-eslint/parser": "^8.48.0",
|
|
54
|
+
"eslint": "^9.39.1",
|
|
55
|
+
"eslint-plugin-react": "^7.37.5",
|
|
56
|
+
"globals": "^16.5.0",
|
|
57
|
+
"jest": "^30.2.0",
|
|
58
|
+
"jiti": "^2.5.1",
|
|
59
|
+
"nodemon": "^3.1.11",
|
|
60
|
+
"prettier": "^3.7.3",
|
|
61
|
+
"ts-node": "^10.9.2",
|
|
62
|
+
"tsconfig-paths": "^4.2.0",
|
|
63
|
+
"typescript": "^5.9.3"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import logger from './core/logger.js';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import cors from 'cors';
|
|
4
|
+
import { originUrl } from './config.js';
|
|
5
|
+
import router from './routes/index.js';
|
|
6
|
+
import { errorHandler } from './middlewares/error.middleware.js';
|
|
7
|
+
import { NotFoundError } from './core/ApiError.js';
|
|
8
|
+
import cookieParser from 'cookie-parser';
|
|
9
|
+
import helmet from "helmet";
|
|
10
|
+
|
|
11
|
+
process.on('uncaughtException', (e) => {
|
|
12
|
+
logger.error(e);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const app = express();
|
|
16
|
+
|
|
17
|
+
// Adjust the size of response body as per requirement
|
|
18
|
+
app.use(express.json({ limit: '10mb' }));
|
|
19
|
+
app.use(
|
|
20
|
+
express.urlencoded({
|
|
21
|
+
limit: '10mb',
|
|
22
|
+
extended: true,
|
|
23
|
+
parameterLimit: 50000,
|
|
24
|
+
}),
|
|
25
|
+
);
|
|
26
|
+
// Allows cross origin reference
|
|
27
|
+
app.use(
|
|
28
|
+
cors({
|
|
29
|
+
origin: originUrl,
|
|
30
|
+
optionsSuccessStatus: 200,
|
|
31
|
+
credentials: true,
|
|
32
|
+
}),
|
|
33
|
+
);
|
|
34
|
+
app.use(cookieParser());
|
|
35
|
+
// Adds security header, express best security practice
|
|
36
|
+
app.use(helmet());
|
|
37
|
+
|
|
38
|
+
// Main routes
|
|
39
|
+
app.use('/', router);
|
|
40
|
+
|
|
41
|
+
app.use((_req, _res, next) => next(new NotFoundError()));
|
|
42
|
+
app.use(errorHandler);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import dotenv from 'dotenv';
|
|
2
|
+
|
|
3
|
+
dotenv.config();
|
|
4
|
+
|
|
5
|
+
export const originUrl = process.env.ORIGIN_URL;
|
|
6
|
+
export const isProduction = process.env.NODE_ENV === 'production';
|
|
7
|
+
export const timeZone = process.env.TZ;
|
|
8
|
+
export const port = process.env.PORT;
|
|
9
|
+
|
|
10
|
+
// JWT token configuration
|
|
11
|
+
export const tokenInfo = {
|
|
12
|
+
accessTokenValidity: parseInt(process.env.ACCESS_TOKEN_VALIDITY_SEC || '0'),
|
|
13
|
+
refreshTokenValidity: parseInt(
|
|
14
|
+
process.env.REFRESH_TOKEN_VALIDITY_SEC || '0',
|
|
15
|
+
),
|
|
16
|
+
issuer: process.env.TOKEN_ISSUER || '',
|
|
17
|
+
audience: process.env.TOKEN_AUDIENCE || '',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// DB config
|
|
21
|
+
export const db = {
|
|
22
|
+
name: process.env.DB_NAME || '',
|
|
23
|
+
host: process.env.DB_HOST || '',
|
|
24
|
+
port: process.env.DB_PORT || '27017',
|
|
25
|
+
user: process.env.DB_USER || '',
|
|
26
|
+
password: process.env.DB_USER_PASSWORD || '',
|
|
27
|
+
minPoolSize: parseInt(process.env.DB_MIN_POOL_SIZE || '5'),
|
|
28
|
+
maxPoolSize: parseInt(process.env.DB_MAX_POOL_SIZE || '10'),
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const logDirectory = process.env.LOG_DIRECTORY;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Response } from 'express';
|
|
2
|
+
import { isProduction } from '../config.js';
|
|
3
|
+
import {
|
|
4
|
+
AuthFailureResponse,
|
|
5
|
+
AccessTokenErrorResponse,
|
|
6
|
+
InternalErrorResponse,
|
|
7
|
+
NotFoundResponse,
|
|
8
|
+
BadRequestResponse,
|
|
9
|
+
ForbiddenResponse,
|
|
10
|
+
} from './ApiResponse.js';
|
|
11
|
+
|
|
12
|
+
export enum ErrorType {
|
|
13
|
+
BAD_TOKEN = 'BadTokenError',
|
|
14
|
+
TOKEN_EXPIRED = 'TokenExpiredError',
|
|
15
|
+
UNAUTHORIZED = 'AuthFailureError',
|
|
16
|
+
ACCESS_TOKEN = 'AccessTokenError',
|
|
17
|
+
INTERNAL = 'InternalError',
|
|
18
|
+
NOT_FOUND = 'NotFoundError',
|
|
19
|
+
NO_ENTRY = 'NoEntryError',
|
|
20
|
+
NO_DATA = 'NoDataError',
|
|
21
|
+
BAD_REQUEST = 'BadRequestError',
|
|
22
|
+
FORBIDDEN = 'ForbiddenError',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export abstract class ApiError extends Error {
|
|
26
|
+
constructor(public type: ErrorType, public message: string = 'error', public success: boolean) {
|
|
27
|
+
super(type);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public static handle(err: ApiError, res: Response): Response {
|
|
31
|
+
switch (err.type) {
|
|
32
|
+
case ErrorType.BAD_TOKEN:
|
|
33
|
+
case ErrorType.TOKEN_EXPIRED:
|
|
34
|
+
case ErrorType.UNAUTHORIZED:
|
|
35
|
+
return new AuthFailureResponse(err.message).send(res);
|
|
36
|
+
case ErrorType.ACCESS_TOKEN:
|
|
37
|
+
return new AccessTokenErrorResponse(err.message).send(res);
|
|
38
|
+
case ErrorType.INTERNAL:
|
|
39
|
+
return new InternalErrorResponse(err.message).send(res);
|
|
40
|
+
case ErrorType.NOT_FOUND:
|
|
41
|
+
case ErrorType.NO_ENTRY:
|
|
42
|
+
case ErrorType.NO_DATA:
|
|
43
|
+
return new NotFoundResponse(err.message).send(res);
|
|
44
|
+
case ErrorType.BAD_REQUEST:
|
|
45
|
+
return new BadRequestResponse(err.message).send(res);
|
|
46
|
+
case ErrorType.FORBIDDEN:
|
|
47
|
+
return new ForbiddenResponse(err.message).send(res);
|
|
48
|
+
default: {
|
|
49
|
+
let message = err.message;
|
|
50
|
+
// Do not send failure message in production as it may send sensitive data
|
|
51
|
+
if (isProduction) {
|
|
52
|
+
message = 'Something wrong happened.';
|
|
53
|
+
}
|
|
54
|
+
return new InternalErrorResponse(message).send(res);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class AuthFailureError extends ApiError {
|
|
61
|
+
constructor(message = 'Invalid Credentials') {
|
|
62
|
+
super(ErrorType.UNAUTHORIZED, message, false);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export class InternalError extends ApiError {
|
|
67
|
+
constructor(message = 'Internal error') {
|
|
68
|
+
super(ErrorType.INTERNAL, message, false);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class BadRequestError extends ApiError {
|
|
73
|
+
constructor(message = 'Bad Request') {
|
|
74
|
+
super(ErrorType.BAD_REQUEST, message, false);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export class NotFoundError extends ApiError {
|
|
79
|
+
constructor(message = 'Not Found') {
|
|
80
|
+
super(ErrorType.NOT_FOUND, message, false);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export class ForbiddenError extends ApiError {
|
|
85
|
+
constructor(message = 'Permission denied') {
|
|
86
|
+
super(ErrorType.FORBIDDEN, message, false);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class NoEntryError extends ApiError {
|
|
91
|
+
constructor(message = "Entry don't exists") {
|
|
92
|
+
super(ErrorType.NO_ENTRY, message, false);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export class BadTokenError extends ApiError {
|
|
97
|
+
constructor(message = 'Token is not valid') {
|
|
98
|
+
super(ErrorType.BAD_TOKEN, message, false);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export class TokenExpiredError extends ApiError {
|
|
103
|
+
constructor(message = 'Token is expired') {
|
|
104
|
+
super(ErrorType.TOKEN_EXPIRED, message, false);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export class NoDataError extends ApiError {
|
|
109
|
+
constructor(message = 'No data available') {
|
|
110
|
+
super(ErrorType.NO_DATA, message, false);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export class AccessTokenError extends ApiError {
|
|
115
|
+
constructor(message = 'Invalid access token') {
|
|
116
|
+
super(ErrorType.ACCESS_TOKEN, message, false);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { Response } from 'express';
|
|
2
|
+
|
|
3
|
+
// Helper code for the API consumer to understand the error and handle it accordingly
|
|
4
|
+
enum StatusCode {
|
|
5
|
+
SUCCESS = '10000',
|
|
6
|
+
FAILURE = '10001',
|
|
7
|
+
RETRY = '10002',
|
|
8
|
+
INVALID_ACCESS_TOKEN = '10003',
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
enum ResponseStatus {
|
|
12
|
+
SUCCESS = 200,
|
|
13
|
+
BAD_REQUEST = 400,
|
|
14
|
+
UNAUTHORIZED = 401,
|
|
15
|
+
FORBIDDEN = 403,
|
|
16
|
+
NOT_FOUND = 404,
|
|
17
|
+
INTERNAL_ERROR = 500,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
abstract class ApiResponse {
|
|
21
|
+
constructor(
|
|
22
|
+
protected statusCode: StatusCode,
|
|
23
|
+
protected status: ResponseStatus,
|
|
24
|
+
protected message: string,
|
|
25
|
+
protected success: boolean
|
|
26
|
+
) { }
|
|
27
|
+
|
|
28
|
+
protected prepare<T extends ApiResponse>(
|
|
29
|
+
res: Response,
|
|
30
|
+
response: T,
|
|
31
|
+
headers: { [key: string]: string },
|
|
32
|
+
): Response {
|
|
33
|
+
for (const [key, value] of Object.entries(headers)) res.append(key, value);
|
|
34
|
+
return res.status(this.status).json(ApiResponse.sanitize(response));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public send(
|
|
38
|
+
res: Response,
|
|
39
|
+
headers: { [key: string]: string } = {},
|
|
40
|
+
): Response {
|
|
41
|
+
return this.prepare<ApiResponse>(res, this, headers);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private static sanitize<T extends ApiResponse>(response: T): T {
|
|
45
|
+
const clone: T = {} as T;
|
|
46
|
+
Object.assign(clone, response);
|
|
47
|
+
// @ts-expect-error: optional
|
|
48
|
+
delete clone.status;
|
|
49
|
+
for (const i in clone) if (typeof clone[i] === 'undefined') delete clone[i];
|
|
50
|
+
return clone;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class AuthFailureResponse extends ApiResponse {
|
|
55
|
+
constructor(message = 'Authentication Failure') {
|
|
56
|
+
super(StatusCode.FAILURE, ResponseStatus.UNAUTHORIZED, message, false);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class NotFoundResponse extends ApiResponse {
|
|
61
|
+
constructor(message = 'Not Found') {
|
|
62
|
+
super(StatusCode.FAILURE, ResponseStatus.NOT_FOUND, message, false);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
send(res: Response, headers: { [key: string]: string } = {}): Response {
|
|
66
|
+
return super.prepare<NotFoundResponse>(res, this, headers);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class ForbiddenResponse extends ApiResponse {
|
|
71
|
+
constructor(message = 'Forbidden') {
|
|
72
|
+
super(StatusCode.FAILURE, ResponseStatus.FORBIDDEN, message, false);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export class BadRequestResponse extends ApiResponse {
|
|
77
|
+
constructor(message = 'Bad Parameters') {
|
|
78
|
+
super(StatusCode.FAILURE, ResponseStatus.BAD_REQUEST, message, false);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export class InternalErrorResponse extends ApiResponse {
|
|
83
|
+
constructor(message = 'Internal Error') {
|
|
84
|
+
super(StatusCode.FAILURE, ResponseStatus.INTERNAL_ERROR, message, false);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export class SuccessMsgResponse extends ApiResponse {
|
|
89
|
+
constructor(message: string) {
|
|
90
|
+
super(StatusCode.SUCCESS, ResponseStatus.SUCCESS, message, true);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class FailureMsgResponse extends ApiResponse {
|
|
95
|
+
constructor(message: string) {
|
|
96
|
+
super(StatusCode.FAILURE, ResponseStatus.SUCCESS, message, false);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export class SuccessResponse<T> extends ApiResponse {
|
|
101
|
+
constructor(message: string, private data: T) {
|
|
102
|
+
super(StatusCode.SUCCESS, ResponseStatus.SUCCESS, message, true);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
send(res: Response, headers: { [key: string]: string } = {}): Response {
|
|
106
|
+
return super.prepare<SuccessResponse<T>>(res, this, headers);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export class AccessTokenErrorResponse extends ApiResponse {
|
|
111
|
+
private instruction = 'refresh_token';
|
|
112
|
+
|
|
113
|
+
constructor(message = 'Access token invalid') {
|
|
114
|
+
super(
|
|
115
|
+
StatusCode.INVALID_ACCESS_TOKEN,
|
|
116
|
+
ResponseStatus.UNAUTHORIZED,
|
|
117
|
+
message,
|
|
118
|
+
false
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
send(res: Response, headers: { [key: string]: string } = {}): Response {
|
|
123
|
+
headers.instruction = this.instruction;
|
|
124
|
+
return super.prepare<AccessTokenErrorResponse>(res, this, headers);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export class TokenRefreshResponse extends ApiResponse {
|
|
129
|
+
constructor(
|
|
130
|
+
message: string,
|
|
131
|
+
private accessToken: string,
|
|
132
|
+
private refreshToken: string,
|
|
133
|
+
) {
|
|
134
|
+
super(StatusCode.SUCCESS, ResponseStatus.SUCCESS, message, true);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
send(res: Response, headers: { [key: string]: string } = {}): Response {
|
|
138
|
+
return super.prepare<TokenRefreshResponse>(res, this, headers);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Request, Response, NextFunction } from "express";
|
|
2
|
+
|
|
3
|
+
type AsyncFunction<Req extends Request = Request> = (
|
|
4
|
+
req: Req,
|
|
5
|
+
res: Response,
|
|
6
|
+
next: NextFunction
|
|
7
|
+
) => Promise<void>;
|
|
8
|
+
|
|
9
|
+
export function asyncHandler<Req extends Request = Request>(
|
|
10
|
+
execution: AsyncFunction<Req>
|
|
11
|
+
) {
|
|
12
|
+
return (req: Request, res: Response, next: NextFunction) => {
|
|
13
|
+
execution(req as Req, res, next).catch(next);
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { AuthFailureError, InternalError } from './ApiError';
|
|
2
|
+
import User from './../types/User';
|
|
3
|
+
import { Tokens } from './../types/app-requests';
|
|
4
|
+
import JWT, { JwtPayload } from './jwtUtils';
|
|
5
|
+
import { tokenInfo } from './../config';
|
|
6
|
+
import { Types } from 'mongoose';
|
|
7
|
+
import bcryptjs from 'bcryptjs';
|
|
8
|
+
|
|
9
|
+
export const getAccessToken = (authorization?: string) => {
|
|
10
|
+
if (!authorization) throw new AuthFailureError('Invalid Authorization');
|
|
11
|
+
if (!authorization.startsWith('Bearer '))
|
|
12
|
+
throw new AuthFailureError('Invalid Authorization');
|
|
13
|
+
return authorization.split(' ')[1];
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const validateTokenData = (payload: JwtPayload): boolean => {
|
|
17
|
+
if (
|
|
18
|
+
!payload ||
|
|
19
|
+
!payload.iss ||
|
|
20
|
+
!payload.sub ||
|
|
21
|
+
!payload.aud ||
|
|
22
|
+
!payload.prm ||
|
|
23
|
+
payload.iss !== tokenInfo.issuer ||
|
|
24
|
+
payload.aud !== tokenInfo.audience ||
|
|
25
|
+
!Types.ObjectId.isValid(payload.sub)
|
|
26
|
+
)
|
|
27
|
+
throw new AuthFailureError('Invalid Access Token');
|
|
28
|
+
return true;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const createTokens = async (
|
|
32
|
+
user: User,
|
|
33
|
+
accessTokenKey: string,
|
|
34
|
+
refreshTokenKey: string,
|
|
35
|
+
): Promise<Tokens> => {
|
|
36
|
+
const accessToken = await JWT.encode(
|
|
37
|
+
new JwtPayload(
|
|
38
|
+
tokenInfo.issuer,
|
|
39
|
+
tokenInfo.audience,
|
|
40
|
+
user._id.toString(),
|
|
41
|
+
accessTokenKey,
|
|
42
|
+
tokenInfo.accessTokenValidity,
|
|
43
|
+
),
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
if (!accessToken) throw new InternalError();
|
|
47
|
+
|
|
48
|
+
const refreshToken = await JWT.encode(
|
|
49
|
+
new JwtPayload(
|
|
50
|
+
tokenInfo.issuer,
|
|
51
|
+
tokenInfo.audience,
|
|
52
|
+
user._id.toString(),
|
|
53
|
+
refreshTokenKey,
|
|
54
|
+
tokenInfo.refreshTokenValidity,
|
|
55
|
+
),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
if (!refreshToken) throw new InternalError();
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
accessToken: accessToken,
|
|
62
|
+
refreshToken: refreshToken,
|
|
63
|
+
} as Tokens;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export const isPasswordCorrect = async function (userPassword: string, hashedPassword: string) {
|
|
67
|
+
return await bcryptjs.compare(userPassword, hashedPassword);
|
|
68
|
+
};
|