very-express 0.2.8 → 0.3.1

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 (44) hide show
  1. package/.env +3 -0
  2. package/dist/cli.js +18 -14
  3. package/dist/generators/controller.template.js +1 -1
  4. package/dist/generators/controllers.generator.js +6 -7
  5. package/dist/generators/index.d.ts +1 -1
  6. package/dist/generators/index.js +1 -1
  7. package/dist/generators/openapi.generator.js +10 -10
  8. package/dist/generators/packageJson.generator.js +6 -16
  9. package/dist/generators/role.generator.d.ts +7 -0
  10. package/dist/generators/role.generator.js +109 -0
  11. package/dist/generators/routes/oauth.generator.js +24 -4
  12. package/dist/generators/routes/routes.generator.d.ts +11 -0
  13. package/dist/generators/routes/routes.generator.js +53 -0
  14. package/dist/generators/routes/routes.template.d.ts +11 -0
  15. package/dist/generators/routes/routes.template.js +32 -0
  16. package/dist/generators/server.generator.js +2 -1
  17. package/dist/generators/server.template.js +62 -40
  18. package/dist/generators/userSchema.generator.d.ts +4 -0
  19. package/dist/generators/userSchema.generator.js +27 -0
  20. package/dist/index.js +41 -18
  21. package/dist/preprocess/jsonschemaFormat.js +5 -8
  22. package/dist/preprocess/roleSetupFile.d.ts +6 -0
  23. package/dist/preprocess/roleSetupFile.js +28 -0
  24. package/dist/templates/jsonSchema/User.json +12 -11
  25. package/dist/templates/plugins/PassportGoogle.ts +87 -0
  26. package/dist/templates/plugins/oauthVerify.ts +39 -0
  27. package/dist/templates/roles/_RoleFactory.d.ts +10 -0
  28. package/dist/templates/roles/_RoleFactory.js +17 -0
  29. package/dist/templates/roles/_RoleFactory.ts +22 -0
  30. package/dist/templates/services/mongoConn.ts +38 -0
  31. package/dist/templates/utils/common.ts +48 -0
  32. package/dist/templates/utils/logger.ts +25 -0
  33. package/dist/types/types.d.ts +14 -6
  34. package/dist/utils/common.d.ts +3 -18
  35. package/dist/utils/common.js +27 -127
  36. package/dist/utils/generator.d.ts +12 -0
  37. package/dist/utils/generator.js +72 -0
  38. package/dist/utils/index.d.ts +4 -0
  39. package/dist/utils/index.js +20 -0
  40. package/dist/utils/jsonSchema.d.ts +14 -0
  41. package/dist/utils/jsonSchema.js +84 -0
  42. package/package.json +1 -1
  43. package/tsconfig.json +2 -2
  44. package/vex.config.json +15 -4
@@ -1,35 +1,54 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
4
24
  };
5
25
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const common_1 = __importDefault(require("./../utils/common"));
26
+ const utilsGenerator = __importStar(require("./../utils/generator"));
7
27
  const importExpressSession = "import session from 'express-session';";
8
- const importPassportGoogle = "import PassportGoogle from \"./plugins/PassportGoogle.gen\"";
28
+ const importOAuthVerifyPlugin = "import oauthVerify from './plugins/oauthVerify.gen';";
29
+ const importPassportGoogle = "import PassportGoogle from './plugins/PassportGoogle.gen'";
9
30
  const importSwaggerRouter = "import SwaggerRouter from './routes/SwaggerRouter.gen';";
10
31
  const importOAuthRouter = "import OAuthRouter from './routes/OAuthRouter.gen';";
11
32
  const ConfigExpressSession = `
12
33
  const expressSessionConfig = {
13
- secret: 'your session secret',
14
- resave: false,
15
- saveUninitialized: false
34
+ secret: 'your session secret',
35
+ resave: false,
36
+ saveUninitialized: false
16
37
  }`;
17
38
  const ConfigSwaggerRouter = "const SwaggerRoute = new SwaggerRouter(); SwaggerRoute.initRoutes();";
18
39
  const ConfigOAuthRouter = "const OAuthRoute = new OAuthRouter(); OAuthRoute.initRoutes();";
19
40
  const ConfigPassportGoogle = `
20
41
  const OAuthGoogle = new PassportGoogle({
21
- strategyConfig: {
22
- // @ts-ignore
23
- verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => {
24
- return done(null, profile);
42
+ strategyConfig: {
43
+ verify: oauthVerify
25
44
  }
26
- }
27
45
  });`;
28
46
  const UseSession = "app.use(session(expressSessionConfig));";
29
47
  const UsePassportGoogle = `
30
- await OAuthGoogle.passportSerializeUser();
31
- app.use(OAuthGoogle.passport.initialize());
32
- app.use(OAuthGoogle.passport.session());`;
48
+ await OAuthGoogle.passportSerializeUser();
49
+ await OAuthGoogle.passportDeserializeUser();
50
+ app.use(OAuthGoogle.passport.initialize());
51
+ app.use(OAuthGoogle.passport.session());`;
33
52
  const UseOAuthRouter = "app.use(OAuthRoute.router);";
34
53
  const UseSwaggerRouter = "app.use(SwaggerRoute.router);";
35
54
  const UseOAuthGoogleRouter = "app.use(OAuthGoogle.router);";
@@ -39,9 +58,8 @@ function serverTemplate(options) {
39
58
  import express from 'express';
40
59
  import dotenv from 'dotenv';
41
60
  import helmet from 'helmet';
42
-
43
- import mongoConn from './services/mongoConn.gen';
44
61
  import log from './utils/logger.gen';
62
+ import mongoConn from './services/mongoConn.gen';
45
63
 
46
64
  import ApiRouter from './routes/ApiRouter.gen';
47
65
  {{Import}}
@@ -53,8 +71,8 @@ import ApiRouter from './routes/ApiRouter.gen';
53
71
  dotenv.config();
54
72
 
55
73
  const helmetConfig = {
56
- xPoweredBy: false,
57
- xDnsPrefetchControl: { allow: false },
74
+ xPoweredBy: false,
75
+ xDnsPrefetchControl: { allow: false },
58
76
  };
59
77
 
60
78
  const ApiRoute = new ApiRouter(); ApiRoute.initRoutes();
@@ -66,43 +84,47 @@ const ApiRoute = new ApiRouter(); ApiRoute.initRoutes();
66
84
  */
67
85
  async function main(): Promise<void> {
68
86
 
69
- const app = express();
70
- app.disable("x-powered-by");
71
- app.use(express.json());
72
- app.use(helmet(helmetConfig));
87
+ const app = express();
88
+ app.disable("x-powered-by");
89
+
90
+ // UseMiddleware
91
+ app.use(express.json());
92
+ app.use(helmet(helmetConfig));
93
+ app.use(mongoConn.middleware);
73
94
 
74
- // UsePlugins
75
- {{AppUse}}
95
+ // UsePlugins
96
+ {{AppUse}}
76
97
 
77
- // Routes
78
- {{AppRouter}}
98
+ // Routes
99
+ {{AppRouter}}
79
100
 
80
- app.use(ApiRoute.router);
101
+ app.use(ApiRoute.router);
81
102
 
82
- app.get('/', (req, res) => {
83
- res.send('Hello World');
84
- });
103
+ app.get('/', (req, res) => {
104
+ res.send('Hello World');
105
+ });
85
106
 
86
- app.listen(3000, () => {
87
- if(!process.env.MONGODB_URI) throw new Error('MONGODB_URI is not defined');
88
- mongoConn.connect(process.env.MONGODB_URI);
89
- log.ok(\`Server is running on : \${process.env.APP_HOST}:\${process.env.APP_PORT}\`);
90
- });
107
+ app.listen(3000, () => {
108
+ if(!process.env.MONGODB_URI) throw new Error('MONGODB_URI is not defined');
109
+ mongoConn.connect(process.env.MONGODB_URI);
110
+ log.ok(\`Server is running on : \${process.env.APP_HOST}:\${process.env.APP_PORT}\`);
111
+ });
91
112
 
92
113
  }
93
114
 
94
115
  main();
95
116
  `;
96
- const usedProvider = common_1.default.isUseOAuth(options.compilerOptions);
117
+ const usedProvider = utilsGenerator.isUseOAuth(options.compilerOptions);
97
118
  const Import = [];
98
119
  const Config = [];
99
120
  const AppUse = [];
100
121
  const AppRoute = [];
101
122
  if (usedProvider.length > 0) {
102
123
  Import.push(importExpressSession);
124
+ Import.push(importOAuthVerifyPlugin);
103
125
  Config.push(ConfigExpressSession);
104
126
  AppUse.push(UseSession);
105
- if (options.compilerOptions.enableSwagger) {
127
+ if (options.compilerOptions.app.enableSwagger) {
106
128
  Import.push(importSwaggerRouter);
107
129
  Config.push(ConfigSwaggerRouter);
108
130
  AppRoute.push(UseSwaggerRouter);
@@ -120,8 +142,8 @@ main();
120
142
  template = template.replace(/{{headerComment}}/g, options.compilerOptions.headerComment || "// generated files by very-express");
121
143
  template = template.replace(/{{Import}}/g, Import.join("\n"));
122
144
  template = template.replace(/{{Config}}/g, Config.join("\n"));
123
- template = template.replace(/{{AppUse}}/g, AppUse.join("\n "));
124
- template = template.replace(/{{AppRouter}}/g, AppRoute.join("\n "));
145
+ template = template.replace(/{{AppUse}}/g, AppUse.join("\n "));
146
+ template = template.replace(/{{AppRouter}}/g, AppRoute.join("\n "));
125
147
  return template;
126
148
  }
127
149
  exports.default = serverTemplate;
@@ -0,0 +1,4 @@
1
+ import * as types from "../types/types";
2
+ export declare function compile(options: {
3
+ compilerOptions: types.compilerOptions;
4
+ }): void;
@@ -0,0 +1,27 @@
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.compile = void 0;
7
+ const logger_1 = __importDefault(require("../utils/logger"));
8
+ const utils_1 = require("../utils");
9
+ function compile(options) {
10
+ logger_1.default.process("UserSchmea");
11
+ const schemaOutPath = `${options.compilerOptions.jsonSchemaDir}/User.json`;
12
+ const templateSchema = (0, utils_1.loadJson)(`${__dirname}/../templates/jsonSchema/User.json`);
13
+ const userSchema = (0, utils_1.loadJson)(schemaOutPath, () => {
14
+ return templateSchema;
15
+ });
16
+ Object.keys(templateSchema.properties).forEach((key) => {
17
+ var _a;
18
+ if (!userSchema.properties[key]) {
19
+ userSchema.properties[key] = templateSchema.properties[key];
20
+ if (key == "role") {
21
+ userSchema.properties[key].enum = ((_a = options.compilerOptions.useRBAC) === null || _a === void 0 ? void 0 : _a.roles) || ["user"];
22
+ }
23
+ }
24
+ });
25
+ (0, utils_1.writeFile)("UserSchmea", schemaOutPath, JSON.stringify(userSchema, null, 4));
26
+ }
27
+ exports.compile = compile;
package/dist/index.js CHANGED
@@ -31,14 +31,19 @@ const fs_1 = __importDefault(require("fs"));
31
31
  const json2mongoose_1 = __importDefault(require("json2mongoose"));
32
32
  const openapiGen = __importStar(require("./generators/openapi.generator"));
33
33
  const logger_1 = __importDefault(require("./utils/logger"));
34
- const common_1 = __importDefault(require("./utils/common"));
34
+ const utils = __importStar(require("./utils"));
35
+ const userSchemaGen = __importStar(require("./generators/userSchema.generator"));
36
+ const roleGen = __importStar(require("./generators/role.generator"));
35
37
  const controllerGen = __importStar(require("./generators/controllers.generator"));
36
- const routeGen = __importStar(require("./generators/routes.generator"));
38
+ const routeGen = __importStar(require("./generators/routes/routes.generator"));
37
39
  const serverGen = __importStar(require("./generators/server.generator"));
38
40
  const jsonschemaFormat_1 = require("./preprocess/jsonschemaFormat");
39
41
  function generate(options) {
40
42
  const openapiFile = "/openapi.gen.yaml";
43
+ const roleSourceDir = `${options.rootDir}/roles`;
44
+ const documents = [];
41
45
  const dir = {
46
+ roleDir: `${options.srcDir}/roles`,
42
47
  routeDir: `${options.srcDir}/routes`,
43
48
  middlewareDir: `${options.srcDir}/middlewares`,
44
49
  controllerDir: `${options.srcDir}/controllers`,
@@ -50,7 +55,7 @@ function generate(options) {
50
55
  };
51
56
  const routeData = [];
52
57
  if (!options.headerComment) {
53
- options.headerComment = common_1.default.getGenaratorHeaderComment();
58
+ options.headerComment = utils.getGenaratorHeaderComment();
54
59
  }
55
60
  if (!fs_1.default.existsSync(options.rootDir)) {
56
61
  fs_1.default.mkdirSync(options.rootDir);
@@ -66,10 +71,15 @@ function generate(options) {
66
71
  fs_1.default.mkdirSync(path);
67
72
  }
68
73
  });
69
- common_1.default.copyDir(`${__dirname}/templates/utils`, dir.utilsDir, options, true);
70
- common_1.default.copyDir(`${__dirname}/templates/services`, dir.serviceDir, options, true);
71
- common_1.default.copyDir(`${__dirname}/templates/plugins`, dir.pluginDir, options, true);
72
- openapiGen.compile(openapiFile, options);
74
+ utils.copyDir(`${__dirname}/templates/utils`, dir.utilsDir, options, true);
75
+ utils.copyDir(`${__dirname}/templates/services`, dir.serviceDir, options, true);
76
+ utils.copyDir(`${__dirname}/templates/plugins`, dir.pluginDir, options, true);
77
+ utils.copyDir(`${__dirname}/templates/roles`, dir.roleDir, options, true);
78
+ if (options.app.useUserSchema) {
79
+ userSchemaGen.compile({
80
+ compilerOptions: options || utils.defaultCompilerOptions,
81
+ });
82
+ }
73
83
  const files = fs_1.default.readdirSync(options.jsonSchemaDir);
74
84
  files.forEach((schemaFileName) => {
75
85
  const schemaPath = `${options.jsonSchemaDir}/${schemaFileName}`;
@@ -79,32 +89,45 @@ function generate(options) {
79
89
  return;
80
90
  }
81
91
  const jsonSchema = (0, jsonschemaFormat_1.formatJsonSchema)(schemaPath, options);
82
- const documentConfig = jsonSchema["x-documentConfig"];
83
- json2mongoose_1.default.typesGen.compileFromFile(`${schemaPath}`, `${dir.typeDir}/${documentConfig.interfaceName}.gen.ts`, options || common_1.default.defaultCompilerOptions);
84
- json2mongoose_1.default.modelsGen.compileFromFile(`${schemaPath}`, `${common_1.default.relativePath(dir.modelDir, dir.typeDir)}/${documentConfig.interfaceName}.gen`, `${dir.modelDir}/${documentConfig.interfaceName}Model.gen.ts`, options || common_1.default.defaultCompilerOptions);
85
- routeData.push({
86
- route: `/${documentConfig.documentName}`,
87
- interfaceName: documentConfig.interfaceName,
88
- controllerPath: common_1.default.relativePath(dir.routeDir, dir.controllerDir) + "/" + documentConfig.interfaceName + "Controller.gen",
92
+ documents.push({
93
+ path: schemaPath,
94
+ config: jsonSchema["x-documentConfig"],
89
95
  });
90
96
  }
91
97
  catch (err) {
92
98
  logger_1.default.error(`Processing File : ${schemaPath}\n`, err);
93
99
  }
94
100
  });
95
- openapiGen.compile(openapiFile, options || common_1.default.defaultCompilerOptions);
96
- common_1.default.copyDir(`${options.openapiDir}`, options.rootDir + "/openapi", options, true);
101
+ if (options.useRBAC && options.useRBAC.roles.length > 0) {
102
+ roleGen.compile({
103
+ collectionList: documents.map((doc) => doc.config.documentName),
104
+ roleSourceDir: roleSourceDir,
105
+ roleOutDir: dir.roleDir,
106
+ compilerOptions: options || utils.defaultCompilerOptions
107
+ });
108
+ }
109
+ openapiGen.compile(openapiFile, options || utils.defaultCompilerOptions);
110
+ utils.copyDir(`${options.openapiDir}`, options.rootDir + "/openapi", options, true);
111
+ documents.forEach((doc) => {
112
+ json2mongoose_1.default.typesGen.compileFromFile(`${doc.path}`, `${dir.typeDir}/${doc.config.interfaceName}.gen.ts`, options || utils.defaultCompilerOptions);
113
+ json2mongoose_1.default.modelsGen.compileFromFile(`${doc.path}`, `${utils.relativePath(dir.modelDir, dir.typeDir)}/${doc.config.interfaceName}.gen`, `${dir.modelDir}/${doc.config.interfaceName}Model.gen.ts`, options || utils.defaultCompilerOptions);
114
+ routeData.push({
115
+ route: `/${doc.config.documentName}`,
116
+ interfaceName: doc.config.interfaceName,
117
+ controllerPath: utils.relativePath(dir.routeDir, dir.controllerDir) + "/" + doc.config.interfaceName + "Controller.gen",
118
+ });
119
+ });
97
120
  controllerGen.compile({
98
121
  openapiFile: openapiFile,
99
122
  controllerOutDir: dir.controllerDir,
100
123
  modelDir: dir.modelDir,
101
- compilerOptions: options || common_1.default.defaultCompilerOptions
124
+ compilerOptions: options || utils.defaultCompilerOptions
102
125
  });
103
126
  routeGen.compile({
104
127
  routesArr: routeData,
105
128
  openapiFile: openapiFile,
106
129
  routesDir: dir.routeDir,
107
- compilerOptions: options || common_1.default.defaultCompilerOptions
130
+ compilerOptions: options || utils.defaultCompilerOptions
108
131
  });
109
132
  serverGen.compile(options);
110
133
  }
@@ -27,15 +27,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.formatJsonSchema = void 0;
30
- const fs_1 = __importDefault(require("fs"));
31
30
  const types = __importStar(require("../types/types"));
32
- const common = __importStar(require("../utils/common"));
31
+ const utilsJsonSchema = __importStar(require("../utils/jsonSchema"));
33
32
  const logger_1 = __importDefault(require("../utils/logger"));
33
+ const utils_1 = require("../utils");
34
34
  function formatJsonSchema(jsonSchemaPath, compilerOptions) {
35
- const jsonSchema = common.loadJsonSchema(jsonSchemaPath);
36
- if (jsonSchema == undefined) {
37
- logger_1.default.error("formatJsonSchema : error at loadJsonSchema()");
38
- }
35
+ const jsonSchema = utilsJsonSchema.loadJsonSchema(jsonSchemaPath);
39
36
  if (!jsonSchema["x-documentConfig"]) {
40
37
  logger_1.default.error(`formatJsonSchema : x-documentConfig not found in ${jsonSchemaPath}`);
41
38
  }
@@ -52,11 +49,11 @@ function formatJsonSchema(jsonSchemaPath, compilerOptions) {
52
49
  if (typeof jsonSchema.properties !== "object") {
53
50
  logger_1.default.error(`properties is invalid in ${jsonSchemaPath}`);
54
51
  }
55
- if (compilerOptions.useObjectID) {
52
+ if (compilerOptions.app.useObjectID) {
56
53
  checkField_id(jsonSchema, jsonSchemaPath);
57
54
  }
58
55
  jsonSchema.required = getRequiredArrStr(jsonSchema, jsonSchemaPath);
59
- fs_1.default.writeFileSync(jsonSchemaPath, JSON.stringify(jsonSchema, null, 4));
56
+ (0, utils_1.writeFile)("Format JsonSchema", jsonSchemaPath, JSON.stringify(jsonSchema, null, 4));
60
57
  return jsonSchema;
61
58
  }
62
59
  exports.formatJsonSchema = formatJsonSchema;
@@ -0,0 +1,6 @@
1
+ import * as types from "../types/types";
2
+ export declare function roleSetupFile(options: {
3
+ collectionList: string[];
4
+ roleSetupDir: string;
5
+ compilerOptions: types.compilerOptions;
6
+ }): void;
@@ -0,0 +1,28 @@
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.roleSetupFile = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const utils_1 = require("../utils");
9
+ const logger_1 = __importDefault(require("../utils/logger"));
10
+ function roleSetupFile(options) {
11
+ var _a;
12
+ const actionArray = ["create", "search", "read", "update", "delete"];
13
+ (_a = options.compilerOptions.useRBAC) === null || _a === void 0 ? void 0 : _a.roles.forEach((role) => {
14
+ logger_1.default.process(`RBAC Setting : ${role}`);
15
+ const roleFilePath = `${options.roleSetupDir}/${role}.json`;
16
+ if (!fs_1.default.existsSync(roleFilePath)) {
17
+ (0, utils_1.writeFile)(`Role Setup : ${role}`, roleFilePath, JSON.stringify({}, null, 4));
18
+ }
19
+ const content = (0, utils_1.loadJson)(roleFilePath);
20
+ options.collectionList.forEach(collectionName => {
21
+ if (!content[collectionName]) {
22
+ content[collectionName] = actionArray;
23
+ }
24
+ });
25
+ (0, utils_1.writeFile)(`RBAC Setting : ${roleFilePath}`, roleFilePath, JSON.stringify(content, null, 4));
26
+ });
27
+ }
28
+ exports.roleSetupFile = roleSetupFile;
@@ -15,24 +15,25 @@
15
15
  "type": "string",
16
16
  "index": true
17
17
  },
18
+ "role":{
19
+ "type": "string",
20
+ "enum": ["user"],
21
+ "default": "user",
22
+ "required": true
23
+ },
18
24
  "authProvider": {
19
25
  "type": "string"
20
26
  },
27
+ "authId": {
28
+ "type": "string",
29
+ "index": true
30
+ },
21
31
  "email": {
22
32
  "type": "string",
23
33
  "format": "email",
24
34
  "index": true,
25
35
  "required": true
26
36
  },
27
- "emailVerified": {
28
- "type": "boolean",
29
- "required": true,
30
- "default": false
31
- },
32
- "authId": {
33
- "type": "string",
34
- "index": true
35
- },
36
37
  "name": {
37
38
  "type": "string",
38
39
  "maxLength": 64,
@@ -40,11 +41,11 @@
40
41
  },
41
42
  "locale": {
42
43
  "type": "string",
43
- "maxLength": 8,
44
- "required": true
44
+ "maxLength": 8
45
45
  },
46
46
  "isActive": {
47
47
  "type": "boolean",
48
+ "default": true,
48
49
  "required": true
49
50
  }
50
51
  }
@@ -0,0 +1,87 @@
1
+ // {{headerComment}}
2
+
3
+ import { Router } from "express";
4
+ import passport, { PassportStatic, Profile } from "passport";
5
+ import { AuthenticateOptionsGoogle, Strategy as GoogleStrategy, StrategyOptions, VerifyCallback } from "passport-google-oauth20";
6
+ import log from "../utils/logger.gen";
7
+ import { UserModel } from "../models/UserModel.gen";
8
+
9
+ export type { Profile };
10
+
11
+ export interface passportGoogleConfig {
12
+ strategyConfig: {
13
+ options?: StrategyOptions,
14
+ verify: (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => void
15
+ },
16
+ authenticateOptionsGoogle?: AuthenticateOptionsGoogle,
17
+ }
18
+
19
+ /** Provides a router and passport instance for Google OAuth */
20
+ export default class PassportGoogle {
21
+
22
+ private config: passportGoogleConfig;
23
+ public router: Router = Router();
24
+ public passport: PassportStatic = passport;
25
+
26
+ constructor(config: passportGoogleConfig ) {
27
+
28
+ this.config = config;
29
+
30
+ this.passport.use(new GoogleStrategy(
31
+ this.config.strategyConfig.options || {
32
+ clientID: process.env.OAUTH_GOOGLE_CLIENTID || "",
33
+ clientSecret: process.env.OAUTH_GOOGLE_CLIENTSECRET || "",
34
+ callbackURL: `${process.env.APP_HOST}:${process.env.APP_PORT}/auth/google/callback`,
35
+ },
36
+ this.config.strategyConfig.verify
37
+ ));
38
+
39
+ // redirect to google login
40
+ this.router.get("/auth/google",
41
+ this.passport.authenticate("google", this.config.authenticateOptionsGoogle || { scope: ["profile", "email"] })
42
+ );
43
+
44
+ // back from google login
45
+ this.router.get("/auth/google/callback",
46
+ this.passport.authenticate("google", { failureRedirect: "/login" }),
47
+ (req, res) => {
48
+ res.redirect("/profile");
49
+ }
50
+ );
51
+ }
52
+
53
+ public passportSerializeUser() {
54
+ this.passport.serializeUser(async (user, done) => {
55
+ log.info("passportGoogle().serializeUser", user);
56
+ // Here, you can choose what data to store in the session.
57
+ // This data will be used in `deserializeUser` to retrieve the full user object.
58
+ // This is typically just the user's ID.
59
+
60
+ // store role in session for access control
61
+ const DbUser = await UserModel.findById(user);
62
+ if (DbUser) {
63
+ done(null, DbUser);
64
+ } else {
65
+ done(new Error("User not found"));
66
+ }
67
+
68
+ done(null, user);
69
+ });
70
+ }
71
+
72
+ public async passportDeserializeUser() {
73
+ this.passport.deserializeUser(async (id, done) => {
74
+ log.info("passportGoogle().deserializeUser", id);
75
+
76
+ const user = await UserModel.findById(id);
77
+ if (user) {
78
+ done(null, user);
79
+ }
80
+ else {
81
+ done(new Error("User not found"));
82
+ }
83
+
84
+ });
85
+ }
86
+
87
+ }
@@ -0,0 +1,39 @@
1
+ // {{headerComment}}
2
+
3
+ import { Profile } from "passport";
4
+ import { UserModel } from "../models/UserModel.gen";
5
+
6
+ interface IProfile extends Profile {
7
+ [key: string]: any;
8
+ }
9
+
10
+ export default async function oauthVerify(accessToken: string, refreshToken: string, profile: IProfile, done: (error: any, user?: any) => void) : Promise<void> {
11
+ try {
12
+
13
+ // find or create user
14
+ const existingUser = await UserModel.findOne({ email: profile.emails?.[0].value });
15
+
16
+ if( existingUser ){
17
+ // log.info('OAuthVerify ExistingUser');
18
+ return done(null, existingUser);
19
+ }
20
+ else {
21
+ // log.info('OAuthVerify NewUser');
22
+ const newUser = new UserModel({
23
+ authProvider: profile.provider,
24
+ email: profile.emails?.[0].value || "",
25
+ authId: profile.id,
26
+ name: profile.displayName,
27
+ familyName: profile.name?.familyName,
28
+ givenName: profile.name?.givenName,
29
+ isActive: true,
30
+ locale: profile._json?.locale,
31
+ });
32
+ newUser.save();
33
+ return done(null, newUser);
34
+ }
35
+ }
36
+ catch(err) {
37
+ return done(err);
38
+ }
39
+ }
@@ -0,0 +1,10 @@
1
+ export type accessAction = "create" | "read" | "update" | "delete" | "search";
2
+ export declare const accessActionArr: accessAction[];
3
+ export interface accessControl<T = accessAction> {
4
+ [key: string]: T[];
5
+ }
6
+ export declare class _RoleFactory<T = accessAction> {
7
+ private accessControl;
8
+ constructor(accessControl: accessControl<T>);
9
+ checkAccess(document: string, access: string): boolean;
10
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._RoleFactory = exports.accessActionArr = void 0;
4
+ exports.accessActionArr = ["create", "read", "update", "delete", "search"];
5
+ class _RoleFactory {
6
+ constructor(accessControl) {
7
+ this.accessControl = {};
8
+ this.accessControl = accessControl;
9
+ }
10
+ checkAccess(document, access) {
11
+ if (this.accessControl[document]) {
12
+ return this.accessControl[document].includes(access);
13
+ }
14
+ return false;
15
+ }
16
+ }
17
+ exports._RoleFactory = _RoleFactory;
@@ -0,0 +1,22 @@
1
+ export type accessAction = "create" | "read" | "update" | "delete" | "search";
2
+ export const accessActionArr: accessAction[] = ["create", "read", "update", "delete", "search"];
3
+
4
+ export interface accessControl< T = accessAction > {
5
+ [key:string]: T[]
6
+ }
7
+
8
+ export class _RoleFactory<T = accessAction> {
9
+ private accessControl: accessControl<T> = {};
10
+
11
+ constructor(accessControl: accessControl<T>) {
12
+ this.accessControl = accessControl;
13
+ }
14
+
15
+ public checkAccess(document: string, access: string): boolean {
16
+ if (this.accessControl[document]) {
17
+ return this.accessControl[document].includes(access as T);
18
+ }
19
+ return false;
20
+ }
21
+
22
+ }
@@ -0,0 +1,38 @@
1
+ // {{headerComment}}
2
+
3
+ import mongoose from "mongoose";
4
+ import { Request, Response, NextFunction } from "express";
5
+ import log from "../utils/logger.gen";
6
+
7
+ export function connect(mongoUrl:string): mongoose.Connection {
8
+ mongoose.connect(mongoUrl, {
9
+ autoCreate: true,
10
+ });
11
+
12
+ mongoose.connection.on("open", () => {
13
+ log.ok("MongoDB Connection open : " + mongoUrl);
14
+ });
15
+
16
+ mongoose.connection.on("error", (err: any) => {
17
+ log.error("MongoDB Connection error:", err.message, err);
18
+ });
19
+
20
+ return mongoose.connection;
21
+ }
22
+
23
+ export function middleware(req: Request, res: Response, next: NextFunction) {
24
+ const db = mongoose.connection;
25
+ if (db.readyState !== 1) {
26
+ return res.status(503).json({ error: "Database connection issue" });
27
+ }
28
+ else {
29
+ next();
30
+ }
31
+ }
32
+
33
+ const mongo = {
34
+ connect,
35
+ middleware
36
+ };
37
+
38
+ export default mongo;