very-express 0.2.7 → 0.3.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/.env +3 -0
- package/dist/cli.js +18 -10
- package/dist/generators/controller.template.js +10 -3
- package/dist/generators/controllers.generator.js +6 -7
- package/dist/generators/index.d.ts +1 -1
- package/dist/generators/index.js +1 -1
- package/dist/generators/openapi.generator.js +20 -12
- package/dist/generators/packageJson.generator.js +6 -16
- package/dist/generators/role.generator.d.ts +7 -0
- package/dist/generators/role.generator.js +109 -0
- package/dist/generators/routes/oauth.generator.js +24 -4
- package/dist/generators/routes/routes.generator.d.ts +11 -0
- package/dist/generators/routes/routes.generator.js +53 -0
- package/dist/generators/routes/routes.template.d.ts +11 -0
- package/dist/generators/routes/routes.template.js +32 -0
- package/dist/generators/server.generator.js +2 -1
- package/dist/generators/server.template.js +62 -40
- package/dist/generators/userSchema.generator.d.ts +4 -0
- package/dist/generators/userSchema.generator.js +27 -0
- package/dist/index.js +43 -19
- package/dist/preprocess/jsonschemaFormat.d.ts +1 -1
- package/dist/preprocess/jsonschemaFormat.js +8 -9
- package/dist/preprocess/roleSetupFile.d.ts +6 -0
- package/dist/preprocess/roleSetupFile.js +28 -0
- package/dist/templates/jsonSchema/User.json +12 -11
- package/dist/templates/plugins/PassportGoogle.ts +87 -0
- package/dist/templates/plugins/oauthVerify.ts +39 -0
- package/dist/templates/roles/_RoleFactory.d.ts +10 -0
- package/dist/templates/roles/_RoleFactory.js +17 -0
- package/dist/templates/roles/_RoleFactory.ts +22 -0
- package/dist/templates/services/mongoConn.ts +38 -0
- package/dist/templates/utils/common.ts +48 -0
- package/dist/templates/utils/logger.ts +25 -0
- package/dist/types/types.d.ts +14 -4
- package/dist/utils/common.d.ts +3 -18
- package/dist/utils/common.js +27 -125
- package/dist/utils/generator.d.ts +12 -0
- package/dist/utils/generator.js +72 -0
- package/dist/utils/index.d.ts +4 -0
- package/dist/utils/index.js +20 -0
- package/dist/utils/jsonSchema.d.ts +14 -0
- package/dist/utils/jsonSchema.js +84 -0
- package/package.json +1 -1
- package/tsconfig.json +2 -2
- package/vex.config.json +15 -2
|
@@ -1,35 +1,54 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var
|
|
3
|
-
|
|
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
|
|
26
|
+
const utilsGenerator = __importStar(require("./../utils/generator"));
|
|
7
27
|
const importExpressSession = "import session from 'express-session';";
|
|
8
|
-
const
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
|
|
22
|
-
|
|
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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
-
|
|
57
|
-
|
|
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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
-
|
|
75
|
-
|
|
95
|
+
// UsePlugins
|
|
96
|
+
{{AppUse}}
|
|
76
97
|
|
|
77
|
-
|
|
78
|
-
|
|
98
|
+
// Routes
|
|
99
|
+
{{AppRouter}}
|
|
79
100
|
|
|
80
|
-
|
|
101
|
+
app.use(ApiRoute.router);
|
|
81
102
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
103
|
+
app.get('/', (req, res) => {
|
|
104
|
+
res.send('Hello World');
|
|
105
|
+
});
|
|
85
106
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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 =
|
|
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,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
|
|
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 =
|
|
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,16 @@ function generate(options) {
|
|
|
66
71
|
fs_1.default.mkdirSync(path);
|
|
67
72
|
}
|
|
68
73
|
});
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
+
utils.copyDir(`${__dirname}/templates/middleware`, dir.middlewareDir, options, true);
|
|
79
|
+
if (options.app.useUserSchema) {
|
|
80
|
+
userSchemaGen.compile({
|
|
81
|
+
compilerOptions: options || utils.defaultCompilerOptions,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
73
84
|
const files = fs_1.default.readdirSync(options.jsonSchemaDir);
|
|
74
85
|
files.forEach((schemaFileName) => {
|
|
75
86
|
const schemaPath = `${options.jsonSchemaDir}/${schemaFileName}`;
|
|
@@ -78,33 +89,46 @@ function generate(options) {
|
|
|
78
89
|
logger_1.default.warn(`Skipping Non Json File : ${schemaPath}`);
|
|
79
90
|
return;
|
|
80
91
|
}
|
|
81
|
-
const jsonSchema = (0, jsonschemaFormat_1.formatJsonSchema)(schemaPath);
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
+
const jsonSchema = (0, jsonschemaFormat_1.formatJsonSchema)(schemaPath, options);
|
|
93
|
+
documents.push({
|
|
94
|
+
path: schemaPath,
|
|
95
|
+
config: jsonSchema["x-documentConfig"],
|
|
89
96
|
});
|
|
90
97
|
}
|
|
91
98
|
catch (err) {
|
|
92
99
|
logger_1.default.error(`Processing File : ${schemaPath}\n`, err);
|
|
93
100
|
}
|
|
94
101
|
});
|
|
95
|
-
|
|
96
|
-
|
|
102
|
+
if (options.useRBAC && options.useRBAC.roles.length > 0) {
|
|
103
|
+
roleGen.compile({
|
|
104
|
+
collectionList: documents.map((doc) => doc.config.documentName),
|
|
105
|
+
roleSourceDir: roleSourceDir,
|
|
106
|
+
roleOutDir: dir.roleDir,
|
|
107
|
+
compilerOptions: options || utils.defaultCompilerOptions
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
openapiGen.compile(openapiFile, options || utils.defaultCompilerOptions);
|
|
111
|
+
utils.copyDir(`${options.openapiDir}`, options.rootDir + "/openapi", options, true);
|
|
112
|
+
documents.forEach((doc) => {
|
|
113
|
+
json2mongoose_1.default.typesGen.compileFromFile(`${doc.path}`, `${dir.typeDir}/${doc.config.interfaceName}.gen.ts`, options || utils.defaultCompilerOptions);
|
|
114
|
+
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);
|
|
115
|
+
routeData.push({
|
|
116
|
+
route: `/${doc.config.documentName}`,
|
|
117
|
+
interfaceName: doc.config.interfaceName,
|
|
118
|
+
controllerPath: utils.relativePath(dir.routeDir, dir.controllerDir) + "/" + doc.config.interfaceName + "Controller.gen",
|
|
119
|
+
});
|
|
120
|
+
});
|
|
97
121
|
controllerGen.compile({
|
|
98
122
|
openapiFile: openapiFile,
|
|
99
123
|
controllerOutDir: dir.controllerDir,
|
|
100
124
|
modelDir: dir.modelDir,
|
|
101
|
-
compilerOptions: options ||
|
|
125
|
+
compilerOptions: options || utils.defaultCompilerOptions
|
|
102
126
|
});
|
|
103
127
|
routeGen.compile({
|
|
104
128
|
routesArr: routeData,
|
|
105
129
|
openapiFile: openapiFile,
|
|
106
130
|
routesDir: dir.routeDir,
|
|
107
|
-
compilerOptions: options ||
|
|
131
|
+
compilerOptions: options || utils.defaultCompilerOptions
|
|
108
132
|
});
|
|
109
133
|
serverGen.compile(options);
|
|
110
134
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import * as types from "../types/types";
|
|
2
|
-
export declare function formatJsonSchema(jsonSchemaPath: string): types.jsonSchema;
|
|
2
|
+
export declare function formatJsonSchema(jsonSchemaPath: string, compilerOptions: types.compilerOptions): types.jsonSchema;
|
|
@@ -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
|
|
31
|
+
const utilsJsonSchema = __importStar(require("../utils/jsonSchema"));
|
|
33
32
|
const logger_1 = __importDefault(require("../utils/logger"));
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
logger_1.default.error("formatJsonSchema : error at loadJsonSchema()");
|
|
38
|
-
}
|
|
33
|
+
const utils_1 = require("../utils");
|
|
34
|
+
function formatJsonSchema(jsonSchemaPath, compilerOptions) {
|
|
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,9 +49,11 @@ function formatJsonSchema(jsonSchemaPath) {
|
|
|
52
49
|
if (typeof jsonSchema.properties !== "object") {
|
|
53
50
|
logger_1.default.error(`properties is invalid in ${jsonSchemaPath}`);
|
|
54
51
|
}
|
|
55
|
-
|
|
52
|
+
if (compilerOptions.app.useObjectID) {
|
|
53
|
+
checkField_id(jsonSchema, jsonSchemaPath);
|
|
54
|
+
}
|
|
56
55
|
jsonSchema.required = getRequiredArrStr(jsonSchema, jsonSchemaPath);
|
|
57
|
-
|
|
56
|
+
(0, utils_1.writeFile)("Format JsonSchema", jsonSchemaPath, JSON.stringify(jsonSchema, null, 4));
|
|
58
57
|
return jsonSchema;
|
|
59
58
|
}
|
|
60
59
|
exports.formatJsonSchema = formatJsonSchema;
|
|
@@ -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;
|