very-express 0.5.12 → 0.5.14

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 (28) hide show
  1. package/dist/index.js +405 -296
  2. package/dist/templates/_middlewares/Authentication.ts +8 -6
  3. package/dist/templates/{root/.env → _projectSettings/env} +4 -4
  4. package/dist/templates/_routes/oauth/OAuthRouteFactory.ts +7 -42
  5. package/dist/templates/_services/VexDbConnector.ts +8 -8
  6. package/dist/templates/_services/VexSystem.ts +5 -6
  7. package/dist/templates/_services/auth/JWTService.ts +168 -0
  8. package/dist/templates/_services/oauth/OAuthProfileMap.ts +69 -0
  9. package/dist/templates/_services/oauth/OAuthStrategyService.ts +92 -0
  10. package/dist/templates/_types/VexResponseError.ts +20 -0
  11. package/dist/templates/_types/responseObject.ts +7 -0
  12. package/dist/templates/_utils/hash.ts +47 -0
  13. package/dist/templates/_utils/index.ts +5 -3
  14. package/dist/templates/_utils/response.ts +102 -32
  15. package/dist/templates/jsonSchema/User.json +3 -0
  16. package/package.json +1 -1
  17. package/tsconfig.json +1 -1
  18. package/vex.config.json +36 -35
  19. package/dist/templates/_plugins/auth/jwt.ts +0 -85
  20. package/dist/templates/_plugins/auth/oauthVerify.ts +0 -86
  21. package/dist/templates/_plugins/auth/profileMapping.ts +0 -68
  22. package/dist/templates/_plugins/auth/token.ts +0 -29
  23. package/dist/templates/_types/response/index.ts +0 -10
  24. package/dist/templates/_types/response/responseCode.ts +0 -15
  25. package/dist/templates/_types/response/responseMsg.ts +0 -28
  26. package/dist/templates/_types/response/responseStatusCodeMap.ts +0 -70
  27. /package/dist/templates/{root → _projectSettings}/package.json +0 -0
  28. /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
  };
@@ -4,19 +4,19 @@ MONGODB_URI=mongodb://localhost:27017/veryExpressDB
4
4
  LOGIN_SUCCESS_REDIRECT_PATH=/logincallback
5
5
  LOGIN_FAILED_REDIRECT_PATH=/logincallback
6
6
 
7
+ # OAUTH
7
8
  OAUTH_GOOGLE_CLIENTID=
8
9
  OAUTH_GOOGLE_CLIENTSECRET=
9
-
10
10
  OAUTH_GITHUB_CLIENTID=
11
11
  OAUTH_GITHUB_CLIENTSECRET=
12
-
12
+ # OAUTH_MICROSOFT_CLIENTID=
13
+ # OAUTH_MICROSOFT_CLIENTSECRET=
13
14
  # OAUTH_APPLE_CLIENTID=
14
15
  # OAUTH_APPLE_CLIENTSECRET=
15
16
 
17
+ # JWT token
16
18
  ACCESS_TOKEN_EXPIRE_TIME='5m'
17
19
  REFRESH_TOKEN_EXPIRE_TIME='15m'
18
-
19
20
  SESSION_COOKIE_SECRET='my-session-cookie-secret'
20
-
21
21
  JWT_ALGORITHM='HS256'
22
22
  JWT_SECRET0='my-secret-key0'
@@ -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
+ }
@@ -0,0 +1,92 @@
1
+ // {{headerComment}}
2
+ import { UserModel, UserDocument } from "./../../_models/UserModel.gen";
3
+ import { User } from "./../../_types/User.gen";
4
+ import JWTService from "./../auth/JWTService.gen";
5
+ import OAuthProfileMap, { IProfile } from "./OAuthProfileMap.gen";
6
+ import utils from "../../_utils";
7
+
8
+
9
+ export default class OAuthStrategyService {
10
+
11
+ public async verify(accessToken: string, refreshToken: string, profile: IProfile, done: (error: any, user?: any) => void) : Promise<void> {
12
+ try {
13
+
14
+ let user: UserDocument;
15
+ const authUser = new OAuthProfileMap().map(profile);
16
+
17
+ // find user by authProfiles.authId or email
18
+ const existingUser = await UserModel.findOne<UserDocument>({
19
+ email: authUser.email,
20
+ $or: authUser.authProfiles?.map((p) => {
21
+ return { "authProfiles.authId": p.authId };
22
+ }),
23
+ });
24
+
25
+ // 1. create new user
26
+ if ( !existingUser ){
27
+ user = await this.createNewUser(authUser);
28
+ }
29
+ // 2. update existing user
30
+ else {
31
+ console.log("OAuthVerify UpdateUser");
32
+ user = await this.processExistingUser(authUser, existingUser);
33
+ }
34
+
35
+ // set req.user
36
+ done(null, {
37
+ provider: profile.provider,
38
+ profile: new JWTService().sanitizeUser(user),
39
+ });
40
+ }
41
+ catch(err) {
42
+ return done(err);
43
+ }
44
+ }
45
+
46
+ private async createNewUser(authProfile: User): Promise<UserDocument>{
47
+ utils.log.info("OAuthVerify > createNewUser");
48
+ const newUser = new UserModel(authProfile);
49
+ return await newUser.save();
50
+ }
51
+
52
+ private async processExistingUser( authUser: User, existingUser: UserDocument): Promise<UserDocument>{
53
+ utils.log.info("OAuthVerify > processExistingUser");
54
+
55
+ let userUpdated = false;
56
+ const authProfile = authUser.authProfiles?.[0] || undefined;
57
+ const userProfiles = existingUser.authProfiles as User["authProfiles"] || [];
58
+
59
+ if(!authProfile){
60
+ utils.log.errorNoExit("OAuthVerify > Invalid OAuth Callback \"authProfile\"");
61
+ throw new Error("Invalid OAuth Callback \"authProfile\"");
62
+ }
63
+
64
+ // B.1. check current provider exist in authProfiles
65
+ const providerExists = userProfiles.length > 0 && userProfiles.find((p: any) => {
66
+ return (p.provider === authProfile.provider) && (p.authId === authProfile.authId);
67
+ });
68
+
69
+ // B.2. add if not exist
70
+ if (!providerExists){
71
+ utils.log.info("OAuthVerify > add new provider",authProfile.provider);
72
+ userProfiles.push(authProfile);
73
+ userUpdated = true;
74
+ }
75
+ // B.3 update if username changed
76
+ else if (providerExists && providerExists.username !== authProfile.username){
77
+ utils.log.info("OAuthVerify > update username", authProfile.provider);
78
+ providerExists.username = authProfile.username;
79
+ userUpdated = true;
80
+ }
81
+
82
+ if (userUpdated){
83
+ utils.log.info("OAuthVerify > Update user");
84
+ return await existingUser.updateOne({ authProfiles: userProfiles });
85
+ }
86
+ else {
87
+ return existingUser;
88
+ }
89
+ }
90
+
91
+
92
+ }
@@ -0,0 +1,20 @@
1
+ import { ResponseCode } from "./../_utils/response.gen";
2
+ import utils from "../_utils/index";
3
+
4
+ export default class VexResponseError extends Error {
5
+ public status: number;
6
+ public ret_code: ResponseCode;
7
+ public ret_msg: any;
8
+
9
+ constructor(
10
+ status: number = 200,
11
+ code?: ResponseCode,
12
+ message?: string,
13
+ ) {
14
+ super(message);
15
+ this.name = "VexResponseError";
16
+ this.status = status;
17
+ this.ret_code = code || utils.response.code.SERVER_ERROR;
18
+ this.ret_msg = message || utils.response.msg.SERVER_ERROR;
19
+ }
20
+ }
@@ -0,0 +1,7 @@
1
+
2
+ export interface responseObject<T>{
3
+ ret_code : number,
4
+ ret_msg : string,
5
+ ret_time?: number,
6
+ result: T,
7
+ }
@@ -0,0 +1,47 @@
1
+ // {{headerComment}}
2
+ import crypto from "crypto";
3
+ import { User } from "../_types/User.gen";
4
+
5
+ /**
6
+ * Hashes a password with a salt (e.g., user email).
7
+ * @param plainPassword The plain text password to hash.
8
+ * @param salt The salt to use (e.g., user email).
9
+ * @param algorithm The hash algorithm (default: 'sha256').
10
+ * @returns The hashed password (hex encoded).
11
+ */
12
+ export function hashPassword(
13
+ plainPassword: string,
14
+ salt: string,
15
+ algorithm: "sha256" = "sha256"
16
+ ): string {
17
+ return crypto.createHash(algorithm).update(plainPassword + salt).digest("hex");
18
+ }
19
+
20
+ /**
21
+ * Verifies if a plain password (with salt) matches a given hashed password.
22
+ * @param user The user object containing email and authProfiles.
23
+ * @param plainPassword The plain text password to verify.
24
+ * @returns True if the password matches, false otherwise.
25
+ */
26
+ export function verifyPassword(
27
+ user: User,
28
+ plainPassword: string,
29
+ ): boolean {
30
+ if(!user.email || !user.authProfiles) {
31
+ console.error("User email or authProfiles missing for local auth's password verification.");
32
+ return false;
33
+ }
34
+
35
+ const hashedPassword = user.authProfiles.find((profile:any) => profile.provider === "local")?.password;
36
+ if(!hashedPassword) {
37
+ console.error("Local auth profile or password missing for user.");
38
+ return false;
39
+ }
40
+
41
+ return hashPassword(plainPassword, user.email) === hashedPassword;
42
+ }
43
+
44
+ export default {
45
+ hashPassword,
46
+ verifyPassword
47
+ };
@@ -1,11 +1,13 @@
1
+ import common from "./common.gen";
2
+ import hash from "./hash.gen";
1
3
  import logger from "./logger.gen";
2
4
  import response from "./response.gen";
3
5
  import validator from "./validator.gen";
4
- import common from "./common.gen";
5
6
 
6
7
  export default {
8
+ common,
9
+ hash,
7
10
  log : logger,
8
11
  response,
9
- validator,
10
- common
12
+ validator
11
13
  };