express-generator-typescript 2.3.7 → 2.4.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.
Files changed (64) hide show
  1. package/README.md +5 -34
  2. package/bin/cli.js +22 -7
  3. package/lib/cli.js +22 -7
  4. package/lib/express-generator-typescript.js +38 -28
  5. package/lib/project-files/spec/tests/users.spec.ts +9 -20
  6. package/lib/project-files/src/models/User.ts +50 -53
  7. package/lib/project-files/src/repos/database.json +1 -1
  8. package/lib/project-files/src/routes/api.ts +1 -24
  9. package/lib/project-files/src/routes/constants/Paths.ts +0 -5
  10. package/lib/project-files/src/server.ts +4 -9
  11. package/lib/project-files/src/views/users.html +0 -5
  12. package/lib/project-files-auth/.eslintignore +1 -0
  13. package/lib/project-files-auth/.eslintrc.json +44 -0
  14. package/lib/project-files-auth/README.md +43 -0
  15. package/lib/project-files-auth/build.ts +64 -0
  16. package/lib/project-files-auth/env/development.env +24 -0
  17. package/lib/project-files-auth/env/production.env +25 -0
  18. package/lib/project-files-auth/env/test.env +24 -0
  19. package/lib/project-files-auth/gitignore +3 -0
  20. package/lib/project-files-auth/package.json +70 -0
  21. package/lib/project-files-auth/spec/index.ts +77 -0
  22. package/lib/project-files-auth/spec/nodemon.json +6 -0
  23. package/lib/project-files-auth/spec/support/jasmine.json +11 -0
  24. package/lib/{project-files → project-files-auth}/spec/support/login.ts +1 -1
  25. package/lib/project-files-auth/spec/support/types.ts +1 -0
  26. package/lib/{project-files → project-files-auth}/spec/tests/auth.spec.ts +2 -2
  27. package/lib/project-files-auth/spec/tests/users.spec.ts +224 -0
  28. package/lib/project-files-auth/spec/types/supertest/index.d.ts +14 -0
  29. package/lib/project-files-auth/src/constants/EnvVars.ts +28 -0
  30. package/lib/project-files-auth/src/constants/HttpStatusCodes.ts +386 -0
  31. package/lib/project-files-auth/src/constants/misc.ts +5 -0
  32. package/lib/project-files-auth/src/index.ts +13 -0
  33. package/lib/project-files-auth/src/models/User.ts +85 -0
  34. package/lib/project-files-auth/src/other/classes.ts +17 -0
  35. package/lib/project-files-auth/src/other/types.ts +4 -0
  36. package/lib/project-files-auth/src/pre-start.ts +37 -0
  37. package/lib/project-files-auth/src/public/scripts/http.js +24 -0
  38. package/lib/project-files-auth/src/public/scripts/users.js +164 -0
  39. package/lib/project-files-auth/src/public/stylesheets/users.css +50 -0
  40. package/lib/project-files-auth/src/repos/MockOrm.ts +42 -0
  41. package/lib/project-files-auth/src/repos/UserRepo.ts +88 -0
  42. package/lib/project-files-auth/src/repos/database.json +1 -0
  43. package/lib/project-files-auth/src/routes/UserRoutes.ts +53 -0
  44. package/lib/project-files-auth/src/routes/api.ts +75 -0
  45. package/lib/project-files-auth/src/routes/constants/FullPaths.ts +40 -0
  46. package/lib/project-files-auth/src/routes/constants/Paths.ts +28 -0
  47. package/lib/project-files-auth/src/routes/types/express/index.d.ts +11 -0
  48. package/lib/project-files-auth/src/routes/types/express/misc.ts +16 -0
  49. package/lib/project-files-auth/src/routes/types/types.ts +22 -0
  50. package/lib/project-files-auth/src/server.ts +96 -0
  51. package/lib/project-files-auth/src/services/AuthService.ts +56 -0
  52. package/lib/project-files-auth/src/services/UserService.ts +66 -0
  53. package/lib/project-files-auth/src/util/PwdUtil.ts +39 -0
  54. package/lib/project-files-auth/src/util/SessionUtil.ts +92 -0
  55. package/lib/project-files-auth/src/util/misc.ts +22 -0
  56. package/lib/project-files-auth/src/views/users.html +42 -0
  57. package/lib/project-files-auth/tsconfig.json +83 -0
  58. package/lib/project-files-auth/tsconfig.prod.json +12 -0
  59. package/package.json +1 -1
  60. /package/lib/{project-files → project-files-auth}/src/public/scripts/login.js +0 -0
  61. /package/lib/{project-files → project-files-auth}/src/public/stylesheets/login.css +0 -0
  62. /package/lib/{project-files → project-files-auth}/src/routes/AuthRoutes.ts +0 -0
  63. /package/lib/{project-files → project-files-auth}/src/routes/middleware/adminMw.ts +0 -0
  64. /package/lib/{project-files → project-files-auth}/src/views/login.html +0 -0
@@ -0,0 +1,56 @@
1
+ import UserRepo from '@src/repos/UserRepo';
2
+
3
+ import PwdUtil from '@src/util/PwdUtil';
4
+ import { tick } from '@src/util/misc';
5
+
6
+ import HttpStatusCodes from '@src/constants/HttpStatusCodes';
7
+ import { RouteError } from '@src/other/classes';
8
+ import { IUser } from '@src/models/User';
9
+
10
+
11
+ // **** Variables **** //
12
+
13
+ // Errors
14
+ export const Errors = {
15
+ Unauth: 'Unauthorized',
16
+ EmailNotFound(email: string) {
17
+ return `User with email "${email}" not found`;
18
+ },
19
+ } as const;
20
+
21
+
22
+ // **** Functions **** //
23
+
24
+ /**
25
+ * Login a user.
26
+ */
27
+ async function login(email: string, password: string): Promise<IUser> {
28
+ // Fetch user
29
+ const user = await UserRepo.getOne(email);
30
+ if (!user) {
31
+ throw new RouteError(
32
+ HttpStatusCodes.UNAUTHORIZED,
33
+ Errors.EmailNotFound(email),
34
+ );
35
+ }
36
+ // Check password
37
+ const hash = (user.pwdHash ?? ''),
38
+ pwdPassed = await PwdUtil.compare(password, hash);
39
+ if (!pwdPassed) {
40
+ // If password failed, wait 500ms this will increase security
41
+ await tick(500);
42
+ throw new RouteError(
43
+ HttpStatusCodes.UNAUTHORIZED,
44
+ Errors.Unauth,
45
+ );
46
+ }
47
+ // Return
48
+ return user;
49
+ }
50
+
51
+
52
+ // **** Export default **** //
53
+
54
+ export default {
55
+ login,
56
+ } as const;
@@ -0,0 +1,66 @@
1
+ import UserRepo from '@src/repos/UserRepo';
2
+ import { IUser } from '@src/models/User';
3
+ import { RouteError } from '@src/other/classes';
4
+ import HttpStatusCodes from '@src/constants/HttpStatusCodes';
5
+
6
+
7
+ // **** Variables **** //
8
+
9
+ export const USER_NOT_FOUND_ERR = 'User not found';
10
+
11
+
12
+ // **** Functions **** //
13
+
14
+ /**
15
+ * Get all users.
16
+ */
17
+ function getAll(): Promise<IUser[]> {
18
+ return UserRepo.getAll();
19
+ }
20
+
21
+ /**
22
+ * Add one user.
23
+ */
24
+ function addOne(user: IUser): Promise<void> {
25
+ return UserRepo.add(user);
26
+ }
27
+
28
+ /**
29
+ * Update one user.
30
+ */
31
+ async function updateOne(user: IUser): Promise<void> {
32
+ const persists = await UserRepo.persists(user.id);
33
+ if (!persists) {
34
+ throw new RouteError(
35
+ HttpStatusCodes.NOT_FOUND,
36
+ USER_NOT_FOUND_ERR,
37
+ );
38
+ }
39
+ // Return user
40
+ return UserRepo.update(user);
41
+ }
42
+
43
+ /**
44
+ * Delete a user by their id.
45
+ */
46
+ async function _delete(id: number): Promise<void> {
47
+ const persists = await UserRepo.persists(id);
48
+ if (!persists) {
49
+ throw new RouteError(
50
+ HttpStatusCodes.NOT_FOUND,
51
+ USER_NOT_FOUND_ERR,
52
+ );
53
+ }
54
+ // Delete user
55
+ return UserRepo.delete(id);
56
+ }
57
+
58
+
59
+ // **** Export default **** //
60
+
61
+ export default {
62
+ getAll,
63
+ addOne,
64
+ updateOne,
65
+ delete: _delete,
66
+ } as const;
@@ -0,0 +1,39 @@
1
+ import bcrypt from 'bcrypt';
2
+
3
+
4
+ // **** Variables **** //
5
+
6
+ const SALT_ROUNDS = 12;
7
+
8
+
9
+ // **** Functions **** //
10
+
11
+ /**
12
+ * Get a hash from the password.
13
+ */
14
+ function getHash(pwd: string): Promise<string> {
15
+ return bcrypt.hash(pwd, SALT_ROUNDS);
16
+ }
17
+
18
+ /**
19
+ * Useful for testing.
20
+ */
21
+ function hashSync(pwd: string): string {
22
+ return bcrypt.hashSync(pwd, SALT_ROUNDS);
23
+ }
24
+
25
+ /**
26
+ * See if a password passes the hash.
27
+ */
28
+ function compare(pwd: string, hash: string): Promise<boolean> {
29
+ return bcrypt.compare(pwd, hash);
30
+ }
31
+
32
+
33
+ // **** Export Default **** //
34
+
35
+ export default {
36
+ getHash,
37
+ hashSync,
38
+ compare,
39
+ } as const;
@@ -0,0 +1,92 @@
1
+ import { Request, Response } from 'express';
2
+
3
+ import HttpStatusCodes from '@src/constants/HttpStatusCodes';
4
+ import { RouteError } from '@src/other/classes';
5
+ import jsonwebtoken from 'jsonwebtoken';
6
+
7
+ import EnvVars from '../constants/EnvVars';
8
+
9
+
10
+ // **** Variables **** //
11
+
12
+ // Errors
13
+ const Errors = {
14
+ ParamFalsey: 'Param is falsey',
15
+ Validation: 'JSON-web-token validation failed.',
16
+ } as const;
17
+
18
+ // Options
19
+ const Options = {
20
+ expiresIn: EnvVars.Jwt.Exp,
21
+ };
22
+
23
+
24
+ // **** Functions **** //
25
+
26
+ /**
27
+ * Get session data from request object (i.e. ISessionUser)
28
+ */
29
+ function getSessionData<T>(req: Request): Promise<string | T | undefined> {
30
+ const { Key } = EnvVars.CookieProps,
31
+ jwt = req.signedCookies[Key];
32
+ return _decode(jwt);
33
+ }
34
+
35
+ /**
36
+ * Add a JWT to the response
37
+ */
38
+ async function addSessionData(
39
+ res: Response,
40
+ data: string | object,
41
+ ): Promise<Response> {
42
+ if (!res || !data) {
43
+ throw new RouteError(HttpStatusCodes.BAD_REQUEST, Errors.ParamFalsey);
44
+ }
45
+ // Setup JWT
46
+ const jwt = await _sign(data),
47
+ { Key, Options } = EnvVars.CookieProps;
48
+ // Return
49
+ return res.cookie(Key, jwt, Options);
50
+ }
51
+
52
+ /**
53
+ * Remove cookie
54
+ */
55
+ function clearCookie(res: Response): Response {
56
+ const { Key, Options } = EnvVars.CookieProps;
57
+ return res.clearCookie(Key, Options);
58
+ }
59
+
60
+
61
+ // **** Helper Functions **** //
62
+
63
+ /**
64
+ * Encrypt data and return jwt.
65
+ */
66
+ function _sign(data: string | object | Buffer): Promise<string> {
67
+ return new Promise((res, rej) => {
68
+ jsonwebtoken.sign(data, EnvVars.Jwt.Secret, Options, (err, token) => {
69
+ return err ? rej(err) : res(token || '');
70
+ });
71
+ });
72
+ }
73
+
74
+ /**
75
+ * Decrypt JWT and extract client data.
76
+ */
77
+ function _decode<T>(jwt: string): Promise<string | undefined | T> {
78
+ return new Promise((res, rej) => {
79
+ jsonwebtoken.verify(jwt, EnvVars.Jwt.Secret, (err, decoded) => {
80
+ return err ? rej(Errors.Validation) : res(decoded as T);
81
+ });
82
+ });
83
+ }
84
+
85
+
86
+ // **** Export default **** //
87
+
88
+ export default {
89
+ addSessionData,
90
+ getSessionData,
91
+ clearCookie,
92
+ } as const;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Miscellaneous shared functions go here.
3
+ */
4
+
5
+
6
+ /**
7
+ * Get a random number between 1 and 1,000,000,000,000
8
+ */
9
+ export function getRandomInt(): number {
10
+ return Math.floor(Math.random() * 1_000_000_000_000);
11
+ }
12
+
13
+ /**
14
+ * Wait for a certain number of milliseconds.
15
+ */
16
+ export function tick(milliseconds: number): Promise<void> {
17
+ return new Promise((resolve) => {
18
+ setTimeout(() => {
19
+ resolve();
20
+ }, milliseconds);
21
+ });
22
+ }
@@ -0,0 +1,42 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>Users</title>
6
+ <link rel="stylesheet" type="text/css" href="/stylesheets/users.css" />
7
+ </head>
8
+ <body>
9
+
10
+ <!-- Add Users -->
11
+ <div class="users-column add-user-col">
12
+ <div class="column-header">
13
+ Add User:
14
+ </div>
15
+ <div>
16
+ <input id="name-input" placeholder="Name" />
17
+ </div>
18
+ <div>
19
+ <input id="email-input" placeholder="Email" />
20
+ </div>
21
+ <div>
22
+ <button id="add-user-btn">
23
+ Add
24
+ </button>
25
+ </div>
26
+ <div>
27
+ <button id="logout-btn">
28
+ Logout
29
+ </button>
30
+ </div>
31
+ </div>
32
+
33
+ <!-- Display Users -->
34
+ <div class="users-column">
35
+ <div class="column-header">Users:</div>
36
+ <div id="all-users-anchor"></div>
37
+ </div>
38
+
39
+ </body>
40
+ <script src="scripts/http.js"></script>
41
+ <script src="scripts/users.js"></script>
42
+ </html>
@@ -0,0 +1,83 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Basic Options */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
8
+ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
9
+ // "lib": [], /* Specify library files to be included in the compilation. */
10
+ // "allowJs": true, /* Allow javascript files to be compiled. */
11
+ // "checkJs": true, /* Report errors in .js files. */
12
+ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
13
+ // "declaration": true, /* Generates corresponding '.d.ts' file. */
14
+ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15
+ // "sourceMap": true, /* Generates corresponding '.map' file. */
16
+ // "outFile": "./", /* Concatenate and emit output to single file. */
17
+ "outDir": "dist", /* Redirect output structure to the directory. */
18
+ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
19
+ // "composite": true, /* Enable project compilation */
20
+ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21
+ // "removeComments": true, /* Do not emit comments to output. */
22
+ // "noEmit": true, /* Do not emit outputs. */
23
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
24
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
26
+
27
+ /* Strict Type-Checking Options */
28
+ "strict": true, /* Enable all strict type-checking options. */
29
+ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
30
+ // "strictNullChecks": true, /* Enable strict null checks. */
31
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
32
+ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36
+
37
+ /* Additional Checks */
38
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
39
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
40
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42
+
43
+ /* Module Resolution Options */
44
+ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
45
+ "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
46
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
47
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
48
+ // "typeRoots": [], /* List of folders to include type definitions from. */
49
+ // "types": [], /* Type declaration files to be included in compilation. */
50
+ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
51
+ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
52
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
53
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
54
+
55
+ /* Source Map Options */
56
+ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
57
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
59
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
60
+
61
+ /* Experimental Options */
62
+ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
63
+ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
64
+
65
+ /* Advanced Options */
66
+ "skipLibCheck": true, /* Skip type checking of declaration files. */
67
+ "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
68
+ "paths": {
69
+ "@src/*": [
70
+ "src/*"
71
+ ],
72
+ },
73
+ "useUnknownInCatchVariables": false
74
+ },
75
+ "include": [
76
+ "src/**/*.ts",
77
+ "spec/**/*.ts",
78
+ "build.ts"
79
+ ],
80
+ "exclude": [
81
+ "src/public/"
82
+ ]
83
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "sourceMap": false,
5
+ "removeComments": true
6
+ },
7
+ "exclude": [
8
+ "spec",
9
+ "src/public/",
10
+ "build.ts"
11
+ ]
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-generator-typescript",
3
- "version": "2.3.7",
3
+ "version": "2.4.0",
4
4
  "description": "Generate new Express applications similar to express-generate which but sets it up to use TypeScript instead",
5
5
  "scripts": {
6
6
  "express-generator-typescript": "node bin/cli.js",