very-express 0.5.0 → 0.5.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 (32) hide show
  1. package/dist/index.js +666 -493
  2. package/dist/templates/_middlewares/Authentication.ts +45 -0
  3. package/dist/templates/_plugins/auth/JWTKeyStore.ts +89 -0
  4. package/dist/templates/_plugins/auth/jwt.ts +59 -0
  5. package/dist/templates/_plugins/auth/oauthVerify.ts +83 -0
  6. package/dist/templates/_plugins/auth/profileMapping.ts +69 -0
  7. package/dist/templates/_plugins/auth/token.ts +30 -0
  8. package/dist/templates/_routes/oauth/OAuthRouteFactory.ts +63 -0
  9. package/dist/templates/_services/VexDbConnector.ts +3 -1
  10. package/dist/templates/_types/response/index.ts +10 -0
  11. package/dist/templates/_types/response/responseCode.ts +13 -0
  12. package/dist/templates/_types/response/responseMsg.ts +21 -0
  13. package/dist/templates/_types/response/responseStatusToCode.ts +70 -0
  14. package/dist/templates/_utils/index.ts +6 -2
  15. package/dist/templates/_utils/logger.ts +5 -5
  16. package/dist/templates/_utils/processTimer.ts +6 -0
  17. package/dist/templates/_utils/response.ts +25 -11
  18. package/dist/templates/jsonSchema/User.json +41 -14
  19. package/dist/templates/root/.env +10 -1
  20. package/dist/templates/root/Dockerfile +20 -0
  21. package/dist/templates/root/README.md +5 -0
  22. package/dist/templates/root/package.json +13 -4
  23. package/dist/templates/root/scripts/build.js +39 -0
  24. package/docs/roadMap/v0-6-0.md +8 -3
  25. package/docs/roadMap/v0-7-0.md +2 -1
  26. package/package.json +4 -14
  27. package/scripts/copyTsTemplates.js +6 -0
  28. package/vex.config.json +5 -7
  29. package/dist/templates/_plugins/PassportGoogle.ts +0 -84
  30. package/dist/templates/_plugins/oauthVerify.ts +0 -39
  31. package/dist/templates/_types/responseMsg.ts +0 -20
  32. /package/docs/{roadMap → releaseNote}/v0-5-0.md +0 -0
@@ -1,25 +1,39 @@
1
1
  import { Response } from "express";
2
- // import { responseObject } from "./../_types/responseMsg.gen";
2
+ import { responseStatusToCode, responseMsg, ResponseCode } from "./../_types/response/index.gen";
3
3
 
4
4
  /**
5
5
  * @param res express response object
6
- * @param code http status
6
+ * @param status http response code
7
+ * @param code custom response/error code
7
8
  * @param message response data message
8
9
  * @param result response data result
9
10
  * @returns express response object
10
11
  */
11
12
  export function send<T = undefined>(
12
13
  res: Response,
13
- code: number = 200,
14
- message: string = "OK",
15
- result?: T,
14
+ status: number = 200,
15
+ body?:{
16
+ code?: ResponseCode,
17
+ message?: string|null,
18
+ result?: T,
19
+ }
16
20
  ): Response<any, Record<string, any>> {
17
- return res.status(code).json({
18
- ret_code: code,
19
- ret_msg: message,
20
- ret_time: new Date().getTime(),
21
- result: result,
22
- });
21
+ const code :ResponseCode | undefined = body?.code || responseStatusToCode.get(status) as ResponseCode | undefined;
22
+ const msg :string | undefined = body?.message || (code ? responseMsg[code] : undefined);
23
+ const noBody = !code && !msg && !body?.result;
24
+
25
+ if(noBody){
26
+ return res.status(status).send();
27
+ }
28
+ else{
29
+ return res.status(status)
30
+ .json({
31
+ ret_code: code,
32
+ ret_msg: msg,
33
+ elapse: Date.now() - res.locals?.startAt || 0,
34
+ result: body?.result,
35
+ });
36
+ }
23
37
  }
24
38
 
25
39
  export default {
@@ -6,25 +6,39 @@
6
6
  "getList",
7
7
  "post",
8
8
  "patch"
9
- ]
9
+ ],
10
+ "documentName": "User"
10
11
  },
11
12
  "properties": {
12
13
  "_id": {
13
14
  "type": "string",
15
+ "x-format": "ObjectId",
14
16
  "index": true
15
17
  },
16
- "authProvider": {
17
- "type": "string"
18
- },
19
- "authId": {
20
- "type": "string",
21
- "index": true
18
+ "authProfiles": {
19
+ "type": "array",
20
+ "items": {
21
+ "type": "object",
22
+ "properties": {
23
+ "provider": {
24
+ "type": "string",
25
+ "index": true
26
+ },
27
+ "authId": {
28
+ "type": "string",
29
+ "index": true
30
+ },
31
+ "username": {
32
+ "type": "string"
33
+ }
34
+ },
35
+ "required": []
36
+ }
22
37
  },
23
38
  "email": {
24
39
  "type": "string",
25
40
  "format": "email",
26
- "index": true,
27
- "required": true
41
+ "index": true
28
42
  },
29
43
  "name": {
30
44
  "type": "string",
@@ -40,17 +54,30 @@
40
54
  "type": "string",
41
55
  "maxLength": 8
42
56
  },
43
- "roles":{
57
+ "roles": {
44
58
  "type": "array",
45
59
  "x-vexData": "role",
46
60
  "items": {
47
61
  "type": "string",
48
- "default": "user",
49
- "required": true,
50
62
  "enum": [
51
- "user"
63
+ "visitor",
64
+ "member",
65
+ "admin"
52
66
  ]
67
+ },
68
+ "default": [
69
+ "visitor"
70
+ ]
71
+ },
72
+ "profileErrors": {
73
+ "type": "array",
74
+ "items": {
75
+ "type": "string"
53
76
  }
54
77
  }
55
- }
78
+ },
79
+ "required": [
80
+ "name",
81
+ "active"
82
+ ]
56
83
  }
@@ -2,4 +2,13 @@ APP_HOST=http://localhost:3000
2
2
  MONGODB_URI=mongodb://localhost:27017/veryExpressDB
3
3
 
4
4
  OAUTH_GOOGLE_CLIENTID=
5
- OAUTH_GOOGLE_CLIENTSECRET=
5
+ OAUTH_GOOGLE_CLIENTSECRET=
6
+
7
+ OAUTH_GITHUB_CLIENTID=
8
+ OAUTH_GITHUB_CLIENTSECRET=
9
+
10
+ # OAUTH_APPLE_CLIENTID=
11
+ # OAUTH_APPLE_CLIENTSECRET=
12
+
13
+ JWT_EXPIRE_TIME=1m
14
+ JWT_KEY0='my-secret-key0'
@@ -0,0 +1,20 @@
1
+ # Use the official Node.js image as the base image
2
+ FROM node:14
3
+
4
+ # Set the working directory inside the container
5
+ WORKDIR /app
6
+
7
+ # Copy package.json and package-lock.json to the working directory
8
+ COPY package*.json ./
9
+
10
+ # Install dependencies
11
+ RUN npm install
12
+
13
+ # Copy only the /dist directory to the working directory
14
+ COPY dist ./dist
15
+
16
+ # Expose the port the app runs on
17
+ EXPOSE 3000
18
+
19
+ # Define the command to run the application
20
+ CMD ["npm", "start"]
@@ -27,6 +27,11 @@
27
27
  npm run start
28
28
  ```
29
29
 
30
+ 5. start the app in docker.
31
+ ```
32
+ npm run docker-build
33
+ npm run docker-start
34
+ ```
30
35
  # Resource
31
36
  - [Documents](https://github.com/Justin26l/VeryExpress/blob/main/README.md)
32
37
 
@@ -1,39 +1,48 @@
1
1
  {
2
2
  "main": "index.js",
3
3
  "scripts": {
4
- "build": "tsc -p .",
4
+ "build": "tsc -p . && node scripts/build.js",
5
5
  "start": "node dist/server.js",
6
- "dev": "nodemon --watch src --exec ts-node src/server.ts"
6
+ "dev": "nodemon --watch src --exec ts-node src/server.ts",
7
+ "docker-build": "docker build -t very-express .",
8
+ "docker-start": "docker run -p 3000:3000 very-express"
7
9
  },
8
10
  "dependencies": {
11
+ "cookie": "^0.6.0",
12
+ "cookie-parser": "^1.4.6",
9
13
  "dotenv": "^16.4.4",
10
14
  "express": "^4.18.2",
11
- "express-session": "^1.18.0",
12
15
  "express-validator": "^7.0.1",
13
16
  "helmet": "^7.1.0",
14
17
  "js-yaml": "^4.1.0",
18
+ "jsonwebtoken": "^9.0.2",
15
19
  "mongo-ts-querystring": "^1.0.4",
16
20
  "mongodb": "^5.6.0",
17
21
  "mongoose": "^7.4.0",
18
22
  "passport": "^0.7.0",
19
23
  "passport-google-oauth20": "^2.0.0",
24
+ "passport-github": "^1.1.0",
25
+ "passport-jwt": "^4.0.1",
20
26
  "swagger-ui-express": "^5.0.0"
21
27
  },
22
28
  "devDependencies": {
29
+ "@types/cookie-parser": "^1.4.7",
30
+ "@types/jsonwebtoken": "^9.0.7",
23
31
  "@types/crypto-js": "^4.1.2",
24
32
  "@types/dotenv": "^8.2.0",
25
33
  "@types/express": "^4.17.17",
26
- "@types/express-session": "^1.17.10",
27
34
  "@types/express-validator": "^3.0.0",
28
35
  "@types/js-yaml": "^4.0.9",
29
36
  "@types/mongodb": "^4.0.7",
30
37
  "@types/node": "^20.4.2",
31
38
  "@types/passport": "^1.0.16",
32
39
  "@types/passport-google-oauth20": "^2.0.14",
40
+ "@types/passport-github": "^1.1.12",
33
41
  "@types/sequelize": "^4.28.15",
34
42
  "@types/swagger-ui-express": "^4.1.6",
35
43
  "@types/ws": "^8.5.5",
36
44
  "nodemon": "^2.0.22",
45
+ "strip-json-comments": "^5.0.1",
37
46
  "ts-node": "^10.9.1",
38
47
  "typescript": "^5.1.6"
39
48
  }
@@ -0,0 +1,39 @@
1
+ // copy openapiDir to tsconfig's outDir
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ async function loadStripJsonComments() {
7
+ const { default: stripJsonComments } = await import('strip-json-comments');
8
+ return stripJsonComments;
9
+ }
10
+
11
+ async function main() {
12
+ // Load strip-json-comments dynamically
13
+ const stripJsonComments = await loadStripJsonComments();
14
+
15
+ const openapiDir = "{{openapiDir}}";
16
+ const tsconfigPath = "tsconfig.json"
17
+
18
+ // 1. read tsconfig.json to get outDir
19
+ const tsconfigContent = fs.readFileSync(tsconfigPath, 'utf-8');
20
+ const tsconfig = JSON.parse(stripJsonComments(tsconfigContent));
21
+ const outDir = tsconfig.compilerOptions.outDir;
22
+
23
+ // 2. copy ./openapi to outDir
24
+ const outDirOpenapi = path.resolve(outDir, 'openapi');
25
+ if (!fs.existsSync(outDirOpenapi)) {
26
+ fs.mkdirSync(outDirOpenapi, { recursive: true });
27
+ }
28
+ fs.readdirSync(openapiDir).forEach((file) => {
29
+ fs.copyFileSync(path.resolve(openapiDir, file), path.resolve(outDirOpenapi, file));
30
+ });
31
+ }
32
+
33
+
34
+ // Execute the main function
35
+ main()
36
+ .catch(err => {
37
+ console.error(err);
38
+ process.exit(1);
39
+ });
@@ -3,8 +3,13 @@
3
3
  ### dockernize
4
4
  - [ ] dockernize
5
5
  ### oauth2 support
6
+ - [x] google
7
+ - [ ] apple
6
8
  - [ ] microsoft
7
- - [ ] github
9
+ - [x] github
10
+ - [ ] meta/facebook
8
11
  ### session storage
9
- - [ ] jwt
10
- - [ ] ~redis~
12
+ - [x] jwt
13
+ - [x] stateless design
14
+ - [ ] redis cache
15
+ - [x] rolling session secret
@@ -1,4 +1,5 @@
1
1
  # v0.7.0 Plan
2
2
 
3
3
  ## security
4
- - [ ] db fields encryption
4
+ - [ ] Rate Limiting
5
+ - [ ] db fields encryption
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "Justin26l",
6
6
  "license": "MIT",
@@ -28,31 +28,21 @@
28
28
  "url": "git+https://github.com/Justin26l/VeryExpress.git"
29
29
  },
30
30
  "devDependencies": {
31
- "@types/express": "^4.17.21",
32
- "@types/express-session": "^1.17.10",
33
31
  "@types/js-yaml": "^4.0.9",
34
32
  "@types/minimist": "^1.2.5",
35
33
  "@types/node": "^20.10.5",
36
34
  "@types/passport": "^1.0.16",
37
- "@types/passport-google-oauth20": "^2.0.14",
38
- "@types/swagger-ui-express": "^4.1.6",
39
35
  "@typescript-eslint/eslint-plugin": "^6.18.1",
40
36
  "@typescript-eslint/parser": "^6.18.1",
41
37
  "dotenv": "^16.3.1",
42
38
  "esbuild": "0.23.0",
43
- "eslint": "^8.56.0",
44
- "express": "^4.18.2",
45
- "express-session": "^1.17.3",
46
- "express-validator": "^7.0.1",
47
- "helmet": "^7.1.0",
39
+ "eslint": "^8.57.1",
48
40
  "js-yaml": "^4.1.0",
49
41
  "json-schema-to-openapi-schema": "^0.4.0",
50
42
  "json-schema-to-typescript": "^13.1.1",
51
- "json2mongoose": "^0.4.2",
43
+ "json2mongoose": "^0.4.4",
52
44
  "minimist": "^1.2.8",
53
- "passport": "^0.7.0",
54
- "passport-google-oauth20": "^2.0.0",
55
- "swagger-ui-express": "^5.0.0",
45
+ "mongoose": "^8.7.1",
56
46
  "ts-node": "^10.9.2",
57
47
  "typescript": "^5.3.3"
58
48
  }
@@ -6,9 +6,15 @@ const path = require('path');
6
6
  * to copy template files into tsc output dir (dist)
7
7
  */
8
8
  function copyDir (src, destination) {
9
+
9
10
  if (!fs.existsSync(destination)) {
10
11
  fs.mkdirSync(destination);
11
12
  }
13
+ else {
14
+ fs.rmSync(destination, { recursive: true });
15
+ fs.mkdirSync(destination);
16
+ }
17
+
12
18
  fs.readdirSync(src).forEach((file) => {
13
19
  const srcPath = path.join(src, file);
14
20
  const destPath = path.join(destination, file);
package/vex.config.json CHANGED
@@ -2,20 +2,18 @@
2
2
  "commitBeforeGenerate": false,
3
3
  "jsonSchemaDir": "./output/jsonSchema",
4
4
  "rootDir": "./output",
5
- "srcDir": "output/src",
6
- "openapiDir": "output/src/openapi",
5
+ "srcDir": "./output/src",
6
+ "openapiDir": "./output/src/openapi",
7
7
  "app": {
8
8
  "enableSwagger": true,
9
9
  "useUserSchema": true,
10
10
  "useObjectID": true,
11
- "allowApiCreateUpdate_id": false
11
+ "allowApiCreateUpdate_id": false,
12
+ "useStatefulRedisAuth": true
12
13
  },
13
14
  "useOauth": {
14
15
  "google": true,
15
- "microsoft": false,
16
- "apple": false,
17
- "github": false,
18
- "facebook": false
16
+ "github": true
19
17
  },
20
18
  "useRBAC": {
21
19
  "roles": [
@@ -1,84 +0,0 @@
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 { UserModel } from "./../_models/UserModel.gen";
7
-
8
- export type { Profile };
9
-
10
- export interface passportGoogleConfig {
11
- strategyConfig: {
12
- options?: StrategyOptions,
13
- verify: (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => void
14
- },
15
- authenticateOptionsGoogle?: AuthenticateOptionsGoogle,
16
- }
17
-
18
- /** Provides a router and passport instance for Google OAuth */
19
- export default class PassportGoogle {
20
-
21
- private config: passportGoogleConfig;
22
- public router: Router = Router();
23
- public passport: PassportStatic = passport;
24
-
25
- constructor(config: passportGoogleConfig ) {
26
-
27
- this.config = config;
28
-
29
- this.passport.use(new GoogleStrategy(
30
- this.config.strategyConfig.options || {
31
- clientID: process.env.OAUTH_GOOGLE_CLIENTID || "",
32
- clientSecret: process.env.OAUTH_GOOGLE_CLIENTSECRET || "",
33
- callbackURL: `${process.env.APP_HOST}/auth/google/callback`,
34
- },
35
- this.config.strategyConfig.verify
36
- ));
37
-
38
- // redirect to google login
39
- this.router.get("/auth/google",
40
- this.passport.authenticate("google", this.config.authenticateOptionsGoogle || { scope: ["profile", "email"] })
41
- );
42
-
43
- // back from google login
44
- this.router.get("/auth/google/callback",
45
- this.passport.authenticate("google", { failureRedirect: "/login" }),
46
- (req, res) => {
47
- res.redirect("/profile");
48
- }
49
- );
50
- }
51
-
52
- public passportSerializeUser() {
53
- this.passport.serializeUser(async (user, done) => {
54
- // you can decide what data to store in the session here.
55
- // this data will be used in `deserializeUser` to retrieve the full user object.
56
- // ussually just user's id.
57
-
58
- // store role in session for access control
59
- const DbUser = await UserModel.findById(user);
60
- if (DbUser) {
61
- done(null, DbUser);
62
- } else {
63
- done(new Error("User not found"));
64
- }
65
-
66
- done(null, user);
67
- });
68
- }
69
-
70
- public async passportDeserializeUser() {
71
- this.passport.deserializeUser(async (id, done) => {
72
-
73
- const user = await UserModel.findById(id);
74
- if (user) {
75
- done(null, user);
76
- }
77
- else {
78
- done(new Error("User not found"));
79
- }
80
-
81
- });
82
- }
83
-
84
- }
@@ -1,39 +0,0 @@
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 || "en",
31
- });
32
- newUser.save();
33
- return done(null, newUser);
34
- }
35
- }
36
- catch(err) {
37
- return done(err);
38
- }
39
- }
@@ -1,20 +0,0 @@
1
- export enum responseMsg {
2
- permissionDeny = "Permission Denied",
3
- ok = "OK",
4
- notFound = "Not Found",
5
- queryError = "Query Error",
6
- validateError = "Validation Error",
7
- unexpectedError = "Unexpected Error",
8
- createFail = "Create Fail",
9
- updateFail = "Update Fail",
10
- deleteFail = "Delete Fail",
11
- }
12
-
13
- export interface responseObject<T>{
14
- ret_code : number,
15
- ret_msg : string,
16
- ret_time?: number,
17
- result: T,
18
- }
19
-
20
- export default responseMsg;
File without changes