very-express 0.5.13 → 0.5.15

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 (48) hide show
  1. package/.eslintrc.json +0 -0
  2. package/.gitattributes +0 -0
  3. package/.github/workflows/npm-start.yml +0 -0
  4. package/LICENSE +0 -0
  5. package/README.md +62 -62
  6. package/dist/index.js +421 -314
  7. package/dist/templates/_middlewares/Authentication.ts +8 -6
  8. package/dist/templates/_projectSettings/env +21 -21
  9. package/dist/templates/_projectSettings/package.json +49 -49
  10. package/dist/templates/_routes/oauth/OAuthRouteFactory.ts +7 -42
  11. package/dist/templates/_services/VexDbConnector.ts +8 -8
  12. package/dist/templates/_services/VexSystem.ts +5 -6
  13. package/dist/templates/_services/auth/JWTService.ts +168 -0
  14. package/dist/templates/_services/oauth/OAuthProfileMap.ts +69 -0
  15. package/dist/templates/_services/oauth/OAuthStrategyService.ts +92 -0
  16. package/dist/templates/_types/VexResponseError.ts +20 -0
  17. package/dist/templates/_types/responseObject.ts +7 -0
  18. package/dist/templates/_utils/hash.ts +47 -0
  19. package/dist/templates/_utils/index.ts +5 -3
  20. package/dist/templates/_utils/response.ts +102 -32
  21. package/dist/templates/jsonSchema/User.json +85 -82
  22. package/dist/templates/root/public/css/style.css +7 -7
  23. package/dist/templates/root/public/js/logincallback.js +18 -18
  24. package/dist/templates/root/public/js/mytokens.js +10 -10
  25. package/dist/templates/root/public/js/refreshtokens.js +22 -22
  26. package/docs/ForeignKey.md +0 -0
  27. package/docs/appGenerated/auth.md +0 -0
  28. package/docs/developmentNote.md +0 -0
  29. package/docs/releaseNote/v0-5-0.md +0 -0
  30. package/docs/roadMap/released.md +0 -0
  31. package/docs/roadMap/v0-6-0.md +0 -0
  32. package/docs/roadMap/v0-7-0.md +0 -0
  33. package/docs/vexJsonSchema.md +0 -0
  34. package/package.json +51 -51
  35. package/scripts/build.js +0 -0
  36. package/scripts/copyTsTemplates.js +0 -0
  37. package/scripts/merge.js +0 -0
  38. package/tsconfig.json +121 -121
  39. package/vex.config.json +36 -35
  40. package/dist/templates/_plugins/auth/jwt.ts +0 -85
  41. package/dist/templates/_plugins/auth/oauthVerify.ts +0 -86
  42. package/dist/templates/_plugins/auth/profileMapping.ts +0 -68
  43. package/dist/templates/_plugins/auth/token.ts +0 -29
  44. package/dist/templates/_types/response/index.ts +0 -10
  45. package/dist/templates/_types/response/responseCode.ts +0 -15
  46. package/dist/templates/_types/response/responseMsg.ts +0 -28
  47. package/dist/templates/_types/response/responseStatusCodeMap.ts +0 -70
  48. /package/dist/templates/{_plugins → _services}/auth/JWTKeyStore.ts +0 -0
@@ -1,12 +1,14 @@
1
1
  // {{headerComment}}
2
2
  import { Request, Response, NextFunction } from "express";
3
3
  import { JsonWebTokenError } from "jsonwebtoken";
4
- import * as jwt from "../_plugins/auth/jwt.gen";
4
+ import JWTService from "../_services/auth/JWTService.gen";
5
5
  import log from "../_utils/logger.gen";
6
- import responseGen from "../_utils/response.gen";
6
+ import response from "../_utils/response.gen";
7
7
 
8
8
  export default class Authentication {
9
9
 
10
+ private JWTService = new JWTService();
11
+
10
12
  public middleware = (req: Request, res: Response, next: NextFunction) => {
11
13
  try {
12
14
  // gate keeper
@@ -23,7 +25,7 @@ export default class Authentication {
23
25
  }
24
26
 
25
27
  // verify token
26
- const tokenData = jwt.verifyToken(token, accessTokenIndex);
28
+ const tokenData = this.JWTService.verifyToken(token, accessTokenIndex);
27
29
 
28
30
  // set req.user to the decoded token
29
31
  log.info("tokenValid", tokenData);
@@ -32,14 +34,14 @@ export default class Authentication {
32
34
  }
33
35
  catch (e: any) {
34
36
  if (typeof e === "number") {
35
- responseGen.send(res, e);
37
+ response.send(res, e);
36
38
  }
37
39
  else if (e instanceof JsonWebTokenError) {
38
- responseGen.send(res, 400, { message: e?.message});
40
+ response.send(res, 400, { message: e?.message});
39
41
  }
40
42
  else {
41
43
  log.errorNoExit(e);
42
- responseGen.send(res, 500, { message: e?.message});
44
+ response.send(res, 500, { message: e?.message});
43
45
  }
44
46
  }
45
47
  };
@@ -1,22 +1,22 @@
1
- APP_HOST=http://localhost:3000
2
- MONGODB_URI=mongodb://localhost:27017/veryExpressDB
3
-
4
- LOGIN_SUCCESS_REDIRECT_PATH=/logincallback
5
- LOGIN_FAILED_REDIRECT_PATH=/logincallback
6
-
7
- # OAUTH
8
- OAUTH_GOOGLE_CLIENTID=
9
- OAUTH_GOOGLE_CLIENTSECRET=
10
- OAUTH_GITHUB_CLIENTID=
11
- OAUTH_GITHUB_CLIENTSECRET=
12
- # OAUTH_MICROSOFT_CLIENTID=
13
- # OAUTH_MICROSOFT_CLIENTSECRET=
14
- # OAUTH_APPLE_CLIENTID=
15
- # OAUTH_APPLE_CLIENTSECRET=
16
-
17
- # JWT token
18
- ACCESS_TOKEN_EXPIRE_TIME='5m'
19
- REFRESH_TOKEN_EXPIRE_TIME='15m'
20
- SESSION_COOKIE_SECRET='my-session-cookie-secret'
21
- JWT_ALGORITHM='HS256'
1
+ APP_HOST=http://localhost:3000
2
+ MONGODB_URI=mongodb://localhost:27017/veryExpressDB
3
+
4
+ LOGIN_SUCCESS_REDIRECT_PATH=/logincallback
5
+ LOGIN_FAILED_REDIRECT_PATH=/logincallback
6
+
7
+ # OAUTH
8
+ OAUTH_GOOGLE_CLIENTID=
9
+ OAUTH_GOOGLE_CLIENTSECRET=
10
+ OAUTH_GITHUB_CLIENTID=
11
+ OAUTH_GITHUB_CLIENTSECRET=
12
+ # OAUTH_MICROSOFT_CLIENTID=
13
+ # OAUTH_MICROSOFT_CLIENTSECRET=
14
+ # OAUTH_APPLE_CLIENTID=
15
+ # OAUTH_APPLE_CLIENTSECRET=
16
+
17
+ # JWT token
18
+ ACCESS_TOKEN_EXPIRE_TIME='5m'
19
+ REFRESH_TOKEN_EXPIRE_TIME='15m'
20
+ SESSION_COOKIE_SECRET='my-session-cookie-secret'
21
+ JWT_ALGORITHM='HS256'
22
22
  JWT_SECRET0='my-secret-key0'
@@ -1,50 +1,50 @@
1
- {
2
- "main": "index.js",
3
- "scripts": {
4
- "build": "tsc -p . && node scripts/build.js",
5
- "start": "node dist/server.js",
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"
9
- },
10
- "dependencies": {
11
- "cookie": "^0.6.0",
12
- "cookie-parser": "^1.4.6",
13
- "dotenv": "^16.4.4",
14
- "express": "^4.18.2",
15
- "express-validator": "^7.0.1",
16
- "helmet": "^7.1.0",
17
- "js-yaml": "^4.1.0",
18
- "jsonwebtoken": "^9.0.2",
19
- "mongo-ts-querystring": "^1.0.4",
20
- "mongodb": "^5.6.0",
21
- "mongoose": "^7.4.0",
22
- "passport": "^0.7.0",
23
- "passport-google-oauth20": "^2.0.0",
24
- "passport-github": "^1.1.0",
25
- "passport-jwt": "^4.0.1",
26
- "swagger-ui-express": "^5.0.0"
27
- },
28
- "devDependencies": {
29
- "@types/cookie-parser": "^1.4.7",
30
- "@types/jsonwebtoken": "^9.0.7",
31
- "@types/crypto-js": "^4.1.2",
32
- "@types/dotenv": "^8.2.0",
33
- "@types/express": "^4.17.17",
34
- "@types/express-validator": "^3.0.0",
35
- "@types/js-yaml": "^4.0.9",
36
- "@types/mongodb": "^4.0.7",
37
- "@types/ms": "^2.1.0",
38
- "@types/node": "^20.4.2",
39
- "@types/passport": "^1.0.16",
40
- "@types/passport-google-oauth20": "^2.0.14",
41
- "@types/passport-github": "^1.1.12",
42
- "@types/sequelize": "^4.28.15",
43
- "@types/swagger-ui-express": "^4.1.6",
44
- "@types/ws": "^8.5.5",
45
- "nodemon": "^2.0.22",
46
- "strip-json-comments": "^5.0.1",
47
- "ts-node": "^10.9.1",
48
- "typescript": "^5.1.6"
49
- }
1
+ {
2
+ "main": "index.js",
3
+ "scripts": {
4
+ "build": "tsc -p . && node scripts/build.js",
5
+ "start": "node dist/server.js",
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"
9
+ },
10
+ "dependencies": {
11
+ "cookie": "^0.6.0",
12
+ "cookie-parser": "^1.4.6",
13
+ "dotenv": "^16.4.4",
14
+ "express": "^4.18.2",
15
+ "express-validator": "^7.0.1",
16
+ "helmet": "^7.1.0",
17
+ "js-yaml": "^4.1.0",
18
+ "jsonwebtoken": "^9.0.2",
19
+ "mongo-ts-querystring": "^1.0.4",
20
+ "mongodb": "^5.6.0",
21
+ "mongoose": "^7.4.0",
22
+ "passport": "^0.7.0",
23
+ "passport-google-oauth20": "^2.0.0",
24
+ "passport-github": "^1.1.0",
25
+ "passport-jwt": "^4.0.1",
26
+ "swagger-ui-express": "^5.0.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/cookie-parser": "^1.4.7",
30
+ "@types/jsonwebtoken": "^9.0.7",
31
+ "@types/crypto-js": "^4.1.2",
32
+ "@types/dotenv": "^8.2.0",
33
+ "@types/express": "^4.17.17",
34
+ "@types/express-validator": "^3.0.0",
35
+ "@types/js-yaml": "^4.0.9",
36
+ "@types/mongodb": "^4.0.7",
37
+ "@types/ms": "^2.1.0",
38
+ "@types/node": "^20.4.2",
39
+ "@types/passport": "^1.0.16",
40
+ "@types/passport-google-oauth20": "^2.0.14",
41
+ "@types/passport-github": "^1.1.12",
42
+ "@types/sequelize": "^4.28.15",
43
+ "@types/swagger-ui-express": "^4.1.6",
44
+ "@types/ws": "^8.5.5",
45
+ "nodemon": "^2.0.22",
46
+ "strip-json-comments": "^5.0.1",
47
+ "ts-node": "^10.9.1",
48
+ "typescript": "^5.1.6"
49
+ }
50
50
  }
@@ -1,17 +1,16 @@
1
1
  // {{headerComment}}
2
2
  import path from "path";
3
- import ms from "ms";
4
3
  import { Router } from "express";
5
4
  import passport, { PassportStatic, Profile } from "passport";
6
5
  import * as oauth2 from "passport-oauth2";
7
- import { SessionModel } from "../../_models/SessionModel.gen";
8
- import { generateAccessToken, generateRefreshToken } from "../../_plugins/auth/jwt.gen";
6
+ import JWTService from "../../_services/auth/JWTService.gen";
7
+ import { User } from "../../_types/User.gen";
9
8
 
10
9
  export type { Profile };
11
10
 
12
11
  export interface passportFactoryConfig {
13
12
  strategyName: string,
14
- strategy: oauth2.Strategy,
13
+ strategy: oauth2.Strategy | passport.Strategy,
15
14
  authenticateOptions?: any,
16
15
  }
17
16
 
@@ -21,6 +20,7 @@ export default class OAuthRouteFactory {
21
20
  private config: passportFactoryConfig;
22
21
  private router: Router = Router();
23
22
  private passport: PassportStatic = passport;
23
+ private JWTService = new JWTService();
24
24
 
25
25
  private loginSuccessRedirectPath = "";
26
26
  private loginFailedRedirectPath = "";
@@ -71,45 +71,10 @@ export default class OAuthRouteFactory {
71
71
  return res.redirect(`${this.loginFailedRedirectPath}?error=invalid user`);
72
72
  }
73
73
 
74
- // @ts-expect-error custom var
75
- const accessToken = await generateAccessToken(req.user.profile._id);
76
- // @ts-expect-error custom var
77
- const refreshToken = await generateRefreshToken({_id: req.user.profile._id});
78
-
79
- res.cookie("vex-access-token", {
80
- accessToken: accessToken.token,
81
- accessTokenIndex: accessToken.clientIndex
82
- }, {
83
- maxAge: ms(process.env.ACCESS_TOKEN_EXPIRE_TIME as ms.StringValue),
84
- httpOnly: true,
85
- secure: true,
86
- sameSite: "strict",
87
- });
88
-
89
- res.cookie("vex-refresh-token", {
90
- accessToken: refreshToken.token,
91
- accessTokenIndex: refreshToken.clientIndex,
92
- }, {
93
- maxAge: ms(process.env.REFRESH_TOKEN_EXPIRE_TIME as ms.StringValue),
94
- httpOnly: true,
95
- secure: true,
96
- sameSite: "strict",
97
- });
98
-
99
-
100
- const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
101
-
102
- SessionModel.create({
103
- sessionCode: sessionCode,
104
- // @ts-expect-error custom var
105
- userId: req.user.profile._id,
106
- // @ts-expect-error custom var
107
- provider: req.user.provider || "",
108
- expired: Date.now() + 5000
109
- });
110
-
111
74
  // return appAuthCode to client
112
- res.redirect(`${this.loginSuccessRedirectPath}?code=${sessionCode}`);
75
+ const redirectUrl = await this.JWTService.assignTokens(req.user as User, res);
76
+ return res.redirect(redirectUrl);
77
+
113
78
  }
114
79
  );
115
80
  }
@@ -1,7 +1,7 @@
1
1
  // {{headerComment}}
2
2
  import mongoose from "mongoose";
3
3
  import { Request, Response, NextFunction } from "express";
4
- import vex from "./../_utils/index.gen";
4
+ import utils from "./../_utils";
5
5
 
6
6
  export default class VexDbConnector {
7
7
  private mongoUrl: string;
@@ -25,31 +25,31 @@ export default class VexDbConnector {
25
25
 
26
26
  connectMongo() : mongoose.Connection | void {
27
27
  if ( !this.mongoUrl ){
28
- vex.log.error("VexDbConnector : MongoUrl is not invalid");
28
+ utils.log.error("VexDbConnector : MongoUrl is not invalid");
29
29
  return;
30
30
  }
31
31
  /**
32
32
  * @param retryTime time in second
33
33
  */
34
34
  const connectWithRetry = (retryTime: number = 10) : Promise<void | typeof mongoose> => {
35
- // vex.log.infoMongo("Connection with retry");
35
+ // utils.log.infoMongo("Connection with retry");
36
36
  return mongoose.connect(this.mongoUrl, {
37
37
  autoCreate: true,
38
38
  connectTimeoutMS: 5000,
39
39
  })
40
40
  .catch((err) => {
41
- vex.log.errorMongo(`Failed to Connect DB, Retrying in ${retryTime} seconds.`, err);
41
+ utils.log.errorMongo(`Failed to Connect DB, Retrying in ${retryTime} seconds.`, err);
42
42
  setTimeout(connectWithRetry, retryTime*1000);
43
43
  });
44
44
  };
45
45
  connectWithRetry(10);
46
46
 
47
47
  mongoose.connection.on("open", () => {
48
- vex.log.infoMongo("MongoDB Connection open");
48
+ utils.log.infoMongo("MongoDB Connection open");
49
49
  });
50
50
 
51
51
  mongoose.connection.on("error", (err: any) => {
52
- vex.log.errorMongo("MongoDB Connection error: ", err.message, err);
52
+ utils.log.errorMongo("MongoDB Connection error: ", err.message, err);
53
53
  });
54
54
 
55
55
  return mongoose.connection;
@@ -63,8 +63,8 @@ export default class VexDbConnector {
63
63
  **/
64
64
  middleware(req: Request, res: Response, next: NextFunction) {
65
65
  if (mongoose.connection.readyState !== 1) {
66
- vex.response.send(res, 503, {
67
- code: vex.response.code.DB_CONN_ERR,
66
+ utils.response.send(res, 503, {
67
+ code: utils.response.code.DB_CONN_ERR,
68
68
  });
69
69
  }
70
70
  else if (this.recordAccessLog){
@@ -1,8 +1,7 @@
1
1
  // {{headerComment}}
2
2
  import { Request, Response } from "express";
3
- import vex from "./../_utils/index.gen";
4
- import { VexResponseError } from "../_utils/response.gen";
5
- import responseCode from "../_types/response/responseCode.gen";
3
+ import utils from "./../_utils";
4
+ import VexResponseError from "../_types/VexResponseError.gen";
6
5
 
7
6
  export default class VexSystem {
8
7
 
@@ -20,14 +19,14 @@ export default class VexSystem {
20
19
  return handler(req, res).catch((err: any) => {
21
20
 
22
21
  if ( err instanceof VexResponseError ) {
23
- return vex.response.send(res, err.status, {
22
+ return utils.response.send(res, err.status, {
24
23
  code: err.ret_code,
25
24
  message: err.message
26
25
  });
27
26
  }
28
27
  else {
29
- return vex.response.send(res, 500, {
30
- code: responseCode.SERVER_ERROR,
28
+ return utils.response.send(res, 500, {
29
+ code: utils.response.code.SERVER_ERROR,
31
30
  message: err.message || "Internal Server Error"
32
31
  });
33
32
  }
@@ -0,0 +1,168 @@
1
+ // {{headerComment}}
2
+ import jwt from "jsonwebtoken";
3
+ import ms from "ms";
4
+ import path from "path";
5
+ import express from "express";
6
+
7
+ import JWTKeyStore from "./JWTKeyStore.gen";
8
+ import utils from "../../_utils";
9
+
10
+ import VexResponseError from "../../_types/VexResponseError.gen";
11
+
12
+ import { UserModel } from "../../_models/UserModel.gen";
13
+ import { SessionModel } from "../../_models/SessionModel.gen";
14
+ import { User } from "../../_types/User.gen";
15
+
16
+ interface tokenObj {
17
+ token: string,
18
+ index?: number,
19
+ clientIndex?: string
20
+ }
21
+
22
+ export default class JWTService {
23
+ private keyStore = new JWTKeyStore();
24
+
25
+ /**
26
+ * Verifies a JSON Web Token (JWT) using the provided token and key index.
27
+ *
28
+ * @param {string} token - The JSON Web Token to be verified.
29
+ * @param {number} index - The index of the key used to verify the token.
30
+ * @return {jwt.JwtPayload } The decoded token payload, an error message, or false if verification fails.
31
+ */
32
+ public verifyToken(token: string, index?: number | string): jwt.JwtPayload {
33
+
34
+ if (token.startsWith("Bearer ")) {
35
+ token = token.split("Bearer ")[1];
36
+ }
37
+
38
+ const key = this.keyStore.getSecret(index || 0);
39
+
40
+ try {
41
+ return jwt.verify(token, key) as jwt.JwtPayload;
42
+ }
43
+ catch (error) {
44
+ if (error instanceof jwt.TokenExpiredError) {
45
+ throw new VexResponseError(401, utils.response.code.err_payload, "Token expired");
46
+ }
47
+ else if (error instanceof jwt.JsonWebTokenError) {
48
+ throw new VexResponseError(401, utils.response.code.err_payload, "jwt malformed");
49
+ }
50
+ else {
51
+ throw error;
52
+ }
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Process of login user, assign tokens and create session.
58
+ */
59
+ public async assignTokens(user: User, res: express.Response) {
60
+ if(!user._id) {
61
+ throw new VexResponseError(500, utils.response.code.err_db_data, "User Data Error, User._id missing.");
62
+ }
63
+
64
+ const accessToken = await this.generateAccessToken(user._id);
65
+ const refreshToken = await this.generateRefreshToken({ _id: user._id });
66
+
67
+ res.cookie("vex-access-token", {
68
+ accessToken: accessToken.token,
69
+ accessTokenIndex: accessToken.clientIndex
70
+ }, {
71
+ maxAge: ms(process.env.ACCESS_TOKEN_EXPIRE_TIME as ms.StringValue),
72
+ httpOnly: true,
73
+ secure: true,
74
+ sameSite: "strict",
75
+ });
76
+
77
+ res.cookie("vex-refresh-token", {
78
+ refreshToken: refreshToken.token,
79
+ refreshTokenIndex: refreshToken.clientIndex,
80
+ }, {
81
+ maxAge: ms(process.env.REFRESH_TOKEN_EXPIRE_TIME as ms.StringValue),
82
+ httpOnly: true,
83
+ secure: true,
84
+ sameSite: "strict",
85
+ });
86
+
87
+ const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
88
+
89
+ SessionModel.create({
90
+ sessionCode: sessionCode,
91
+ userId: user._id,
92
+ provider: "local",
93
+ expired: Date.now() + 5000
94
+ });
95
+
96
+ // return appAuthCode to client
97
+ const redirectPath = `${path.posix.join("/", process.env.LOGIN_SUCCESS_REDIRECT_PATH || "/logincallback")}?code=${sessionCode}`;
98
+
99
+ return redirectPath;
100
+ }
101
+
102
+ public returnToken(userProfile: User) {
103
+ const sanitizedProfile = this.sanitizeUser(userProfile);
104
+ const accessToken = this.generateToken(sanitizedProfile, undefined, process.env.ACCESS_TOKEN_EXPIRE_TIME);
105
+ const refreshToken = this.generateToken({ _id: userProfile._id }, 0, process.env.REFRESH_TOKEN_EXPIRE_TIME);
106
+
107
+ return {
108
+ profile: sanitizedProfile,
109
+ accessToken: accessToken.token,
110
+ accessTokenIndex: accessToken.index,
111
+ clientIndex: accessToken.clientIndex,
112
+ refreshToken: refreshToken.token
113
+ };
114
+ }
115
+
116
+ /** utils */
117
+
118
+ public sanitizeUser(user: User) {
119
+ return {
120
+ _id: user._id,
121
+ email: user.email,
122
+ name: user.name,
123
+ locale: user.locale,
124
+ roles: user.roles,
125
+ profileErrors: user.profileErrors,
126
+ active: user.active
127
+ };
128
+ }
129
+
130
+ private generateToken(
131
+ data: any,
132
+ index?: number,
133
+ expiresIn?: string
134
+ ): tokenObj {
135
+ data = JSON.parse(JSON.stringify(data));
136
+ const keyInfo = typeof index == "number" ? this.keyStore.getSecretObj(index) : this.keyStore.getRandomKey();
137
+ const token = jwt.sign(
138
+ data,
139
+ keyInfo.key as jwt.Secret,
140
+ {
141
+ expiresIn: (expiresIn || this.keyStore.expireTime || "1h") as ms.StringValue,
142
+ algorithm: this.keyStore.algorithm
143
+ }
144
+ );
145
+
146
+ return {
147
+ token: token,
148
+ index: keyInfo.index,
149
+ clientIndex: keyInfo.clientIndex
150
+ };
151
+ }
152
+
153
+ public async generateAccessToken(userId: string, index?: number): Promise<tokenObj> {
154
+
155
+ const userDoc = await UserModel.findById(userId).exec();
156
+ if (!userDoc) {
157
+ throw new VexResponseError(404, utils.response.code.err_payload, "Invalid User Id");
158
+ }
159
+ const userInfo = this.sanitizeUser(userDoc);
160
+
161
+ return this.generateToken(userInfo, index, process.env.ACCESS_TOKEN_EXPIRE_TIME);
162
+ }
163
+
164
+ public generateRefreshToken(data: any, index?: number): tokenObj {
165
+ return this.generateToken(data, index, process.env.REFRESH_TOKEN_EXPIRE_TIME);
166
+ }
167
+
168
+ }
@@ -0,0 +1,69 @@
1
+ // {{headerComment}}
2
+ import { Profile } from "passport";
3
+ import { User } from "./../../_types/User.gen";
4
+
5
+ export interface IProfile extends Profile {
6
+ [key: string]: any;
7
+ }
8
+
9
+ export default class OAuthProfileMap {
10
+
11
+ public map(oauthProfile: Profile) {
12
+ let authProfile: User;
13
+ switch (oauthProfile.provider) {
14
+ case "github":
15
+ authProfile = this.GithubProfileMapping(oauthProfile);
16
+ break;
17
+ case "google":
18
+ authProfile = this.GoogleProfileMapping(oauthProfile);
19
+ break;
20
+ default:
21
+ throw new Error("Invalid OAuth Provider");
22
+ break;
23
+ }
24
+
25
+ // if ( !authProfile.email){
26
+ // console.log('missingEmail');
27
+ // authProfile.profileErrors?.push('missingEmail');
28
+ // authProfile.active = false;
29
+ // }
30
+ return authProfile;
31
+ }
32
+
33
+ private GithubProfileMapping(oauthProfile: IProfile): User {
34
+ const user: User = {
35
+ active: true,
36
+ authProfiles: [{
37
+ provider: oauthProfile.provider,
38
+ authId: oauthProfile.id,
39
+ username: oauthProfile.username || oauthProfile.displayName
40
+ }],
41
+ roles: undefined,
42
+ name: oauthProfile.username || oauthProfile.displayName,
43
+ email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
44
+ locale: undefined,
45
+ profileErrors: []
46
+ };
47
+
48
+ return user;
49
+ }
50
+ private GoogleProfileMapping(oauthProfile: IProfile): User {
51
+ const user: User = {
52
+ active: true,
53
+ authProfiles: [{
54
+ provider: oauthProfile.provider,
55
+ authId: oauthProfile.id,
56
+ username: oauthProfile.username || oauthProfile.displayName
57
+ }],
58
+ roles: undefined,
59
+ name: oauthProfile.username || oauthProfile.displayName,
60
+ // data below could be missing depend on the provider
61
+ email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
62
+ locale: oauthProfile._json.locale || undefined,
63
+ profileErrors: []
64
+ };
65
+
66
+ return user;
67
+ }
68
+
69
+ }