very-express 0.5.26 → 0.6.0-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.
- package/.eslintrc.json +36 -37
- package/.gitattributes +2 -2
- package/.github/copilot-instructions.md +107 -84
- package/.github/workflows/npm-start.yml +23 -23
- package/LICENSE +21 -21
- package/README.md +75 -75
- package/dist/index.js +1040 -1149
- package/dist/templates/_controllers/_ControllerFactory.ts +7 -3
- package/dist/templates/_middlewares/Authentication.ts +1 -5
- package/dist/templates/_middlewares/tsoaAuthentication.ts +24 -0
- package/dist/templates/_projectSettings/env +25 -24
- package/dist/templates/_projectSettings/package.json +50 -54
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +48 -0
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +59 -0
- package/dist/templates/_services/VexDb.ts +14 -0
- package/dist/templates/_services/VexDbConnector.ts +108 -163
- package/dist/templates/_services/VexSystem.ts +25 -42
- package/dist/templates/_services/auth/JWTService.ts +26 -13
- package/dist/templates/_services/oauth/OAuthProfileMap.ts +6 -14
- package/dist/templates/_services/oauth/OAuthStrategyService.ts +70 -51
- package/dist/templates/_types/IVexRepository.ts +18 -0
- package/dist/templates/_types/VexRequest.ts +11 -0
- package/dist/templates/_types/VexResponse.ts +25 -0
- package/dist/templates/_types/VexResponseError.ts +4 -3
- package/dist/templates/_types/responseObject.ts +1 -1
- package/dist/templates/_utils/common.ts +50 -16
- package/dist/templates/_utils/hash.ts +6 -5
- package/dist/templates/_utils/index.ts +2 -1
- package/dist/templates/_utils/logger.ts +15 -14
- package/dist/templates/_utils/processTimer.ts +1 -0
- package/dist/templates/_utils/response.ts +4 -3
- package/dist/templates/_utils/validator.ts +1 -0
- package/dist/templates/jsonSchema/Session.json +34 -31
- package/dist/templates/jsonSchema/User.json +50 -85
- package/dist/templates/jsonSchema/UserAuthProfiles.json +48 -0
- package/dist/templates/root/Dockerfile +19 -19
- package/dist/templates/root/README.md +38 -38
- package/dist/templates/root/public/css/style.css +7 -7
- package/dist/templates/root/public/js/login.js +58 -58
- package/dist/templates/root/public/js/logincallback.js +18 -18
- package/dist/templates/root/public/js/mytokens.js +10 -10
- package/dist/templates/root/public/js/refreshtokens.js +22 -22
- package/dist/templates/root/scripts/build.js +38 -38
- package/dist/templates/root/tsconfig.json +29 -27
- package/docs/ForeignKey.md +43 -43
- package/docs/appGenerated/auth.md +22 -22
- package/docs/developmentNote.md +22 -22
- package/docs/releaseNote/v0-5-0.md +17 -17
- package/docs/roadMap/futurePlan.md +9 -9
- package/docs/roadMap/released.md +49 -49
- package/docs/roadMap/v0-6-0.md +15 -15
- package/docs/vexJsonSchema.md +55 -55
- package/package.json +59 -58
- package/scripts/build.js +13 -13
- package/scripts/bump-version.js +86 -86
- package/scripts/copyTsTemplates.js +30 -30
- package/scripts/merge.js +124 -124
- package/tsconfig.json +121 -121
- package/vex.config.json +37 -36
- 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
|
|
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
|
|
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
|
-
|
|
17
|
-
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
77
|
-
if (!
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
-
|
|
85
|
-
if (
|
|
86
|
-
this.
|
|
87
|
-
|
|
88
|
-
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
-
|
|
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
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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.
|
|
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.
|
|
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
|
-
}
|
|
188
|
-
|
|
189
|
-
|
|
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:
|
|
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
|
-
*
|
|
17
|
-
*
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
}
|
|
@@ -8,9 +8,11 @@ import JWTKeyStore from "./JWTKeyStore.gen";
|
|
|
8
8
|
import utils from "../../_utils";
|
|
9
9
|
|
|
10
10
|
import VexResponseError from "../../_types/VexResponseError.gen";
|
|
11
|
+
import { IVexRepository } from "../../_types/IVexRepository.gen";
|
|
11
12
|
|
|
12
|
-
import
|
|
13
|
-
import {
|
|
13
|
+
import VexDb from "../VexDb.gen";
|
|
14
|
+
import { UserEntity } from "../../_models/UserModel.gen";
|
|
15
|
+
import { SessionEntity } from "../../_models/SessionModel.gen";
|
|
14
16
|
import { User } from "../../_types/User.gen";
|
|
15
17
|
|
|
16
18
|
interface tokenObj {
|
|
@@ -22,6 +24,15 @@ interface tokenObj {
|
|
|
22
24
|
export default class JWTService {
|
|
23
25
|
private keyStore = new JWTKeyStore();
|
|
24
26
|
|
|
27
|
+
private get userRepo(): IVexRepository<UserEntity> {
|
|
28
|
+
return VexDb.getRepository(UserEntity);
|
|
29
|
+
}
|
|
30
|
+
private get sessionRepo(): IVexRepository<SessionEntity> {
|
|
31
|
+
return VexDb.getRepository(SessionEntity);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
constructor() {}
|
|
35
|
+
|
|
25
36
|
/**
|
|
26
37
|
* Verifies a JSON Web Token (JWT) using the provided token and key index.
|
|
27
38
|
*
|
|
@@ -42,10 +53,10 @@ export default class JWTService {
|
|
|
42
53
|
}
|
|
43
54
|
catch (error) {
|
|
44
55
|
if (error instanceof jwt.TokenExpiredError) {
|
|
45
|
-
throw new VexResponseError(401,
|
|
56
|
+
throw new VexResponseError(401, null, "Token expired");
|
|
46
57
|
}
|
|
47
58
|
else if (error instanceof jwt.JsonWebTokenError) {
|
|
48
|
-
throw new VexResponseError(401,
|
|
59
|
+
throw new VexResponseError(401, null, "jwt malformed");
|
|
49
60
|
}
|
|
50
61
|
else {
|
|
51
62
|
throw error;
|
|
@@ -58,7 +69,7 @@ export default class JWTService {
|
|
|
58
69
|
*/
|
|
59
70
|
public async assignTokens(user: User) {
|
|
60
71
|
if(!user._id) {
|
|
61
|
-
throw new VexResponseError(500,
|
|
72
|
+
throw new VexResponseError(500, null, "User Data Error, User._id missing.");
|
|
62
73
|
}
|
|
63
74
|
|
|
64
75
|
// const accessToken = await this.generateAccessToken(user._id);
|
|
@@ -86,12 +97,14 @@ export default class JWTService {
|
|
|
86
97
|
|
|
87
98
|
const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
|
88
99
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
100
|
+
if (this.sessionRepo) {
|
|
101
|
+
await this.sessionRepo.create({
|
|
102
|
+
sessionCode,
|
|
103
|
+
userId: user._id,
|
|
104
|
+
provider: "local",
|
|
105
|
+
expired: Date.now() + 5000,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
95
108
|
|
|
96
109
|
// return appAuthCode to client
|
|
97
110
|
const redirectPath = `${path.posix.join("/", process.env.LOGIN_SUCCESS_REDIRECT_PATH || "/logincallback")}?code=${sessionCode}`;
|
|
@@ -152,9 +165,9 @@ export default class JWTService {
|
|
|
152
165
|
|
|
153
166
|
public async generateAccessToken(userId: string, index?: number): Promise<tokenObj> {
|
|
154
167
|
|
|
155
|
-
const userDoc = await
|
|
168
|
+
const userDoc = await this.userRepo.findOne({ _id: userId });
|
|
156
169
|
if (!userDoc) {
|
|
157
|
-
throw new VexResponseError(404,
|
|
170
|
+
throw new VexResponseError(404, null, "Invalid User Id");
|
|
158
171
|
}
|
|
159
172
|
const userInfo = this.sanitizeUser(userDoc);
|
|
160
173
|
|
|
@@ -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
|
-
|
|
30
|
+
userAuthProfiles: [{
|
|
37
31
|
provider: oauthProfile.provider,
|
|
38
|
-
|
|
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
|
-
|
|
46
|
+
userAuthProfiles: [{
|
|
54
47
|
provider: oauthProfile.provider,
|
|
55
|
-
|
|
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;
|