propro-utils 1.3.33 → 1.3.35

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.
@@ -61,7 +61,11 @@ const getAccountProfile = async (redisClient, userSchema, accountId) => {
61
61
  const checkIfUserExists = async (userSchema, accountId) => {
62
62
  const user = await userSchema.findOne({ accountId });
63
63
  if (!user) {
64
- await userSchema.create({accountId});
64
+ await userSchema.create({
65
+ accountId,
66
+ id: uuidv4(),
67
+ verified: false,
68
+ });
65
69
  }
66
70
  };
67
71
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "propro-utils",
3
- "version": "1.3.33",
3
+ "version": "1.3.35",
4
4
  "description": "Auth middleware for propro-auth",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
package/src/index.js CHANGED
@@ -21,7 +21,7 @@ let _serverAuth, _clientAuth;
21
21
  * validateUser: async (userId) => { }, // Function to validate user
22
22
  * onAuthFailRedirect: '/login', // URL to redirect on authentication failure
23
23
  * additionalChecks: async (req) => { }, // Additional custom checks for requests
24
- * }
24
+ * },
25
25
  * @param {boolean} [options.useClientAuth=false] - A boolean flag to enable client-side authentication.
26
26
  * @param {Object} [options.clientOptions={}] - Configuration options for client-side authentication.
27
27
  * @param {Schema} [userSchema] - The user schema to perform the operations on.
@@ -39,7 +39,7 @@ let _serverAuth, _clientAuth;
39
39
  * additionalChecks: async (req) => { },
40
40
  * },
41
41
  * useClientAuth: false,
42
- * }));
42
+ * }, UserSchema));
43
43
  */
44
44
  module.exports = function proproAuthMiddleware(options = {}, userSchema) {
45
45
  validateEnvironmentVariables([
@@ -1,8 +1,9 @@
1
1
  require("dotenv").config();
2
2
  const {
3
- exchangeToken,
3
+ exchangeToken,
4
4
  } = require("./middleware/verifyToken");
5
5
  const {checkIfUserExists} = require("../../middlewares/account_info");
6
+ const {post} = require("axios");
6
7
 
7
8
  /**
8
9
  * Middleware for handling authentication and authorization.
@@ -19,73 +20,107 @@ const {checkIfUserExists} = require("../../middlewares/account_info");
19
20
  * @returns {Function} - Express middleware function.
20
21
  */
21
22
  function proproAuthMiddleware(options = {}, userSchema) {
22
- const {
23
- secret = "RESTFULAPIs",
24
- authUrl = process.env.AUTH_URL,
25
- clientId = process.env.CLIENT_ID,
26
- clientSecret = process.env.CLIENT_SECRET,
27
- clientUrl = process.env.CLIENT_URL,
28
- redirectUri = process.env.REDIRECT_URI,
29
- appName = process.env.APP_NAME,
30
- } = options;
31
-
32
- return async (req, res, next) => {
33
- try {
34
- if (!["/api/auth", "/api/callback"].includes(req.path)) {
35
- return next();
36
- }
37
-
38
- if (req.path === "/api/auth") {
39
- const authClientUrl = `${clientUrl}/signin`;
40
- const redirectUrl = `${authClientUrl}?response_type=code&appName=${appName}&client_id=${clientId}&redirect_uri=${encodeURIComponent(
41
- redirectUri
42
- )}`;
43
- res.status(200).json({ redirectUrl });
44
- }
45
-
46
- if (req.path === "/api/callback") {
47
- const code = req.query.code;
48
- if (!code) {
49
- return res.status(400).send("No code received");
50
- }
23
+ const {
24
+ secret = "RESTFULAPIs",
25
+ authUrl = process.env.AUTH_URL,
26
+ clientId = process.env.CLIENT_ID,
27
+ clientSecret = process.env.CLIENT_SECRET,
28
+ clientUrl = process.env.CLIENT_URL,
29
+ redirectUri = process.env.REDIRECT_URI,
30
+ appName = process.env.APP_NAME,
31
+ } = options;
32
+
33
+ return async (req, res, next) => {
34
+ try {
35
+ if (!["/api/auth", "/api/callback"].includes(req.path)) {
36
+ return next();
37
+ }
38
+
39
+ if (req.path === "/api/auth") {
40
+ const authClientUrl = `${clientUrl}/signin`;
41
+ const redirectUrl = `${authClientUrl}?response_type=code&appName=${appName}&client_id=${clientId}&redirect_uri=${encodeURIComponent(
42
+ redirectUri
43
+ )}`;
44
+ res.status(200).json({redirectUrl});
45
+ }
46
+
47
+ if (req.path === "/api/refreshToken") {
48
+ const refreshToken = req.cookies["x-refresh-token"];
49
+ if (!refreshToken) {
50
+ return res.status(401).json({error: "No refresh token provided"});
51
+ }
52
+
53
+ const {accountData, access, refresh} = await post(`${authUrl}/api/v1/auth/refreshTokens`, {
54
+ refreshToken
55
+ }, {
56
+ actionType: "refresh",
57
+ });
58
+
59
+
60
+ const currentDateTime = new Date();
51
61
 
52
- const {tokens, account, redirectUrl} = await exchangeToken(
53
- authUrl,
54
- code,
55
- clientId,
56
- clientSecret,
57
- redirectUri
58
- );
62
+ const refreshMaxAge = new Date(refresh.expires).getTime() - currentDateTime.getTime();
59
63
 
60
- await checkIfUserExists(userSchema, account.accountId);
64
+ res.cookie("x-refresh-token", refresh.token, {
65
+ httpOnly: true,
66
+ secure: process.env.NODE_ENV === "production",
67
+ maxAge: refreshMaxAge
68
+ });
61
69
 
62
- const currentDateTime = new Date();
70
+ const accessMaxAge = new Date(access.expires).getTime() - currentDateTime.getTime();
63
71
 
64
- const refreshMaxAge = new Date(tokens.refresh.expires).getTime() - currentDateTime.getTime();
72
+ res.cookie("x-access-token", access.token, {
73
+ httpOnly: true,
74
+ secure: process.env.NODE_ENV === "production",
75
+ maxAge: accessMaxAge
76
+ });
65
77
 
66
- res.cookie("x-refresh-token", tokens.refresh.token, {
67
- httpOnly: true,
68
- secure: process.env.NODE_ENV === "production",
69
- maxAge: refreshMaxAge
70
- });
78
+ return res.status(200).json({message: "Token refreshed successfully"});
79
+ }
71
80
 
72
- const accessMaxAge = new Date(tokens.access.expires).getTime() - currentDateTime.getTime();
81
+ if (req.path === "/api/callback") {
82
+ const code = req.query.code;
83
+ if (!code) {
84
+ return res.status(400).send("No code received");
85
+ }
73
86
 
74
- res.cookie("x-access-token", tokens.access.token, {
75
- httpOnly: true,
76
- secure: process.env.NODE_ENV === "production",
77
- maxAge: accessMaxAge
78
- });
87
+ const {tokens, account, redirectUrl} = await exchangeToken(
88
+ authUrl,
89
+ code,
90
+ clientId,
91
+ clientSecret,
92
+ redirectUri
93
+ );
79
94
 
80
- const urlToRedirect = `http://${redirectUrl}/`;
95
+ await checkIfUserExists(userSchema, account.accountId);
81
96
 
82
- return res.redirect(urlToRedirect);
83
- }
84
- } catch (error) {
85
- console.error("Error in proproAuthMiddleware:", error);
86
- res.status(401).send("Unauthorized: Invalid or expired token");
87
- }
88
- };
97
+ const currentDateTime = new Date();
98
+
99
+ const refreshMaxAge = new Date(tokens.refresh.expires).getTime() - currentDateTime.getTime();
100
+
101
+ res.cookie("x-refresh-token", tokens.refresh.token, {
102
+ httpOnly: true,
103
+ secure: process.env.NODE_ENV === "production",
104
+ maxAge: refreshMaxAge
105
+ });
106
+
107
+ const accessMaxAge = new Date(tokens.access.expires).getTime() - currentDateTime.getTime();
108
+
109
+ res.cookie("x-access-token", tokens.access.token, {
110
+ httpOnly: true,
111
+ secure: process.env.NODE_ENV === "production",
112
+ maxAge: accessMaxAge
113
+ });
114
+
115
+ const urlToRedirect = `http://${redirectUrl}/`;
116
+
117
+ return res.redirect(urlToRedirect);
118
+ }
119
+ } catch (error) {
120
+ console.error("Error in proproAuthMiddleware:", error);
121
+ res.status(401).send("Unauthorized: Invalid or expired token");
122
+ }
123
+ };
89
124
  }
90
125
 
91
126
  module.exports = proproAuthMiddleware;