very-express 0.5.26 → 0.6.1-alpha

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 (60) hide show
  1. package/.eslintrc.json +35 -37
  2. package/.gitattributes +2 -2
  3. package/.github/copilot-instructions.md +107 -84
  4. package/.github/workflows/npm-start.yml +23 -23
  5. package/LICENSE +21 -21
  6. package/README.md +75 -75
  7. package/dist/index.js +1039 -1149
  8. package/dist/templates/_controllers/_ControllerFactory.ts +7 -3
  9. package/dist/templates/_middlewares/Authentication.ts +1 -5
  10. package/dist/templates/_middlewares/tsoaAuthentication.ts +24 -0
  11. package/dist/templates/_projectSettings/env +25 -24
  12. package/dist/templates/_projectSettings/package.json +50 -54
  13. package/dist/templates/_services/MongooseRepositoryAdapter.ts +48 -0
  14. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +59 -0
  15. package/dist/templates/_services/VexDb.ts +14 -0
  16. package/dist/templates/_services/VexDbConnector.ts +108 -163
  17. package/dist/templates/_services/VexSystem.ts +25 -42
  18. package/dist/templates/_services/auth/JWTService.ts +26 -14
  19. package/dist/templates/_services/oauth/OAuthProfileMap.ts +6 -14
  20. package/dist/templates/_services/oauth/OAuthStrategyService.ts +69 -51
  21. package/dist/templates/_types/IVexRepository.ts +18 -0
  22. package/dist/templates/_types/VexRequest.ts +11 -0
  23. package/dist/templates/_types/VexResponse.ts +25 -0
  24. package/dist/templates/_types/VexResponseError.ts +4 -3
  25. package/dist/templates/_types/responseObject.ts +1 -1
  26. package/dist/templates/_utils/common.ts +50 -16
  27. package/dist/templates/_utils/hash.ts +6 -5
  28. package/dist/templates/_utils/index.ts +2 -1
  29. package/dist/templates/_utils/logger.ts +15 -14
  30. package/dist/templates/_utils/processTimer.ts +1 -0
  31. package/dist/templates/_utils/response.ts +4 -3
  32. package/dist/templates/_utils/validator.ts +1 -0
  33. package/dist/templates/jsonSchema/Session.json +34 -31
  34. package/dist/templates/jsonSchema/User.json +50 -85
  35. package/dist/templates/jsonSchema/UserAuthProfiles.json +48 -0
  36. package/dist/templates/root/Dockerfile +19 -19
  37. package/dist/templates/root/README.md +38 -38
  38. package/dist/templates/root/public/css/style.css +7 -7
  39. package/dist/templates/root/public/js/login.js +58 -58
  40. package/dist/templates/root/public/js/logincallback.js +18 -18
  41. package/dist/templates/root/public/js/mytokens.js +10 -10
  42. package/dist/templates/root/public/js/refreshtokens.js +22 -22
  43. package/dist/templates/root/scripts/build.js +38 -38
  44. package/dist/templates/root/tsconfig.json +29 -27
  45. package/docs/ForeignKey.md +43 -43
  46. package/docs/appGenerated/auth.md +22 -22
  47. package/docs/developmentNote.md +22 -22
  48. package/docs/releaseNote/v0-5-0.md +17 -17
  49. package/docs/roadMap/futurePlan.md +9 -9
  50. package/docs/roadMap/released.md +49 -49
  51. package/docs/roadMap/v0-6-0.md +15 -15
  52. package/docs/vexJsonSchema.md +55 -55
  53. package/package.json +59 -58
  54. package/scripts/build.js +13 -13
  55. package/scripts/bump-version.js +86 -86
  56. package/scripts/copyTsTemplates.js +30 -30
  57. package/scripts/merge.js +124 -124
  58. package/tsconfig.json +121 -121
  59. package/vex.config.json +37 -36
  60. package/dist/templates/_types/VexResponsePayloadError.ts +0 -20
@@ -1,226 +1,171 @@
1
1
  // {{headerComment}}
2
- import mongoose from "mongoose";
3
2
  import { Request, Response, NextFunction } from "express";
4
- import knex, { Knex } from "knex";
3
+ import { DataSource, EntityTarget, ObjectLiteral } from "typeorm";
4
+ import mongoose, { Document } from "mongoose";
5
+ import { sqlMigrations } from "../_models/sqlMigration.gen";
6
+ import { IVexRepository } from "../_types/IVexRepository.gen";
7
+ import { TypeOrmRepositoryAdapter } from "./TypeOrmRepositoryAdapter.gen";
8
+ import { MongooseRepositoryAdapter } from "./MongooseRepositoryAdapter.gen";
5
9
  import utils from "./../_utils";
6
10
 
7
- export default class VexDbConnector {
8
- private mongoUrl: string;
11
+ export class VexDbConnector {
9
12
  private sqlUrl: string;
10
-
11
- private sqlConnection?: Knex;
12
- private sqlClient?: string;
13
13
  private sqlCa: string;
14
+ private mongoUrl: string;
14
15
  private recordAccessLog: boolean = false;
15
16
 
16
- constructor(options:{
17
- mongoUrl?: string;
17
+ public dataSource?: DataSource;
18
+
19
+ constructor(options: {
18
20
  sqlUrl?: string;
19
21
  sqlCa?: string;
22
+ mongoUrl?: string;
20
23
  recordAccessLog?: boolean;
21
- }){
22
- this.mongoUrl = options.mongoUrl || "";
24
+ }) {
23
25
  this.sqlUrl = options.sqlUrl || "";
24
26
  this.sqlCa = options.sqlCa || "";
27
+ this.mongoUrl = options.mongoUrl || "";
25
28
  this.recordAccessLog = options.recordAccessLog || false;
26
-
27
- // Bind the middleware method to the instance
28
29
  this.middleware = this.middleware.bind(this);
29
30
  }
30
-
31
+
31
32
  connect(): void {
32
- if (this.mongoUrl) this.connectMongo();
33
33
  if (this.sqlUrl) this.connectSql();
34
+ if (this.mongoUrl) this.connectMongo();
34
35
  }
35
36
 
36
37
  close(): void {
37
- if (this.mongoUrl) this.closeMongo();
38
38
  if (this.sqlUrl) this.closeSql();
39
+ if (this.mongoUrl) this.closeMongo();
39
40
  }
40
-
41
- connectMongo() : mongoose.Connection | void {
42
- if ( !this.mongoUrl ){
43
- utils.log.error("VexDbConnector : MongoUrl is not invalid");
44
- return;
45
- }
46
- else {
47
- utils.log.infoMongo("Connecting to MongoDB...");
41
+
42
+ connectSql(): void {
43
+ utils.log.infoSql("Connecting to SQL DB (TypeORM)...");
44
+
45
+ const caRaw = this.sqlCa || undefined;
46
+ let ca: string | undefined;
47
+ if (caRaw) {
48
+ ca = caRaw.startsWith("-----BEGIN") ? caRaw : Buffer.from(caRaw, "base64").toString("utf8");
48
49
  }
49
- /**
50
- * @param retryTime time in second
51
- */
52
- const connectWithRetry = (retryTime: number = 10) : Promise<void | typeof mongoose> => {
53
- // utils.log.infoMongo("Connection with retry");
54
- return mongoose.connect(this.mongoUrl, {
55
- autoCreate: true,
56
- connectTimeoutMS: 5000,
57
- })
50
+ const insecure = (process.env.SQL_INSECURE_TLS || "").toLowerCase() === "true";
51
+ const ssl = insecure
52
+ ? { rejectUnauthorized: false }
53
+ : (ca ? { rejectUnauthorized: true, ca } : undefined);
54
+
55
+ const sqlUrl = new URL(this.sqlUrl);
56
+ const ds = new DataSource({
57
+ type: "postgres",
58
+ host: sqlUrl.hostname,
59
+ port: Number(sqlUrl.port) || 5432,
60
+ username: sqlUrl.username,
61
+ password: sqlUrl.password,
62
+ database: sqlUrl.pathname.slice(1),
63
+ ssl,
64
+ synchronize: (process.env.SQL_SYNCHRONIZE || "").toLowerCase() === "true",
65
+ logging: false,
66
+ entities: [__dirname + "/../_models/*.gen.{ts,js}"],
67
+ migrations: [],
68
+ });
69
+
70
+ const connectWithRetry = (retryTime = 10): void => {
71
+ ds.initialize()
72
+ .then(() => {
73
+ this.dataSource = ds;
74
+ utils.log.infoSql("TypeORM DataSource initialized");
75
+ this.runSqlMigrations(ds);
76
+ })
58
77
  .catch((err) => {
59
- utils.log.errorMongo(`Failed to Connect DB, Retrying in ${retryTime} seconds.`, err);
60
- setTimeout(connectWithRetry, retryTime*1000);
78
+ utils.log.errorSql(`Failed to initialize TypeORM, retrying in ${retryTime}s`, err);
79
+ setTimeout(() => connectWithRetry(retryTime), retryTime * 1000);
61
80
  });
62
81
  };
63
- connectWithRetry(10);
64
82
 
65
- mongoose.connection.on("open", () => {
66
- utils.log.infoMongo("MongoDB Connection open");
67
- });
68
-
69
- mongoose.connection.on("error", (err: any) => {
70
- utils.log.errorMongo("MongoDB Connection error: ", err.message, err);
71
- });
72
-
73
- return mongoose.connection;
83
+ connectWithRetry(10);
74
84
  }
75
85
 
76
- connectSql(): Knex | void {
77
- if (!this.sqlUrl) {
78
- return;
79
- }
80
- else {
81
- utils.log.infoSql("Connecting to SQL DB...");
86
+ private async runSqlMigrations(ds: DataSource): Promise<void> {
87
+ if (!sqlMigrations.length) return;
88
+ const runner = ds.createQueryRunner();
89
+ await runner.connect();
90
+ try {
91
+ for (const sql of sqlMigrations) {
92
+ utils.log.infoSql(`Applying migration: ${sql}`);
93
+ await runner.query(sql);
94
+ }
95
+ utils.log.infoSql(`${sqlMigrations.length} migrations applied`);
96
+ } catch (err) {
97
+ utils.log.errorSql("SQL migration failed", err);
98
+ } finally {
99
+ await runner.release();
82
100
  }
101
+ }
83
102
 
84
- const url = this.sqlUrl.toLowerCase();
85
- if (url.startsWith("postgres://") || url.startsWith("postgresql://")) {
86
- this.sqlClient = "pg";
87
- } else if (url.startsWith("mysql://") || url.startsWith("mariadb://")) {
88
- this.sqlClient = "mysql2";
89
- } else {
90
- // try to guess by common keywords
91
- if (url.indexOf("postgres") !== -1) this.sqlClient = "pg";
92
- else this.sqlClient = "mysql2";
103
+ closeSql(): void {
104
+ if (this.dataSource?.isInitialized) {
105
+ this.dataSource.destroy()
106
+ .then(() => utils.log.infoSql("TypeORM DataSource closed"))
107
+ .catch((err) => utils.log.errorSql("Error closing TypeORM DataSource", err));
93
108
  }
109
+ }
94
110
 
95
- try {
96
- const caRaw = this.sqlCa || undefined;
97
- let ca: string | undefined;
98
- if (caRaw) {
99
- ca = caRaw.startsWith("-----BEGIN") ? caRaw : Buffer.from(caRaw, "base64").toString("utf8");
100
- }
101
- const insecure = (process.env.SQL_INSECURE_TLS || "").toLowerCase() === "true";
102
- const ssl = insecure ? { rejectUnauthorized: false } : (ca ? { rejectUnauthorized: true, ca } : undefined);
103
-
104
- utils.log.infoSql(`Using SQL client: ${this.sqlClient}, SSL: ${ssl ? "enabled" : "disabled"}`);
105
- const connection: Knex.Config["connection"] | string = this.sqlClient === "pg" ? {
106
- user: new URL(this.sqlUrl).username,
107
- password: new URL(this.sqlUrl).password,
108
- host: new URL(this.sqlUrl).hostname,
109
- port: Number(new URL(this.sqlUrl).port),
110
- database: new URL(this.sqlUrl).pathname.slice(1),
111
- ssl
112
- } : this.sqlUrl;
113
-
114
- this.sqlConnection = knex({
115
- client: this.sqlClient,
116
- connection,
117
- pool: { min: 0, max: 10 }
118
- });
119
-
120
- // quick health check
121
- this.sqlConnection.raw("select 1").then(() => {
122
- utils.log.infoSql("SQL DB Connection established");
123
- })
124
- .catch((err:any) => {
125
- utils.log.errorSql("Failed to establish SQL DB connection", err);
111
+ connectMongo(): void {
112
+ utils.log.infoSql("Connecting to MongoDB (Mongoose)...");
113
+ const connectWithRetry = (retryTime = 10): void => {
114
+ mongoose.connect(this.mongoUrl)
115
+ .then(() => utils.log.infoSql("Mongoose connected"))
116
+ .catch((err) => {
117
+ utils.log.errorSql(`Failed to connect Mongoose, retrying in ${retryTime}s`, err);
118
+ setTimeout(() => connectWithRetry(retryTime), retryTime * 1000);
126
119
  });
127
-
128
- return this.sqlConnection;
129
- }
130
- catch (err:any) {
131
- utils.log.errorSql("VexDbConnector: connectSql error", err);
132
- return;
133
- }
120
+ };
121
+ connectWithRetry(10);
134
122
  }
135
123
 
136
124
  closeMongo(): void {
137
- if (mongoose.connection.readyState === 1) {
138
- mongoose.connection.close().then(() => {
139
- utils.log.infoMongo("MongoDB Connection closed");
140
- }).catch((err:any) => {
141
- utils.log.errorMongo("Error closing MongoDB connection", err);
142
- });
143
- }
125
+ mongoose.disconnect()
126
+ .then(() => utils.log.infoSql("Mongoose disconnected"))
127
+ .catch((err) => utils.log.errorSql("Error disconnecting Mongoose", err));
144
128
  }
145
129
 
146
- closeSql(): void {
147
- if (this.sqlConnection) {
148
- this.sqlConnection.destroy().then(() => {
149
- utils.log.infoSql("SQL DB Connection closed");
150
- }).catch((err:any) => {
151
- utils.log.errorSql("Error closing SQL DB connection", err);
152
- });
130
+ getRepository<T extends Document>(target: { schema: unknown; modelName: string }): IVexRepository<T>;
131
+ getRepository<T extends ObjectLiteral>(target: EntityTarget<T>): IVexRepository<T>;
132
+ getRepository<T>(target: EntityTarget<ObjectLiteral> | any): IVexRepository<T> {
133
+ // Mongoose Model: has .schema and .modelName properties
134
+ if (target?.schema && target?.modelName) {
135
+ return new MongooseRepositoryAdapter<T & Document>(target);
153
136
  }
137
+ if (!this.dataSource) throw new Error("SQL DataSource not initialized");
138
+ return new TypeOrmRepositoryAdapter<T & ObjectLiteral>(this.dataSource.getRepository(target));
154
139
  }
155
140
 
156
- /**
157
- * Database Middleware
158
- * Feature:
159
- * - restrict access to app when DB connection down.
160
- * - record access log
161
- **/
162
141
  async middleware(req: Request, res: Response, next: NextFunction): Promise<void> {
163
142
  try {
164
- if (this.mongoUrl && mongoose.connection.readyState !== 1) {
143
+ if (this.sqlUrl && (!this.dataSource || !this.dataSource.isInitialized)) {
165
144
  utils.response.send(res, 503, { code: utils.response.code.DB_CONN_ERR });
166
145
  return;
167
146
  }
168
147
 
169
- if (this.sqlUrl && this.sqlConnection) {
170
- try {
171
- await this.sqlConnection.raw("select 1");
172
- }
173
- catch (err:any) {
174
- utils.response.send(res, 503, { code: utils.response.code.DB_CONN_ERR });
175
- return;
176
- }
177
- }
178
-
179
- if (this.recordAccessLog) {
148
+ if (this.recordAccessLog && this.dataSource?.isInitialized) {
180
149
  const logEntry = {
181
150
  timestamp: new Date().getTime(),
182
151
  ipa: req.socket.remoteAddress || req.headers["x-forwarded-for"],
183
152
  method: req.method,
184
153
  url: req.url.split("?")[0],
185
- headers: req.headers,
186
- query: req.query,
187
- } as any;
188
-
189
- // write to Mongo if available
190
- if (this.mongoUrl && mongoose.connection.readyState === 1) {
191
- try {
192
- mongoose.connection.collection("accessLogs").insertOne(logEntry);
193
- }
194
- catch (e:any) {
195
- utils.log.error("Failed to write access log to Mongo", e);
196
- }
197
- }
198
-
199
- // write to SQL if available
200
- if (this.sqlUrl && this.sqlConnection) {
201
- try {
202
- const table = "accessLogs";
203
- const insert = { ...logEntry };
204
- // knex may not accept headers/query objects directly for some DBs,
205
- // so stringify them to be safe
206
- insert.headers = JSON.stringify(insert.headers || {});
207
- insert.query = JSON.stringify(insert.query || {});
208
- await this.sqlConnection(table).insert(insert as any).catch(()=>{});
209
- }
210
- catch (e:any) {
211
- utils.log.error("Failed to write access log to SQL", e);
212
- }
154
+ headers: JSON.stringify(req.headers),
155
+ query: JSON.stringify(req.query),
156
+ };
157
+ try {
158
+ await this.dataSource.getRepository("AccessLog").save(logEntry);
213
159
  }
214
-
215
- next();
216
- return;
160
+ catch { /* table may not exist */ }
217
161
  }
218
162
 
219
163
  next();
220
164
  }
221
- catch (err:any) {
222
- utils.response.send(res, 503, { code: utils.response.code.DB_Action_ERR, message: err.message });
165
+ catch (err: unknown) {
166
+ utils.response.send(res, 503, { code: utils.response.code.DB_Action_ERR, message: (err as Error).message });
223
167
  }
224
168
  }
225
169
  }
226
170
 
171
+ export default VexDbConnector;
@@ -1,51 +1,34 @@
1
1
  // {{headerComment}}
2
- import { Request, Response } from "express";
2
+ import { Request, Response, NextFunction } from "express";
3
3
  import utils from "./../_utils";
4
+ import VexResponse from "../_types/VexResponse.gen";
4
5
  import VexResponseError from "../_types/VexResponseError.gen";
5
- import VexResponsePayloadError from "../_types/VexResponsePayloadError.gen";
6
- import { validationResult } from "express-validator";
7
6
 
8
7
  export default class VexSystem {
9
-
10
- constructor() {
11
- // Bind the middleware method to the instance
12
- this.RouteHandler = this.RouteHandler.bind(this);
13
- }
14
8
 
15
9
  /**
16
- * System Middleware
17
- * Feature:
18
- * - error handling
19
- * - validation handling
20
- **/
21
- public RouteHandler(handler: (req: Request, res: Response) => Promise<any>) {
22
- return async (req: Request, res: Response) => {
23
- try {
24
- const validation = validationResult(req);
25
- if (!validation.isEmpty()) throw new VexResponsePayloadError(validation.array());
26
- return await handler(req, res);
27
- }
28
- catch (err: any) {
29
- if ( err instanceof VexResponseError ) {
30
- return utils.response.send(res, err.status, {
31
- code: err.ret_code,
32
- message: err.message
33
- });
34
- }
35
- else if (err instanceof VexResponsePayloadError) {
36
- return utils.response.send(res, err.status, {
37
- code: err.ret_code,
38
- message: err.message,
39
- result: err.result
40
- });
41
- }
42
- else {
43
- return utils.response.send(res, 500, {
44
- code: utils.response.code.SERVER_ERROR,
45
- message: err.message || "Internal Server Error"
46
- });
47
- }
48
- }
49
- };
10
+ * Express error-handling middleware.
11
+ * Register AFTER all routes: app.use(VexSystem.responseHandler)
12
+ */
13
+ static responseHandler(err: unknown, _req: Request, res: Response, _next: NextFunction): Response {
14
+ if (err instanceof VexResponse) {
15
+ return utils.response.send(res, err.status, err.body);
16
+ }
17
+ else if (err instanceof VexResponseError) {
18
+ const vexErr = err as VexResponseError;
19
+ return utils.response.send(res, vexErr.status, {
20
+ code: vexErr.ret_code,
21
+ message: vexErr.message,
22
+ });
23
+ }
24
+ else {
25
+ utils.log.error("Unhandled error:", err);
26
+ const e: any = err;
27
+ return utils.response.send(res, e?.status ?? 500, {
28
+ code: e?.ret_code ?? utils.response.code.SERVER_ERROR,
29
+ message: e?.message ?? "Internal Server Error",
30
+ });
31
+ }
50
32
  }
33
+
51
34
  }
@@ -5,12 +5,13 @@ import path from "path";
5
5
  // import express, { CookieOptions } from "express";
6
6
 
7
7
  import JWTKeyStore from "./JWTKeyStore.gen";
8
- import utils from "../../_utils";
9
8
 
10
9
  import VexResponseError from "../../_types/VexResponseError.gen";
10
+ import { IVexRepository } from "../../_types/IVexRepository.gen";
11
11
 
12
- import { UserModel } from "../../_models/UserModel.gen";
13
- import { SessionModel } from "../../_models/SessionModel.gen";
12
+ import VexDb from "../VexDb.gen";
13
+ import { UserEntity } from "../../_models/UserModel.gen";
14
+ import { SessionEntity } from "../../_models/SessionModel.gen";
14
15
  import { User } from "../../_types/User.gen";
15
16
 
16
17
  interface tokenObj {
@@ -22,6 +23,15 @@ interface tokenObj {
22
23
  export default class JWTService {
23
24
  private keyStore = new JWTKeyStore();
24
25
 
26
+ private get userRepo(): IVexRepository<UserEntity> {
27
+ return VexDb.getRepository(UserEntity);
28
+ }
29
+ private get sessionRepo(): IVexRepository<SessionEntity> {
30
+ return VexDb.getRepository(SessionEntity);
31
+ }
32
+
33
+ constructor() {}
34
+
25
35
  /**
26
36
  * Verifies a JSON Web Token (JWT) using the provided token and key index.
27
37
  *
@@ -42,10 +52,10 @@ export default class JWTService {
42
52
  }
43
53
  catch (error) {
44
54
  if (error instanceof jwt.TokenExpiredError) {
45
- throw new VexResponseError(401, utils.response.code.err_payload, "Token expired");
55
+ throw new VexResponseError(401, null, "Token expired");
46
56
  }
47
57
  else if (error instanceof jwt.JsonWebTokenError) {
48
- throw new VexResponseError(401, utils.response.code.err_payload, "jwt malformed");
58
+ throw new VexResponseError(401, null, "jwt malformed");
49
59
  }
50
60
  else {
51
61
  throw error;
@@ -58,7 +68,7 @@ export default class JWTService {
58
68
  */
59
69
  public async assignTokens(user: User) {
60
70
  if(!user._id) {
61
- throw new VexResponseError(500, utils.response.code.err_db_data, "User Data Error, User._id missing.");
71
+ throw new VexResponseError(500, null, "User Data Error, User._id missing.");
62
72
  }
63
73
 
64
74
  // const accessToken = await this.generateAccessToken(user._id);
@@ -86,12 +96,14 @@ export default class JWTService {
86
96
 
87
97
  const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
88
98
 
89
- SessionModel.create({
90
- sessionCode: sessionCode,
91
- userId: user._id,
92
- provider: "local",
93
- expired: Date.now() + 5000
94
- });
99
+ if (this.sessionRepo) {
100
+ await this.sessionRepo.create({
101
+ sessionCode,
102
+ userId: user._id,
103
+ provider: "local",
104
+ expired: Date.now() + 5000,
105
+ });
106
+ }
95
107
 
96
108
  // return appAuthCode to client
97
109
  const redirectPath = `${path.posix.join("/", process.env.LOGIN_SUCCESS_REDIRECT_PATH || "/logincallback")}?code=${sessionCode}`;
@@ -152,9 +164,9 @@ export default class JWTService {
152
164
 
153
165
  public async generateAccessToken(userId: string, index?: number): Promise<tokenObj> {
154
166
 
155
- const userDoc = await UserModel.findById(userId).exec();
167
+ const userDoc = await this.userRepo.findOne({ _id: userId });
156
168
  if (!userDoc) {
157
- throw new VexResponseError(404, utils.response.code.err_payload, "Invalid User Id");
169
+ throw new VexResponseError(404, null, "Invalid User Id");
158
170
  }
159
171
  const userInfo = this.sanitizeUser(userDoc);
160
172
 
@@ -21,28 +21,21 @@ export default class OAuthProfileMap {
21
21
  throw new Error("Invalid OAuth Provider");
22
22
  break;
23
23
  }
24
-
25
- // if ( !authProfile.email){
26
- // console.log('missingEmail');
27
- // authProfile.profileErrors?.push('missingEmail');
28
- // authProfile.active = false;
29
- // }
30
24
  return authProfile;
31
25
  }
32
26
 
33
27
  private GithubProfileMapping(oauthProfile: IProfile): User {
34
28
  const user: User = {
35
29
  active: true,
36
- authProfiles: [{
30
+ userAuthProfiles: [{
37
31
  provider: oauthProfile.provider,
38
- authId: oauthProfile.id,
32
+ oauthId: oauthProfile.id,
39
33
  username: oauthProfile.username || oauthProfile.displayName
40
34
  }],
41
- roles: undefined,
42
35
  name: oauthProfile.username || oauthProfile.displayName,
43
36
  email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
44
37
  locale: undefined,
45
- profileErrors: []
38
+ profileErrors: ""
46
39
  };
47
40
 
48
41
  return user;
@@ -50,17 +43,16 @@ export default class OAuthProfileMap {
50
43
  private GoogleProfileMapping(oauthProfile: IProfile): User {
51
44
  const user: User = {
52
45
  active: true,
53
- authProfiles: [{
46
+ userAuthProfiles: [{
54
47
  provider: oauthProfile.provider,
55
- authId: oauthProfile.id,
48
+ oauthId: oauthProfile.id,
56
49
  username: oauthProfile.username || oauthProfile.displayName
57
50
  }],
58
- roles: undefined,
59
51
  name: oauthProfile.username || oauthProfile.displayName,
60
52
  // data below could be missing depend on the provider
61
53
  email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
62
54
  locale: oauthProfile._json.locale || undefined,
63
- profileErrors: []
55
+ profileErrors: ""
64
56
  };
65
57
 
66
58
  return user;