express-generator-typescript 1.10.3 → 2.0.2

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.
Files changed (121) hide show
  1. package/README.md +37 -27
  2. package/bin/cli.js +2 -15
  3. package/lib/cli.js +1 -15
  4. package/lib/express-generator-typescript.js +11 -21
  5. package/lib/project-files/.eslintrc.json +16 -2
  6. package/lib/project-files/build.ts +2 -2
  7. package/lib/project-files/package.json +15 -5
  8. package/lib/project-files/spec/nodemon.json +1 -1
  9. package/lib/{auth-proj → project-files}/spec/support/login-agent.ts +6 -8
  10. package/lib/{auth-proj → project-files}/spec/tests/auth.spec.ts +18 -32
  11. package/lib/project-files/spec/tests/users.spec.ts +31 -22
  12. package/lib/project-files/spec/types/supertest/index.d.ts +14 -0
  13. package/lib/project-files/src/models/user-model.ts +18 -3
  14. package/lib/project-files/src/pre-start/env/development.env +9 -0
  15. package/lib/project-files/src/pre-start/env/production.env +10 -0
  16. package/lib/project-files/src/pre-start/env/test.env +9 -0
  17. package/lib/{auth-proj → project-files}/src/public/scripts/http.js +0 -0
  18. package/lib/{auth-proj → project-files}/src/public/scripts/login.js +0 -0
  19. package/lib/{auth-proj → project-files}/src/public/scripts/users.js +0 -0
  20. package/lib/{auth-proj → project-files}/src/public/stylesheets/login.css +0 -0
  21. package/lib/{auth-proj → project-files}/src/public/stylesheets/users.css +0 -0
  22. package/lib/project-files/src/repos/mock-orm.ts +2 -2
  23. package/lib/project-files/src/repos/user-repo.ts +1 -1
  24. package/lib/project-files/src/routes/api.ts +9 -6
  25. package/lib/{socket-io → project-files}/src/routes/auth-router.ts +14 -15
  26. package/lib/{auth-proj → project-files}/src/routes/middleware.ts +10 -8
  27. package/lib/project-files/src/routes/user-router.ts +9 -15
  28. package/lib/project-files/src/server.ts +82 -73
  29. package/lib/{auth-proj → project-files}/src/services/auth-service.ts +1 -1
  30. package/lib/project-files/src/services/user-service.ts +9 -9
  31. package/lib/project-files/src/shared/env-vars.ts +18 -0
  32. package/lib/project-files/src/shared/errors.ts +11 -0
  33. package/lib/project-files/src/shared/types.ts +14 -0
  34. package/lib/project-files/src/types/express/index.d.ts +16 -8
  35. package/lib/{socket-io → project-files}/src/util/jwt-util.ts +10 -9
  36. package/lib/{auth-proj → project-files}/src/views/login.html +0 -0
  37. package/lib/{auth-proj → project-files}/src/views/users.html +0 -0
  38. package/lib/project-files/tsconfig.json +3 -0
  39. package/package.json +1 -1
  40. package/chat-screenshot.png +0 -0
  41. package/lib/auth-proj/.eslintignore +0 -1
  42. package/lib/auth-proj/.eslintrc.json +0 -27
  43. package/lib/auth-proj/build.ts +0 -64
  44. package/lib/auth-proj/gitignore +0 -3
  45. package/lib/auth-proj/package.json +0 -73
  46. package/lib/auth-proj/spec/index.ts +0 -57
  47. package/lib/auth-proj/spec/loadEnv.ts +0 -10
  48. package/lib/auth-proj/spec/nodemon.json +0 -6
  49. package/lib/auth-proj/spec/support/jasmine.json +0 -11
  50. package/lib/auth-proj/spec/tests/users.spec.ts +0 -283
  51. package/lib/auth-proj/src/index.ts +0 -14
  52. package/lib/auth-proj/src/models/user-model.ts +0 -56
  53. package/lib/auth-proj/src/pre-start/env/development.env +0 -23
  54. package/lib/auth-proj/src/pre-start/env/production.env +0 -24
  55. package/lib/auth-proj/src/pre-start/env/test.env +0 -23
  56. package/lib/auth-proj/src/pre-start/index.ts +0 -28
  57. package/lib/auth-proj/src/repos/database.json +0 -1
  58. package/lib/auth-proj/src/repos/mock-orm.ts +0 -41
  59. package/lib/auth-proj/src/repos/user-repo.ts +0 -88
  60. package/lib/auth-proj/src/routes/api.ts +0 -17
  61. package/lib/auth-proj/src/routes/auth-router.ts +0 -63
  62. package/lib/auth-proj/src/routes/user-router.ts +0 -80
  63. package/lib/auth-proj/src/server.ts +0 -82
  64. package/lib/auth-proj/src/services/user-service.ts +0 -52
  65. package/lib/auth-proj/src/shared/env-vars.ts +0 -20
  66. package/lib/auth-proj/src/shared/errors.ts +0 -45
  67. package/lib/auth-proj/src/shared/functions.ts +0 -18
  68. package/lib/auth-proj/src/types/express/index.d.ts +0 -32
  69. package/lib/auth-proj/src/util/jwt-util.ts +0 -47
  70. package/lib/auth-proj/tsconfig.json +0 -100
  71. package/lib/auth-proj/tsconfig.prod.json +0 -11
  72. package/lib/project-files/src/public/scripts/index.js +0 -183
  73. package/lib/project-files/src/public/stylesheets/style.css +0 -33
  74. package/lib/project-files/src/views/index.html +0 -31
  75. package/lib/socket-io/.eslintignore +0 -1
  76. package/lib/socket-io/.eslintrc.json +0 -27
  77. package/lib/socket-io/build.ts +0 -64
  78. package/lib/socket-io/gitignore +0 -3
  79. package/lib/socket-io/package.json +0 -75
  80. package/lib/socket-io/spec/index.ts +0 -57
  81. package/lib/socket-io/spec/loadEnv.ts +0 -10
  82. package/lib/socket-io/spec/nodemon.json +0 -6
  83. package/lib/socket-io/spec/support/jasmine.json +0 -11
  84. package/lib/socket-io/spec/support/login-agent.ts +0 -49
  85. package/lib/socket-io/spec/tests/auth.spec.ts +0 -159
  86. package/lib/socket-io/spec/tests/chat.spec.ts +0 -150
  87. package/lib/socket-io/spec/tests/users.spec.ts +0 -283
  88. package/lib/socket-io/src/index.ts +0 -14
  89. package/lib/socket-io/src/models/user-model.ts +0 -56
  90. package/lib/socket-io/src/pre-start/env/development.env +0 -23
  91. package/lib/socket-io/src/pre-start/env/production.env +0 -24
  92. package/lib/socket-io/src/pre-start/env/test.env +0 -23
  93. package/lib/socket-io/src/pre-start/index.ts +0 -28
  94. package/lib/socket-io/src/public/scripts/chat.js +0 -87
  95. package/lib/socket-io/src/public/scripts/http.js +0 -24
  96. package/lib/socket-io/src/public/scripts/index.js +0 -16
  97. package/lib/socket-io/src/public/scripts/login.js +0 -17
  98. package/lib/socket-io/src/public/scripts/users.js +0 -148
  99. package/lib/socket-io/src/public/stylesheets/chat.css +0 -43
  100. package/lib/socket-io/src/public/stylesheets/index.css +0 -13
  101. package/lib/socket-io/src/public/stylesheets/login.css +0 -20
  102. package/lib/socket-io/src/public/stylesheets/users.css +0 -40
  103. package/lib/socket-io/src/repos/database.json +0 -38
  104. package/lib/socket-io/src/repos/mock-orm.ts +0 -41
  105. package/lib/socket-io/src/repos/user-repo.ts +0 -88
  106. package/lib/socket-io/src/routes/api.ts +0 -19
  107. package/lib/socket-io/src/routes/chat-router.ts +0 -97
  108. package/lib/socket-io/src/routes/middleware.ts +0 -55
  109. package/lib/socket-io/src/routes/user-router.ts +0 -77
  110. package/lib/socket-io/src/server.ts +0 -100
  111. package/lib/socket-io/src/services/auth-service.ts +0 -38
  112. package/lib/socket-io/src/services/user-service.ts +0 -52
  113. package/lib/socket-io/src/shared/env-vars.ts +0 -20
  114. package/lib/socket-io/src/shared/errors.ts +0 -56
  115. package/lib/socket-io/src/shared/functions.ts +0 -18
  116. package/lib/socket-io/src/types/express/index.d.ts +0 -34
  117. package/lib/socket-io/src/views/chat.html +0 -51
  118. package/lib/socket-io/src/views/login.html +0 -35
  119. package/lib/socket-io/src/views/users.html +0 -47
  120. package/lib/socket-io/tsconfig.json +0 -100
  121. package/lib/socket-io/tsconfig.prod.json +0 -11
@@ -1,23 +0,0 @@
1
- ## Environment ##
2
- NODE_ENV=development
3
-
4
-
5
- ## Server ##
6
- PORT=3000
7
- HOST=localhost
8
-
9
-
10
- ## Setup jet-logger ##
11
- JET_LOGGER_MODE=CONSOLE
12
- JET_LOGGER_FILEPATH=jet-logger.log
13
- JET_LOGGER_TIMESTAMP=TRUE
14
- JET_LOGGER_FORMAT=LINE
15
-
16
- ## Authentication ##
17
- COOKIE_DOMAIN=localhost
18
- COOKIE_PATH=/
19
- SECURE_COOKIE=false
20
- JWT_SECRET=xxxxxxxxxxxxxx
21
- COOKIE_SECRET=xxxxxxxxxxxxxx
22
- # expires in 3 days
23
- COOKIE_EXP=259200000
@@ -1,24 +0,0 @@
1
- ## Environment ##
2
- NODE_ENV=production
3
-
4
-
5
- ## Server ##
6
- PORT=8081
7
- HOST=localhost
8
-
9
-
10
- ## Setup jet-logger ##
11
- JET_LOGGER_MODE=FILE
12
- JET_LOGGER_FILEPATH=jet-logger.log
13
- JET_LOGGER_TIMESTAMP=TRUE
14
- JET_LOGGER_FORMAT=LINE
15
-
16
- ## Authentication ##
17
- # SECURE_COOKIE 'false' here for demo-ing. But ideally should be true.
18
- COOKIE_DOMAIN=localhost
19
- COOKIE_PATH=/
20
- SECURE_COOKIE=false
21
- JWT_SECRET=xxxxxxxxxxxxxx
22
- COOKIE_SECRET=xxxxxxxxxxxxxx
23
- # expires in 3 days
24
- COOKIE_EXP=259200000
@@ -1,23 +0,0 @@
1
- ## Environment ##
2
- NODE_ENV=test
3
-
4
-
5
- ## Server ##
6
- PORT=4000
7
- HOST=localhost
8
-
9
-
10
- ## Setup jet-logger ##
11
- JET_LOGGER_MODE=CONSOLE
12
- JET_LOGGER_FILEPATH=jet-logger.log
13
- JET_LOGGER_TIMESTAMP=TRUE
14
- JET_LOGGER_FORMAT=LINE
15
-
16
- ## Authentication ##
17
- COOKIE_DOMAIN=localhost
18
- COOKIE_PATH=/
19
- SECURE_COOKIE=false
20
- JWT_SECRET=xxxxxxxxxxxxxx
21
- COOKIE_SECRET=xxxxxxxxxxxxxx
22
- # expires in 3 days
23
- COOKIE_EXP=259200000
@@ -1,28 +0,0 @@
1
- /**
2
- * Pre-start is where we want to place things that must run BEFORE the express server is started.
3
- * This is useful for environment variables, command-line arguments, and cron-jobs.
4
- */
5
-
6
- import path from 'path';
7
- import dotenv from 'dotenv';
8
- import commandLineArgs from 'command-line-args';
9
-
10
-
11
- // Setup command line options
12
- const options = commandLineArgs([
13
- {
14
- name: 'env',
15
- alias: 'e',
16
- defaultValue: 'development',
17
- type: String,
18
- },
19
- ]);
20
-
21
- // Set the env file
22
- const result2 = dotenv.config({
23
- path: path.join(__dirname, `env/${String(options.env)}.env`),
24
- });
25
-
26
- if (result2.error) {
27
- throw result2.error;
28
- }
@@ -1 +0,0 @@
1
- {"users":[{"name":"Sean Maxwell","email":"sean.maxwell@gmail.com","pwdHash":"$2b$12$1mE2OI9hMS/rgH9Mi0s85OM2V5gzm7aF3gJIWH1y0S1MqVBueyjsy","role":1,"id":159123164363},{"name":"Gordan Freeman","email":"gordan.freeman@halflife.com","pwdHash":"$2b$12$1mE2OI9hMS/rgH9Mi0s85OM2V5gzm7aF3gJIWH1y0S1MqVBueyjsy","role":0,"id":906524522143},{"name":"John Smith","email":"jsmith@yahoo.com","pwdHash":"$2b$12$1mE2OI9hMS/rgH9Mi0s85OM2V5gzm7aF3gJIWH1y0S1MqVBueyjsy","role":0,"id":357437875835}]}
@@ -1,41 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unsafe-return */
2
-
3
- import jsonfile from 'jsonfile';
4
- import { IUser } from '@models/user-model';
5
-
6
-
7
- // **** Variables **** //
8
-
9
- const dbFilePath = 'src/repos/database.json';
10
-
11
-
12
- // **** Types **** //
13
-
14
- interface IDb {
15
- users: IUser[];
16
- }
17
-
18
-
19
- // **** Functions **** //
20
-
21
- /**
22
- * Fetch the json from the file.
23
- */
24
- function openDb(): Promise<IDb> {
25
- return jsonfile.readFile(dbFilePath);
26
- }
27
-
28
- /**
29
- * Update the file.
30
- */
31
- function saveDb(db: IDb): Promise<void> {
32
- return jsonfile.writeFile(dbFilePath, db);
33
- }
34
-
35
-
36
- // **** Export default **** //
37
-
38
- export default {
39
- openDb,
40
- saveDb,
41
- } as const;
@@ -1,88 +0,0 @@
1
- import { IUser } from '@models/user-model';
2
- import { getRandomInt } from '@shared/functions';
3
- import orm from './mock-orm';
4
-
5
-
6
- // **** Functions **** //
7
-
8
- /**
9
- * Get one user.
10
- */
11
- async function getOne(email: string): Promise<IUser | null> {
12
- const db = await orm.openDb();
13
- for (const user of db.users) {
14
- if (user.email === email) {
15
- return user;
16
- }
17
- }
18
- return null;
19
- }
20
-
21
- /**
22
- * See if a user with the given id exists.
23
- */
24
- async function persists(id: number): Promise<boolean> {
25
- const db = await orm.openDb();
26
- for (const user of db.users) {
27
- if (user.id === id) {
28
- return true;
29
- }
30
- }
31
- return false;
32
- }
33
-
34
- /**
35
- * Get all users.
36
- */
37
- async function getAll(): Promise<IUser[]> {
38
- const db = await orm.openDb();
39
- return db.users;
40
- }
41
-
42
- /**
43
- * Add one user.
44
- */
45
- async function add(user: IUser): Promise<void> {
46
- const db = await orm.openDb();
47
- user.id = getRandomInt();
48
- db.users.push(user);
49
- return orm.saveDb(db);
50
- }
51
-
52
- /**
53
- * Update a user.
54
- */
55
- async function update(user: IUser): Promise<void> {
56
- const db = await orm.openDb();
57
- for (let i = 0; i < db.users.length; i++) {
58
- if (db.users[i].id === user.id) {
59
- db.users[i] = user;
60
- return orm.saveDb(db);
61
- }
62
- }
63
- }
64
-
65
- /**
66
- * Delete one user.
67
- */
68
- async function _delete(id: number): Promise<void> {
69
- const db = await orm.openDb();
70
- for (let i = 0; i < db.users.length; i++) {
71
- if (db.users[i].id === id) {
72
- db.users.splice(i, 1);
73
- return orm.saveDb(db);
74
- }
75
- }
76
- }
77
-
78
-
79
- // **** Export default **** //
80
-
81
- export default {
82
- getOne,
83
- persists,
84
- getAll,
85
- add,
86
- update,
87
- delete: _delete,
88
- } as const;
@@ -1,17 +0,0 @@
1
- import { Router } from 'express';
2
- import { authMw } from './middleware';
3
- import authRouter from './auth-router';
4
- import userRouter from './user-router';
5
-
6
-
7
- // Init
8
- const apiRouter = Router();
9
-
10
- // Add api routes
11
- apiRouter.use('/auth', authRouter);
12
- apiRouter.use('/users', authMw, userRouter);
13
-
14
-
15
- // **** Export default **** //
16
-
17
- export default apiRouter;
@@ -1,63 +0,0 @@
1
- import { Request, Response, Router } from 'express';
2
- import StatusCodes from 'http-status-codes';
3
-
4
- import authService from '@services/auth-service';
5
- import { ParamMissingError } from '@shared/errors';
6
- import envVars from 'src/shared/env-vars';
7
- import { IReq } from 'src/types/express';
8
-
9
-
10
- // **** Types **** //
11
-
12
- interface ILogin {
13
- email: string;
14
- password: string;
15
- }
16
-
17
-
18
- // **** Variables **** //
19
-
20
- // Misc
21
- const router = Router(),
22
- { OK } = StatusCodes;
23
-
24
- // Paths
25
- export const p = {
26
- login: '/login',
27
- logout: '/logout',
28
- } as const;
29
-
30
-
31
- // **** Routes **** //
32
-
33
- /**
34
- * Login a user.
35
- */
36
- router.post(p.login, async (req: IReq<ILogin>, res: Response) => {
37
- // Check email and password present
38
- const { email, password } = req.body;
39
- if (!email || !password) {
40
- throw new ParamMissingError();
41
- }
42
- // Get jwt
43
- const jwt = await authService.login(email, password);
44
- // Add jwt to cookie
45
- const { key, options } = envVars.cookieProps;
46
- res.cookie(key, jwt, options);
47
- // Return
48
- return res.status(OK).end();
49
- });
50
-
51
- /**
52
- * Logout the user.
53
- */
54
- router.get(p.logout, (_: Request, res: Response) => {
55
- const { key, options } = envVars.cookieProps;
56
- res.clearCookie(key, options);
57
- return res.status(OK).end();
58
- });
59
-
60
-
61
- // **** Export router **** //
62
-
63
- export default router;
@@ -1,80 +0,0 @@
1
- import StatusCodes from 'http-status-codes';
2
- import { Request, Response, Router } from 'express';
3
-
4
- import userService from '@services/user-service';
5
- import { ParamMissingError } from '@shared/errors';
6
- import { IReq } from 'src/types/express';
7
- import { IUser } from '@models/user-model';
8
-
9
-
10
- // **** Variables **** //
11
-
12
- // Misc
13
- const router = Router(),
14
- { CREATED, OK } = StatusCodes;
15
-
16
- // Paths
17
- export const p = {
18
- get: '/all',
19
- add: '/add',
20
- update: '/update',
21
- delete: '/delete/:id',
22
- } as const;
23
-
24
-
25
- // **** Routes **** //
26
-
27
- /**
28
- * Get all users.
29
- */
30
- router.get(p.get, async (_: Request, res: Response) => {
31
- const users = await userService.getAll();
32
- return res.status(OK).json({ users });
33
- });
34
-
35
- /**
36
- * Add one user.
37
- */
38
- router.post(p.add, async (req: IReq<{user: IUser}>, res: Response) => {
39
- const { user } = req.body;
40
- // Check param
41
- if (!user) {
42
- throw new ParamMissingError();
43
- }
44
- // Fetch data
45
- await userService.addOne(user);
46
- return res.status(CREATED).end();
47
- });
48
-
49
- /**
50
- * Update one user.
51
- */
52
- router.put(p.update, async (req: IReq<{user: IUser}>, res: Response) => {
53
- const { user } = req.body;
54
- // Check param
55
- if (!user) {
56
- throw new ParamMissingError();
57
- }
58
- // Fetch data
59
- await userService.updateOne(user);
60
- return res.status(OK).end();
61
- });
62
-
63
- /**
64
- * Delete one user.
65
- */
66
- router.delete(p.delete, async (req: Request, res: Response) => {
67
- const { id } = req.params;
68
- // Check param
69
- if (!id) {
70
- throw new ParamMissingError();
71
- }
72
- // Fetch data
73
- await userService.delete(Number(id));
74
- return res.status(OK).end();
75
- });
76
-
77
-
78
- // **** Export default **** //
79
-
80
- export default router;
@@ -1,82 +0,0 @@
1
- import cookieParser from 'cookie-parser';
2
- import morgan from 'morgan';
3
- import path from 'path';
4
- import helmet from 'helmet';
5
- import StatusCodes from 'http-status-codes';
6
- import express, { Request, Response, NextFunction } from 'express';
7
-
8
- import 'express-async-errors';
9
-
10
- import BaseRouter from './routes/api';
11
- import logger from 'jet-logger';
12
- import { CustomError } from '@shared/errors';
13
- import envVars from '@shared/env-vars';
14
-
15
-
16
- // **** Init express **** //
17
-
18
- const app = express();
19
-
20
-
21
- // **** Set basic express settings **** //
22
-
23
- app.use(express.json());
24
- app.use(express.urlencoded({extended: true}));
25
- app.use(cookieParser(envVars.cookieProps.secret));
26
-
27
- // Show routes called in console during development
28
- if (envVars.nodeEnv === 'development') {
29
- app.use(morgan('dev'));
30
- }
31
-
32
- // Security
33
- if (envVars.nodeEnv === 'production') {
34
- app.use(helmet());
35
- }
36
-
37
-
38
- // **** Add API routes **** //
39
-
40
- // Add APIs
41
- app.use('/api', BaseRouter);
42
-
43
- // Error handling
44
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
45
- app.use((err: Error | CustomError, req: Request, res: Response, _: NextFunction) => {
46
- logger.err(err, true);
47
- const status = (err instanceof CustomError ? err.HttpStatus : StatusCodes.BAD_REQUEST);
48
- return res.status(status).json({
49
- error: err.message,
50
- });
51
- });
52
-
53
-
54
- // **** Serve front-end content **** //
55
-
56
- // Set views directory (html)
57
- const viewsDir = path.join(__dirname, 'views');
58
- app.set('views', viewsDir);
59
-
60
- // Set static directory (js and css).
61
- const staticDir = path.join(__dirname, 'public');
62
- app.use(express.static(staticDir));
63
-
64
- // Nav to login pg by default
65
- app.get('/', (_: Request, res: Response) => {
66
- res.sendFile('login.html', {root: viewsDir});
67
- });
68
-
69
- // Redirect to login if not logged in.
70
- app.get('/users', (req: Request, res: Response) => {
71
- const jwt = req.signedCookies[envVars.cookieProps.key];
72
- if (!jwt) {
73
- res.redirect('/');
74
- } else {
75
- res.sendFile('users.html', {root: viewsDir});
76
- }
77
- });
78
-
79
-
80
- // **** Export default **** //
81
-
82
- export default app;
@@ -1,52 +0,0 @@
1
- import userRepo from '@repos/user-repo';
2
- import { IUser } from '@models/user-model';
3
- import { UserNotFoundError } from '@shared/errors';
4
-
5
-
6
- // **** Functions **** //
7
-
8
- /**
9
- * Get all users.
10
- */
11
- function getAll(): Promise<IUser[]> {
12
- return userRepo.getAll();
13
- }
14
-
15
- /**
16
- * Add one user.
17
- */
18
- function addOne(user: IUser): Promise<void> {
19
- return userRepo.add(user);
20
- }
21
-
22
- /**
23
- * Update one user.
24
- */
25
- async function updateOne(user: IUser): Promise<void> {
26
- const persists = await userRepo.persists(user.id);
27
- if (!persists) {
28
- throw new UserNotFoundError();
29
- }
30
- return userRepo.update(user);
31
- }
32
-
33
- /**
34
- * Delete a user by their id.
35
- */
36
- async function _delete(id: number): Promise<void> {
37
- const persists = await userRepo.persists(id);
38
- if (!persists) {
39
- throw new UserNotFoundError();
40
- }
41
- return userRepo.delete(id);
42
- }
43
-
44
-
45
- // **** Export default **** //
46
-
47
- export default {
48
- getAll,
49
- addOne,
50
- updateOne,
51
- delete: _delete,
52
- } as const;
@@ -1,20 +0,0 @@
1
- export default {
2
- nodeEnv: (process.env.NODE_ENV ?? ''),
3
- port: (process.env.PORT ?? 0),
4
- cookieProps: {
5
- key: 'ExpressGeneratorTs',
6
- secret: (process.env.COOKIE_SECRET ?? ''),
7
- options: {
8
- httpOnly: true,
9
- signed: true,
10
- path: (process.env.COOKIE_PATH ?? ''),
11
- maxAge: Number(process.env.COOKIE_EXP ?? 0),
12
- domain: (process.env.COOKIE_DOMAIN ?? ''),
13
- secure: (process.env.SECURE_COOKIE === 'true'),
14
- },
15
- },
16
- jwt: {
17
- secret: (process.env.JWT_SECRET ?? ''),
18
- exp: (process.env.COOKIE_EXP ?? ''), // exp at the same time as the cookie
19
- },
20
- } as const;
@@ -1,45 +0,0 @@
1
- import HttpStatusCodes from 'http-status-codes';
2
-
3
-
4
- export abstract class CustomError extends Error {
5
-
6
- public readonly HttpStatus = HttpStatusCodes.BAD_REQUEST;
7
-
8
- constructor(msg: string, httpStatus: number) {
9
- super(msg);
10
- this.HttpStatus = httpStatus;
11
- }
12
- }
13
-
14
-
15
- export class ParamMissingError extends CustomError {
16
-
17
- public static readonly Msg = 'One or more of the required parameters was missing.';
18
- public static readonly HttpStatus = HttpStatusCodes.BAD_REQUEST;
19
-
20
- constructor() {
21
- super(ParamMissingError.Msg, ParamMissingError.HttpStatus);
22
- }
23
- }
24
-
25
-
26
- export class UserNotFoundError extends CustomError {
27
-
28
- public static readonly Msg = 'A user with the given id does not exists in the database.';
29
- public static readonly HttpStatus = HttpStatusCodes.NOT_FOUND;
30
-
31
- constructor() {
32
- super(UserNotFoundError.Msg, UserNotFoundError.HttpStatus);
33
- }
34
- }
35
-
36
-
37
- export class UnauthorizedError extends CustomError {
38
-
39
- public static readonly Msg = 'Login failed';
40
- public static readonly HttpStatus = HttpStatusCodes.UNAUTHORIZED;
41
-
42
- constructor() {
43
- super(UnauthorizedError.Msg, UnauthorizedError.HttpStatus);
44
- }
45
- }
@@ -1,18 +0,0 @@
1
- import logger from 'jet-logger';
2
-
3
-
4
- /**
5
- * Print an error object if it's truthy. Useful for testing.
6
- */
7
- export function pErr(err?: Error): void {
8
- if (!!err) {
9
- logger.err(err);
10
- }
11
- }
12
-
13
- /**
14
- * Get a random number between 1 and 1,000,000,000,000
15
- */
16
- export function getRandomInt(): number {
17
- return Math.floor(Math.random() * 1_000_000_000_000);
18
- }
@@ -1,32 +0,0 @@
1
- import * as e from 'express';
2
- import 'express';
3
-
4
- import { ISessionUser } from '@routes/middleware';
5
-
6
-
7
- // **** Declaration Merging **** //
8
-
9
- declare module 'express' {
10
-
11
- export interface Request {
12
- signedCookies: Record<string, string>;
13
- }
14
-
15
- export interface Response {
16
- locals: {
17
- sessionUser: ISessionUser;
18
- };
19
- }
20
- }
21
-
22
-
23
- // **** Generics for Request Object **** //
24
-
25
- export interface IReq<T> extends e.Request {
26
- body: T;
27
- }
28
-
29
- export interface IReqQuery<T extends Query, U = void> extends e.Request {
30
- query: T;
31
- body?: U;
32
- }
@@ -1,47 +0,0 @@
1
- import randomString from 'randomstring';
2
- import jsonwebtoken, { JwtPayload } from 'jsonwebtoken';
3
-
4
-
5
- // **** Variables **** //
6
-
7
- // Errors
8
- const errors = {
9
- validation: 'JSON-web-token validation failed.',
10
- } as const;
11
-
12
- // Misc
13
- const secret = (process.env.JWT_SECRET || randomString.generate(100));
14
- const options = {expiresIn: process.env.COOKIE_EXP};
15
-
16
-
17
- // **** Functions **** //
18
-
19
- /**
20
- * Encrypt data and return jwt.
21
- */
22
- function sign(data: JwtPayload): Promise<string> {
23
- return new Promise((resolve, reject) => {
24
- jsonwebtoken.sign(data, secret, options, (err, token) => {
25
- return err ? reject(err) : resolve(token || '');
26
- });
27
- });
28
- }
29
-
30
- /**
31
- * Decrypt JWT and extract client data.
32
- */
33
- function decode<T>(jwt: string): Promise<T> {
34
- return new Promise((res, rej) => {
35
- jsonwebtoken.verify(jwt, secret, (err, decoded) => {
36
- return err ? rej(errors.validation) : res(decoded as T);
37
- });
38
- });
39
- }
40
-
41
-
42
- // **** Export default **** //
43
-
44
- export default {
45
- sign,
46
- decode,
47
- };