@gneiss/client-auth 1.0.4 → 1.0.5
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/dist/cjs/index.js +382 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/esm/index.js +343 -0
- package/dist/esm/index.js.map +7 -0
- package/dist/types/src/config.d.ts +5 -0
- package/dist/types/src/config.d.ts.map +1 -0
- package/dist/types/src/core/AuthGneissCore.d.ts +53 -0
- package/dist/types/src/core/AuthGneissCore.d.ts.map +1 -0
- package/dist/types/src/core/index.d.ts +5 -0
- package/dist/types/src/core/index.d.ts.map +1 -0
- package/dist/types/src/core/types.d.ts +20 -0
- package/dist/types/src/core/types.d.ts.map +1 -0
- package/dist/types/src/frameworks/express/middleware/ExpressAuthGneissClient.d.ts +64 -0
- package/dist/types/src/frameworks/express/middleware/ExpressAuthGneissClient.d.ts.map +1 -0
- package/dist/types/src/frameworks/index.d.ts +3 -0
- package/dist/types/src/frameworks/index.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +5 -0
- package/dist/types/src/index.d.ts.map +1 -0
- package/dist/types/src/utils/index.d.ts +2 -0
- package/dist/types/src/utils/index.d.ts.map +1 -0
- package/dist/types/src/utils/storage/cookieHandling.d.ts +20 -0
- package/dist/types/src/utils/storage/cookieHandling.d.ts.map +1 -0
- package/dist/types/tests/frameworks/express/middleware/ExpressAuthGneissClient.integration.test.d.ts +2 -0
- package/dist/types/tests/frameworks/express/middleware/ExpressAuthGneissClient.integration.test.d.ts.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
AuthGneissCore: () => AuthGneissCore_default,
|
|
34
|
+
ExpressAuthGneissClient: () => ExpressAuthGneissClient_default,
|
|
35
|
+
parseCookies: () => parseCookies
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(index_exports);
|
|
38
|
+
|
|
39
|
+
// src/core/AuthGneissCore.ts
|
|
40
|
+
var import_axios = __toESM(require("axios"), 1);
|
|
41
|
+
var import_dotenv = __toESM(require("dotenv"), 1);
|
|
42
|
+
var import_axios2 = require("axios");
|
|
43
|
+
|
|
44
|
+
// src/config.ts
|
|
45
|
+
var config = {
|
|
46
|
+
authUrl: process.env.ENV === "prod" ? "auth.gneiss.io" : process.env.ENV === "staging" ? "auth.gneiss.io/testing" : "localhost:5000"
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// src/core/AuthGneissCore.ts
|
|
50
|
+
if (!process.env.ENV) {
|
|
51
|
+
import_dotenv.default.config();
|
|
52
|
+
}
|
|
53
|
+
var AuthGneissCore = class {
|
|
54
|
+
constructor(devConfig) {
|
|
55
|
+
this.config = { ...devConfig, ...config };
|
|
56
|
+
this.authUrl = this.config.authUrl;
|
|
57
|
+
this.loginUrl = this.authUrl ? `${this.authUrl}/auth/login` : void 0;
|
|
58
|
+
this.logoutUrl = this.authUrl ? `${this.authUrl}/auth/logout` : void 0;
|
|
59
|
+
let errorMsgs = [];
|
|
60
|
+
if (!process.env.ENV) {
|
|
61
|
+
errorMsgs.push("ENV is not set in environment variables");
|
|
62
|
+
}
|
|
63
|
+
if (errorMsgs.length > 0) {
|
|
64
|
+
throw new Error(errorMsgs.join("\n"));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* getTokens is a method that exchanges an authentication code for access and refresh tokens.
|
|
69
|
+
* The client id and secret are passed as basic auth headers to authenticate the client itself.
|
|
70
|
+
* @param authCode - The authentication code received from the Gneiss authentication service.
|
|
71
|
+
* @returns A promise that resolves to an object containing the access and refresh tokens.
|
|
72
|
+
*/
|
|
73
|
+
async getTokens(authCode) {
|
|
74
|
+
try {
|
|
75
|
+
const url = `${this.authUrl}/auth/access_token?auth_code=${authCode}`;
|
|
76
|
+
const encodedClientId = btoa(this.config.clientId);
|
|
77
|
+
const encodedClientSecret = btoa(this.config.clientSecret);
|
|
78
|
+
const response = await import_axios.default.post(url, {}, {
|
|
79
|
+
headers: {
|
|
80
|
+
"Authorization": `Basic ${encodedClientId}:${encodedClientSecret}`
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
return {
|
|
84
|
+
accessToken: response.data.access_token,
|
|
85
|
+
refreshToken: response.data.refresh_token,
|
|
86
|
+
tokenType: response.data.token_type
|
|
87
|
+
};
|
|
88
|
+
} catch (error) {
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* refreshToken is a method that refreshes the access token using the refresh token.
|
|
94
|
+
* @param refreshToken - The refresh token to be used for token refresh.
|
|
95
|
+
* @returns A promise that resolves to the refreshed access token.
|
|
96
|
+
*/
|
|
97
|
+
async refreshToken(refreshToken) {
|
|
98
|
+
try {
|
|
99
|
+
const url = `${this.authUrl}/auth/refresh`;
|
|
100
|
+
const response = await import_axios.default.post(url, {}, {
|
|
101
|
+
headers: {
|
|
102
|
+
"Authorization": `Bearer ${refreshToken}`
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
return response.data.access_token;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* getUserData is a method that fetches user data using the access token.
|
|
112
|
+
* @param accessToken - The access token to be used for user data fetching.
|
|
113
|
+
* @returns A promise that resolves to the user data.
|
|
114
|
+
*/
|
|
115
|
+
async getUserData(accessToken) {
|
|
116
|
+
const url = `${this.authUrl}/resource/user_data`;
|
|
117
|
+
const response = await import_axios.default.get(url, {
|
|
118
|
+
headers: {
|
|
119
|
+
"Authorization": `Bearer ${accessToken}`
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
if (response.status === 200) {
|
|
123
|
+
return response.data;
|
|
124
|
+
}
|
|
125
|
+
throw new Error("Failed to fetch user data");
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* validateToken is a method that validates the access token.
|
|
129
|
+
* @param token - The access token to be validated.
|
|
130
|
+
* @returns A promise that resolves to a boolean indicating the validity of the token.
|
|
131
|
+
*/
|
|
132
|
+
async validateToken(token) {
|
|
133
|
+
try {
|
|
134
|
+
console.log("DEBUG: token", token);
|
|
135
|
+
if (!token) {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
const url = `${this.authUrl}/auth/validate_token`;
|
|
139
|
+
const response = await import_axios.default.get(url, {
|
|
140
|
+
headers: {
|
|
141
|
+
"Authorization": `Bearer ${token}`
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
return response.status === 200;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error instanceof import_axios2.AxiosError && error.response?.status === 401) {
|
|
147
|
+
return false;
|
|
148
|
+
} else {
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* getLoginUrl is a method that returns the login URL.
|
|
155
|
+
* @returns The login URL.
|
|
156
|
+
*/
|
|
157
|
+
getLoginUrl() {
|
|
158
|
+
return this.loginUrl;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* deleteUser deletes the user
|
|
162
|
+
* */
|
|
163
|
+
async deleteUserData(accessToken) {
|
|
164
|
+
const response = await import_axios.default.post(`${this.authUrl}/resource/delete_user`, {}, {
|
|
165
|
+
headers: {
|
|
166
|
+
"Authorization": `Bearer ${accessToken}`
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
return response.data;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
var AuthGneissCore_default = AuthGneissCore;
|
|
173
|
+
|
|
174
|
+
// src/utils/storage/cookieHandling.ts
|
|
175
|
+
var import_jsonwebtoken = require("jsonwebtoken");
|
|
176
|
+
function setAccessToken(res, accessToken) {
|
|
177
|
+
const decodedToken = (0, import_jsonwebtoken.decode)(accessToken);
|
|
178
|
+
if (!decodedToken.exp) {
|
|
179
|
+
throw new Error("Access token does not contain an expiration time");
|
|
180
|
+
}
|
|
181
|
+
res.cookie("accessToken", accessToken, {
|
|
182
|
+
httpOnly: true,
|
|
183
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
184
|
+
sameSite: "lax",
|
|
185
|
+
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
function setRefreshToken(res, refreshToken) {
|
|
189
|
+
const decodedToken = (0, import_jsonwebtoken.decode)(refreshToken);
|
|
190
|
+
if (!decodedToken.exp) {
|
|
191
|
+
throw new Error("Refresh token does not contain an expiration time");
|
|
192
|
+
}
|
|
193
|
+
res.cookie("refreshToken", refreshToken, {
|
|
194
|
+
httpOnly: true,
|
|
195
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
196
|
+
sameSite: "lax",
|
|
197
|
+
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
function parseCookies(req) {
|
|
201
|
+
const cookies = req.headers.cookie;
|
|
202
|
+
if (!cookies) {
|
|
203
|
+
return {};
|
|
204
|
+
}
|
|
205
|
+
return cookies.split(";").reduce((acc, cookie) => {
|
|
206
|
+
const [key, value] = cookie.split("=").map((s) => s.trim());
|
|
207
|
+
acc[key] = value;
|
|
208
|
+
return acc;
|
|
209
|
+
}, {});
|
|
210
|
+
}
|
|
211
|
+
function clearCookies(res) {
|
|
212
|
+
res.clearCookie("accessToken", {
|
|
213
|
+
httpOnly: true,
|
|
214
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
215
|
+
sameSite: "strict",
|
|
216
|
+
path: "/"
|
|
217
|
+
});
|
|
218
|
+
res.clearCookie("refreshToken", {
|
|
219
|
+
httpOnly: true,
|
|
220
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
221
|
+
sameSite: "strict",
|
|
222
|
+
path: "/"
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// src/frameworks/express/middleware/ExpressAuthGneissClient.ts
|
|
227
|
+
var import_axios3 = require("axios");
|
|
228
|
+
var import_axios4 = __toESM(require("axios"), 1);
|
|
229
|
+
var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
230
|
+
constructor(config2) {
|
|
231
|
+
super(config2);
|
|
232
|
+
this.requireAuth = this.requireAuth.bind(this);
|
|
233
|
+
this.handleCallBack = this.handleCallBack.bind(this);
|
|
234
|
+
this.login = this.login.bind(this);
|
|
235
|
+
this.logout = this.logout.bind(this);
|
|
236
|
+
this.getUser = this.getUser.bind(this);
|
|
237
|
+
this.deleteUser = this.deleteUser.bind(this);
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* requireAuth is a middleware function that checks if the access token is valid.
|
|
241
|
+
* If the access token is not valid, it attempts to refresh the token using the refresh token.
|
|
242
|
+
* If the refresh token is not valid, it redirects the user to the login page.
|
|
243
|
+
* @param req - The request object.
|
|
244
|
+
* @param res - The response object.
|
|
245
|
+
* @param next - The next middleware function.
|
|
246
|
+
*/
|
|
247
|
+
async requireAuth(req, res, next) {
|
|
248
|
+
const cookies = parseCookies(req);
|
|
249
|
+
console.log("DEBUG: cookies", cookies);
|
|
250
|
+
try {
|
|
251
|
+
const isAccessTokenValid = await this.validateToken(cookies?.accessToken);
|
|
252
|
+
if (!isAccessTokenValid) {
|
|
253
|
+
const newAccessToken = await this.refreshToken(cookies?.refreshToken);
|
|
254
|
+
if (newAccessToken) {
|
|
255
|
+
setAccessToken(res, newAccessToken);
|
|
256
|
+
res.redirect(req.originalUrl);
|
|
257
|
+
} else {
|
|
258
|
+
const returnToUrl = req.originalUrl;
|
|
259
|
+
res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}&return_to_url=${returnToUrl}`);
|
|
260
|
+
}
|
|
261
|
+
} else {
|
|
262
|
+
next();
|
|
263
|
+
}
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (error instanceof import_axios3.AxiosError) {
|
|
266
|
+
res.status(error.response?.status || 500).send(error.response?.data || "Internal server error");
|
|
267
|
+
} else {
|
|
268
|
+
res.status(500).send("Internal server error");
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* getUserData is a middleware function that fetches user data using the access token.
|
|
274
|
+
* @param req - The request object.
|
|
275
|
+
* @param res - The response object.
|
|
276
|
+
* @param next - The next middleware function.
|
|
277
|
+
*/
|
|
278
|
+
async getUser(req, res) {
|
|
279
|
+
const cookies = parseCookies(req);
|
|
280
|
+
const accessToken = cookies?.accessToken;
|
|
281
|
+
if (!accessToken) {
|
|
282
|
+
throw new Error("No access token found in request cookies");
|
|
283
|
+
}
|
|
284
|
+
const userData = await this.getUserData(accessToken);
|
|
285
|
+
res.status(200).send(userData);
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* handleCallBack is a middleware function that handles the callback from the authentication service.
|
|
289
|
+
* It extracts the auth code from the request URL parameters, exchanges it for tokens, and sets the access and refresh tokens in the response cookies.
|
|
290
|
+
* @param req - The request object.
|
|
291
|
+
* @param res - The response object.
|
|
292
|
+
* @param next - The next middleware function.
|
|
293
|
+
*/
|
|
294
|
+
async handleCallBack(req, res, next) {
|
|
295
|
+
try {
|
|
296
|
+
const authCode = req.query.auth_code;
|
|
297
|
+
const returnToUrl = req.query.return_to_url;
|
|
298
|
+
if (!authCode) {
|
|
299
|
+
throw new Error("No auth code found in request url parameters");
|
|
300
|
+
}
|
|
301
|
+
const tokens = await this.getTokens(authCode);
|
|
302
|
+
setAccessToken(res, tokens.accessToken);
|
|
303
|
+
setRefreshToken(res, tokens.refreshToken);
|
|
304
|
+
if (returnToUrl) {
|
|
305
|
+
res.redirect(returnToUrl);
|
|
306
|
+
} else {
|
|
307
|
+
res.redirect("/");
|
|
308
|
+
}
|
|
309
|
+
} catch (error) {
|
|
310
|
+
if (error instanceof import_axios3.AxiosError) {
|
|
311
|
+
res.status(error.response?.status || 500).send(error.response?.data || "Internal server error");
|
|
312
|
+
console.error("DEBUG: error", error);
|
|
313
|
+
} else {
|
|
314
|
+
res.status(500).send("Internal server error");
|
|
315
|
+
console.error("DEBUG: error", error);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* login is a function that redirects the user to the Gneiss authentication service for authentication.
|
|
321
|
+
* @param req - The request object.
|
|
322
|
+
* @param res - The response object.
|
|
323
|
+
*/
|
|
324
|
+
login(req, res) {
|
|
325
|
+
try {
|
|
326
|
+
if (!this.loginUrl) {
|
|
327
|
+
throw new Error("Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.");
|
|
328
|
+
}
|
|
329
|
+
res.redirect(this.loginUrl + `?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}`);
|
|
330
|
+
} catch (error) {
|
|
331
|
+
console.error("Error in login middleware:", error);
|
|
332
|
+
res.status(500).send("Internal server error");
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* logout is a function that redirects the user to the Gneiss logout service.
|
|
337
|
+
* @param req - The request object.
|
|
338
|
+
* @param res - The response object.
|
|
339
|
+
*/
|
|
340
|
+
logout(req, res) {
|
|
341
|
+
const cookies = parseCookies(req);
|
|
342
|
+
try {
|
|
343
|
+
if (!this.logoutUrl) {
|
|
344
|
+
throw new Error("Logout URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.");
|
|
345
|
+
}
|
|
346
|
+
if (cookies?.accessToken) {
|
|
347
|
+
import_axios4.default.post(this.logoutUrl, {}, {
|
|
348
|
+
// Logout
|
|
349
|
+
headers: {
|
|
350
|
+
"Authorization": `Bearer ${cookies?.accessToken}`
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
clearCookies(res);
|
|
355
|
+
res.redirect("/");
|
|
356
|
+
} catch (error) {
|
|
357
|
+
console.error("Error in logout middleware:", error);
|
|
358
|
+
res.status(500).send("Internal server error");
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Utility route handler for deleting a user
|
|
363
|
+
* This ensures that the user is fully logged out before
|
|
364
|
+
* deleting the user's data
|
|
365
|
+
*
|
|
366
|
+
* @param req - The request object.
|
|
367
|
+
* @param res - The response object.
|
|
368
|
+
*/
|
|
369
|
+
deleteUser(req, res) {
|
|
370
|
+
const cookies = parseCookies(req);
|
|
371
|
+
this.logout(req, res);
|
|
372
|
+
this.deleteUserData(cookies?.accessToken);
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
var ExpressAuthGneissClient_default = ExpressAuthGneissClient;
|
|
376
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
377
|
+
0 && (module.exports = {
|
|
378
|
+
AuthGneissCore,
|
|
379
|
+
ExpressAuthGneissClient,
|
|
380
|
+
parseCookies
|
|
381
|
+
});
|
|
382
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/index.ts", "../../src/core/AuthGneissCore.ts", "../../src/config.ts", "../../src/utils/storage/cookieHandling.ts", "../../src/frameworks/express/middleware/ExpressAuthGneissClient.ts"],
|
|
4
|
+
"sourcesContent": ["export { ExpressAuthGneissClient } from \"./frameworks\";\nexport { AuthGneissCore } from \"./core\";\nexport { parseCookies } from \"@utils\"\nexport type { AuthGneissCoreConfig } from \"./core\";\n", "import { AuthGneissCoreConfig } from \"@core/types\";\nimport axios, { AxiosResponse } from \"axios\";\nimport { Tokens } from \"@core/types\";\nimport dotenv from \"dotenv\";\nimport { AxiosError } from \"axios\";\nimport { config as generalConfig } from \"@/config\";\nimport { AuthGneissGeneralConfig } from \"@/config\";\n\n//load environment variables if not already set\nif (!process.env.ENV) {\n dotenv.config();\n}\n\n/**\n * AuthGneissCore provides core functionality for OAuth2 authentication flow with Gneiss authentication service.\n * It handles token exchange, token refresh, user data fetching, and token validation.\n * \n * This class serves as a base class that can be extended by framework-specific implementations\n * to provide authentication middleware and handlers.\n */\nclass AuthGneissCore {\n protected config: AuthGneissCoreConfig & AuthGneissGeneralConfig; // Configuration object\n protected authUrl : string | undefined\n protected loginUrl : string | undefined\n protected logoutUrl : string | undefined\n\n constructor(\n devConfig: AuthGneissCoreConfig\n ) {\n this.config = {...devConfig, ...generalConfig};\n this.authUrl = this.config.authUrl // Gneiss endpoint\n this.loginUrl = this.authUrl ? `${this.authUrl}/auth/login` : undefined; // Login URL\n this.logoutUrl = this.authUrl ? `${this.authUrl}/auth/logout` : undefined; // Logout URL\n\n //check if environment variables are set\n let errorMsgs = [];\n if (!process.env.ENV) {\n errorMsgs.push(\"ENV is not set in environment variables\");\n }\n if (errorMsgs.length > 0) {\n throw new Error(errorMsgs.join(\"\\n\"));\n }\n }\n\n /**\n * getTokens is a method that exchanges an authentication code for access and refresh tokens.\n * The client id and secret are passed as basic auth headers to authenticate the client itself.\n * @param authCode - The authentication code received from the Gneiss authentication service.\n * @returns A promise that resolves to an object containing the access and refresh tokens.\n */\n protected async getTokens(authCode : string) : Promise<Tokens> {\n try {\n const url : string = `${this.authUrl}/auth/access_token?auth_code=${authCode}`;\n //Encode in base64 before transport\n const encodedClientId = btoa(this.config.clientId);\n const encodedClientSecret = btoa(this.config.clientSecret);\n const response : AxiosResponse = await axios.post(url, {}, {\n headers: {\n \"Authorization\": `Basic ${encodedClientId}:${encodedClientSecret}`\n }\n });\n return {\n accessToken: response.data.access_token,\n refreshToken: response.data.refresh_token,\n tokenType: response.data.token_type\n } as Tokens;\n } catch (error) {\n // console.error(\"Error in getTokens:\", error);\n throw error;\n }\n }\n \n /**\n * refreshToken is a method that refreshes the access token using the refresh token.\n * @param refreshToken - The refresh token to be used for token refresh.\n * @returns A promise that resolves to the refreshed access token.\n */\n protected async refreshToken(refreshToken: string): Promise<string | null> {\n try {\n const url : string = `${this.authUrl}/auth/refresh`;\n const response : AxiosResponse = await axios.post(url, {}, {\n headers: {\n \"Authorization\": `Bearer ${refreshToken}`\n }\n });\n return response.data.access_token as string;\n } catch (error) {\n // console.error(\"Error in refreshToken:\", error);\n return null;\n }\n }\n \n /**\n * getUserData is a method that fetches user data using the access token.\n * @param accessToken - The access token to be used for user data fetching.\n * @returns A promise that resolves to the user data.\n */\n async getUserData(accessToken: string) {\n const url : string = `${this.authUrl}/resource/user_data`;\n const response : AxiosResponse = await axios.get(url, {\n headers: {\n \"Authorization\": `Bearer ${accessToken}`\n }\n });\n if (response.status === 200) {\n return response.data;\n }\n throw new Error(\"Failed to fetch user data\");\n }\n \n /**\n * validateToken is a method that validates the access token.\n * @param token - The access token to be validated.\n * @returns A promise that resolves to a boolean indicating the validity of the token.\n */\n protected async validateToken(token: string): Promise<boolean> {\n try {\n console.log(\"DEBUG: token\", token);\n // Token validation logic\n if (!token) {\n return false;\n }\n const url : string = `${this.authUrl}/auth/validate_token`;\n const response : AxiosResponse = await axios.get(url, {\n headers: {\n \"Authorization\": `Bearer ${token}`\n }\n });\n return response.status === 200;\n } catch (error) {\n // console.error(\"Error in validateToken:\", error);\n if (error instanceof AxiosError && error.response?.status === 401) {\n return false;\n } else {\n throw error;\n }\n }\n }\n\n /**\n * getLoginUrl is a method that returns the login URL.\n * @returns The login URL.\n */\n public getLoginUrl() : string | undefined {\n return this.loginUrl;\n }\n\n /**\n * deleteUser deletes the user\n * */\n protected async deleteUserData(accessToken : string) : Promise<object> {\n const response : AxiosResponse = await axios.post(`${this.authUrl}/resource/delete_user`, {}, {\n headers: {\n \"Authorization\": `Bearer ${accessToken}`\n } \n });\n return response.data;\n }\n}\n\nexport default AuthGneissCore;\n", "export type AuthGneissGeneralConfig = {\n authUrl: string\n}\n\nexport const config : AuthGneissGeneralConfig = {\n authUrl: process.env.ENV === \"prod\" ? \"auth.gneiss.io\" : \n process.env.ENV === \"staging\" ? \"auth.gneiss.io/testing\" : \"localhost:5000\"\n}", "import { Response } from \"express\";\nimport { JwtPayload, decode } from \"jsonwebtoken\";\nimport { Request } from \"express\";\n\n/**\n * Set the access token in the response cookies.\n * @param res - The response object.\n * @param accessToken - The access token to set.\n */\nfunction setAccessToken(res: Response, accessToken: string) {\n\n const decodedToken = decode(accessToken) as JwtPayload;\n \n // decoded.exp is in seconds since epoch\n // Date.now() returns milliseconds since epoch\n // maxAge needs milliseconds remaining\n if (!decodedToken.exp) {\n throw new Error(\"Access token does not contain an expiration time\");\n }\n \n res.cookie('accessToken', accessToken, {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'lax',\n maxAge: (decodedToken.exp * 1000) - Date.now()\n });\n}\n\n/**\n * Set the refresh token in the response cookies.\n * @param res - The response object.\n * @param refreshToken - The refresh token to set.\n */\nfunction setRefreshToken(res: Response, refreshToken: string) {\n\n const decodedToken = decode(refreshToken) as JwtPayload;\n\n if (!decodedToken.exp) {\n throw new Error(\"Refresh token does not contain an expiration time\");\n }\n\n res.cookie('refreshToken', refreshToken, {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'lax',\n maxAge: (decodedToken.exp * 1000) - Date.now()\n });\n}\n\nfunction parseCookies(req: Request) : { [key: string]: string } {\n const cookies = req.headers.cookie;\n if (!cookies) {\n return {};\n }\n return cookies.split(';').reduce((acc: { [key: string]: string }, cookie) => {\n const [key, value] = cookie.split('=').map(s => s.trim());\n acc[key] = value;\n return acc;\n }, {});\n}\n\nfunction clearCookies(res: Response) {\n res.clearCookie(\"accessToken\", {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'strict',\n path: '/'\n });\n res.clearCookie(\"refreshToken\", {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'strict',\n path: '/'\n });\n}\n\nexport { setAccessToken, setRefreshToken, parseCookies, clearCookies };\n", "import { AuthGneissCore, AuthGneissCoreConfig } from \"@core\";\nimport { Request, Response, NextFunction } from \"express\";\nimport { RequestWithTokens, Tokens } from \"@core/types\";\nimport { setAccessToken, setRefreshToken, parseCookies } from \"@utils\";\nimport { JwtPayload } from \"jsonwebtoken\";\nimport { AxiosError } from \"axios\";\nimport axios from \"axios\";\nimport { clearCookies } from \"@/utils/storage/cookieHandling\";\n\n/**\n * ExpressAuthGneissClient extends AuthGneissCore to provide Express-specific authentication middleware\n * and functionality for handling OAuth2 authentication flow with Gneiss authentication service.\n * \n * @extends AuthGneissCore\n * @example\n * const authClient = new ExpressAuthGneissClient({\n * clientId: 'your-client-id',\n * clientSecret: 'your-client-secret',\n * redirectUrl: 'your-redirect-url'\n * });\n */\nclass ExpressAuthGneissClient extends AuthGneissCore {\n\n constructor(\n config: AuthGneissCoreConfig\n ) {\n super(config);\n \n // Bind the methods in constructor\n this.requireAuth = this.requireAuth.bind(this);\n this.handleCallBack = this.handleCallBack.bind(this);\n this.login = this.login.bind(this);\n this.logout = this.logout.bind(this);\n this.getUser = this.getUser.bind(this);\n this.deleteUser = this.deleteUser.bind(this)\n }\n\n /**\n * requireAuth is a middleware function that checks if the access token is valid.\n * If the access token is not valid, it attempts to refresh the token using the refresh token.\n * If the refresh token is not valid, it redirects the user to the login page.\n * @param req - The request object.\n * @param res - The response object.\n * @param next - The next middleware function.\n */\n public async requireAuth(req: Request, res: Response, next: NextFunction): Promise<void> {\n const cookies = parseCookies(req);\n //Check for the existence of the access token\n console.log(\"DEBUG: cookies\", cookies);\n try {\n const isAccessTokenValid : boolean = await this.validateToken(cookies?.accessToken);\n if (!isAccessTokenValid) { //if the access token is not valid\n //try to refresh the token\n const newAccessToken : string | null = await this.refreshToken(cookies?.refreshToken);\n if (newAccessToken) { // set access token and then redirect to the original requested url to 'redo' the request with new access token\n setAccessToken(res, newAccessToken);\n res.redirect(req.originalUrl)\n }\n else {\n // no access token or valid refresh token, redirect to login\n const returnToUrl : string | undefined = req.originalUrl as string;\n res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}&return_to_url=${returnToUrl}`);\n }\n }\n else {\n // access token is valid, continue to the next middleware or route handler\n next();\n }\n } catch (error) {\n // console.error('Error in requireAuth middleware:', error);\n if (error instanceof AxiosError) {\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\n } else {\n res.status(500).send('Internal server error');\n }\n }\n }\n\n /**\n * getUserData is a middleware function that fetches user data using the access token.\n * @param req - The request object.\n * @param res - The response object.\n * @param next - The next middleware function.\n */\n public async getUser(req: Request, res: Response): Promise<void> {\n const cookies = parseCookies(req);\n const accessToken = cookies?.accessToken;\n if (!accessToken) {\n throw new Error(\"No access token found in request cookies\");\n }\n const userData = await this.getUserData(accessToken);\n res.status(200).send(userData);\n }\n\n /**\n * handleCallBack is a middleware function that handles the callback from the authentication service.\n * It extracts the auth code from the request URL parameters, exchanges it for tokens, and sets the access and refresh tokens in the response cookies.\n * @param req - The request object.\n * @param res - The response object.\n * @param next - The next middleware function.\n */\n public async handleCallBack(\n req: Request,\n res: Response,\n next: NextFunction\n ): Promise<void> {\n try {\n const authCode: string | undefined = req.query.auth_code as string\n const returnToUrl : string | undefined = req.query.return_to_url as string;\n if (!authCode) {\n throw new Error(\"No auth code found in request url parameters\");\n }\n\n const tokens: Tokens = await this.getTokens(authCode);\n \n // Set the access and refresh tokens in the response cookies\n setAccessToken(res, tokens.accessToken);\n setRefreshToken(res, tokens.refreshToken);\n\n if (returnToUrl) {\n // Go to the original request url\n res.redirect(returnToUrl);\n }\n else {\n // Go to the root url\n res.redirect(\"/\")\n }\n } catch (error) {\n // console.error('Error in handleCallBack middleware:', error);\n if (error instanceof AxiosError) {\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\n console.error(\"DEBUG: error\", error);\n } else {\n res.status(500).send('Internal server error');\n console.error(\"DEBUG: error\", error);\n }\n }\n }\n\n /**\n * login is a function that redirects the user to the Gneiss authentication service for authentication.\n * @param req - The request object.\n * @param res - The response object.\n */\n public login(req: Request, res: Response): void {\n try {\n if (!this.loginUrl) {\n throw new Error('Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\n }\n res.redirect(this.loginUrl + `?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}`);\n } catch (error) {\n console.error('Error in login middleware:', error);\n res.status(500).send('Internal server error');\n }\n }\n\n /**\n * logout is a function that redirects the user to the Gneiss logout service.\n * @param req - The request object.\n * @param res - The response object.\n */\n public logout(req: Request, res: Response): void {\n const cookies = parseCookies(req);\n try {\n if (!this.logoutUrl) {\n throw new Error('Logout URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\n }\n if (cookies?.accessToken) { // Only logout if the access token exists\n axios.post(this.logoutUrl, {}, { // Logout\n headers: {\n \"Authorization\": `Bearer ${cookies?.accessToken}`\n }\n });\n }\n clearCookies(res); // clear the access and refresh cookies\n res.redirect(\"/\") // Redirect back to home after logout\n } catch (error) {\n console.error('Error in logout middleware:', error);\n res.status(500).send('Internal server error');\n }\n }\n\n /**\n * Utility route handler for deleting a user\n * This ensures that the user is fully logged out before \n * deleting the user's data\n * \n * @param req - The request object.\n * @param res - The response object.\n */\n public deleteUser(req: Request, res: Response) {\n const cookies = parseCookies(req);\n this.logout(req, res)\n this.deleteUserData(cookies?.accessToken)\n }\n}\n\nexport default ExpressAuthGneissClient;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,mBAAqC;AAErC,oBAAmB;AACnB,IAAAA,gBAA2B;;;ACApB,IAAM,SAAmC;AAAA,EAC5C,SAAS,QAAQ,IAAI,QAAQ,SAAS,mBACtC,QAAQ,IAAI,QAAQ,YAAY,2BAA2B;AAC/D;;;ADEA,IAAI,CAAC,QAAQ,IAAI,KAAK;AAClB,gBAAAC,QAAO,OAAO;AAClB;AASA,IAAM,iBAAN,MAAqB;AAAA,EAMjB,YACI,WACF;AACE,SAAK,SAAS,EAAC,GAAG,WAAW,GAAG,OAAa;AAC7C,SAAK,UAAU,KAAK,OAAO;AAC3B,SAAK,WAAW,KAAK,UAAU,GAAG,KAAK,OAAO,gBAAgB;AAC9D,SAAK,YAAY,KAAK,UAAU,GAAG,KAA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,SAAS,OAAO;AACZ,cAAQ,MAAM,8BAA8B,KAAK;AACjD,UAAI,OAAO,GAAG,EAAE,KAAK,uBAAuB;AAAA,IAChD;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,OAAO,KAAc,KAAqB;AAC7C,UAAM,UAAU,aAAa,GAAG;AAChC,QAAI;AACA,UAAI,CAAC,KAAK,WAAW;AACjB,cAAM,IAAI,MAAM,qFAAqF;AAAA,MACzG;AACA,UAAI,SAAS,aAAa;AACtB,sBAAAC,QAAM,KAAK,KAAK,WAAW,CAAC,GAAG;AAAA;AAAA,UAC3B,SAAS;AAAA,YACL,iBAAiB,UAAU,SAAS,WAAW;AAAA,UACnD;AAAA,QACJ,CAAC;AAAA,MACL;AACA,mBAAa,GAAG;AAChB,UAAI,SAAS,GAAG;AAAA,IACpB,SAAS,OAAO;AACZ,cAAQ,MAAM,+BAA+B,KAAK;AAClD,UAAI,OAAO,GAAG,EAAE,KAAK,uBAAuB;AAAA,IAChD;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUO,WAAW,KAAc,KAAe;AAC3C,UAAM,UAAU,aAAa,GAAG;AAChC,SAAK,OAAO,KAAK,GAAG;AACpB,SAAK,eAAe,SAAS,WAAW;AAAA,EAC5C;AACJ;AAEA,IAAO,kCAAQ;",
|
|
6
|
+
"names": ["import_axios", "dotenv", "axios", "import_axios", "config", "axios"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// src/core/AuthGneissCore.ts
|
|
2
|
+
import axios from "axios";
|
|
3
|
+
import dotenv from "dotenv";
|
|
4
|
+
import { AxiosError } from "axios";
|
|
5
|
+
|
|
6
|
+
// src/config.ts
|
|
7
|
+
var config = {
|
|
8
|
+
authUrl: process.env.ENV === "prod" ? "auth.gneiss.io" : process.env.ENV === "staging" ? "auth.gneiss.io/testing" : "localhost:5000"
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// src/core/AuthGneissCore.ts
|
|
12
|
+
if (!process.env.ENV) {
|
|
13
|
+
dotenv.config();
|
|
14
|
+
}
|
|
15
|
+
var AuthGneissCore = class {
|
|
16
|
+
constructor(devConfig) {
|
|
17
|
+
this.config = { ...devConfig, ...config };
|
|
18
|
+
this.authUrl = this.config.authUrl;
|
|
19
|
+
this.loginUrl = this.authUrl ? `${this.authUrl}/auth/login` : void 0;
|
|
20
|
+
this.logoutUrl = this.authUrl ? `${this.authUrl}/auth/logout` : void 0;
|
|
21
|
+
let errorMsgs = [];
|
|
22
|
+
if (!process.env.ENV) {
|
|
23
|
+
errorMsgs.push("ENV is not set in environment variables");
|
|
24
|
+
}
|
|
25
|
+
if (errorMsgs.length > 0) {
|
|
26
|
+
throw new Error(errorMsgs.join("\n"));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* getTokens is a method that exchanges an authentication code for access and refresh tokens.
|
|
31
|
+
* The client id and secret are passed as basic auth headers to authenticate the client itself.
|
|
32
|
+
* @param authCode - The authentication code received from the Gneiss authentication service.
|
|
33
|
+
* @returns A promise that resolves to an object containing the access and refresh tokens.
|
|
34
|
+
*/
|
|
35
|
+
async getTokens(authCode) {
|
|
36
|
+
try {
|
|
37
|
+
const url = `${this.authUrl}/auth/access_token?auth_code=${authCode}`;
|
|
38
|
+
const encodedClientId = btoa(this.config.clientId);
|
|
39
|
+
const encodedClientSecret = btoa(this.config.clientSecret);
|
|
40
|
+
const response = await axios.post(url, {}, {
|
|
41
|
+
headers: {
|
|
42
|
+
"Authorization": `Basic ${encodedClientId}:${encodedClientSecret}`
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
accessToken: response.data.access_token,
|
|
47
|
+
refreshToken: response.data.refresh_token,
|
|
48
|
+
tokenType: response.data.token_type
|
|
49
|
+
};
|
|
50
|
+
} catch (error) {
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* refreshToken is a method that refreshes the access token using the refresh token.
|
|
56
|
+
* @param refreshToken - The refresh token to be used for token refresh.
|
|
57
|
+
* @returns A promise that resolves to the refreshed access token.
|
|
58
|
+
*/
|
|
59
|
+
async refreshToken(refreshToken) {
|
|
60
|
+
try {
|
|
61
|
+
const url = `${this.authUrl}/auth/refresh`;
|
|
62
|
+
const response = await axios.post(url, {}, {
|
|
63
|
+
headers: {
|
|
64
|
+
"Authorization": `Bearer ${refreshToken}`
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
return response.data.access_token;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* getUserData is a method that fetches user data using the access token.
|
|
74
|
+
* @param accessToken - The access token to be used for user data fetching.
|
|
75
|
+
* @returns A promise that resolves to the user data.
|
|
76
|
+
*/
|
|
77
|
+
async getUserData(accessToken) {
|
|
78
|
+
const url = `${this.authUrl}/resource/user_data`;
|
|
79
|
+
const response = await axios.get(url, {
|
|
80
|
+
headers: {
|
|
81
|
+
"Authorization": `Bearer ${accessToken}`
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
if (response.status === 200) {
|
|
85
|
+
return response.data;
|
|
86
|
+
}
|
|
87
|
+
throw new Error("Failed to fetch user data");
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* validateToken is a method that validates the access token.
|
|
91
|
+
* @param token - The access token to be validated.
|
|
92
|
+
* @returns A promise that resolves to a boolean indicating the validity of the token.
|
|
93
|
+
*/
|
|
94
|
+
async validateToken(token) {
|
|
95
|
+
try {
|
|
96
|
+
console.log("DEBUG: token", token);
|
|
97
|
+
if (!token) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
const url = `${this.authUrl}/auth/validate_token`;
|
|
101
|
+
const response = await axios.get(url, {
|
|
102
|
+
headers: {
|
|
103
|
+
"Authorization": `Bearer ${token}`
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
return response.status === 200;
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error instanceof AxiosError && error.response?.status === 401) {
|
|
109
|
+
return false;
|
|
110
|
+
} else {
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* getLoginUrl is a method that returns the login URL.
|
|
117
|
+
* @returns The login URL.
|
|
118
|
+
*/
|
|
119
|
+
getLoginUrl() {
|
|
120
|
+
return this.loginUrl;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* deleteUser deletes the user
|
|
124
|
+
* */
|
|
125
|
+
async deleteUserData(accessToken) {
|
|
126
|
+
const response = await axios.post(`${this.authUrl}/resource/delete_user`, {}, {
|
|
127
|
+
headers: {
|
|
128
|
+
"Authorization": `Bearer ${accessToken}`
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
return response.data;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
var AuthGneissCore_default = AuthGneissCore;
|
|
135
|
+
|
|
136
|
+
// src/utils/storage/cookieHandling.ts
|
|
137
|
+
import { decode } from "jsonwebtoken";
|
|
138
|
+
function setAccessToken(res, accessToken) {
|
|
139
|
+
const decodedToken = decode(accessToken);
|
|
140
|
+
if (!decodedToken.exp) {
|
|
141
|
+
throw new Error("Access token does not contain an expiration time");
|
|
142
|
+
}
|
|
143
|
+
res.cookie("accessToken", accessToken, {
|
|
144
|
+
httpOnly: true,
|
|
145
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
146
|
+
sameSite: "lax",
|
|
147
|
+
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
function setRefreshToken(res, refreshToken) {
|
|
151
|
+
const decodedToken = decode(refreshToken);
|
|
152
|
+
if (!decodedToken.exp) {
|
|
153
|
+
throw new Error("Refresh token does not contain an expiration time");
|
|
154
|
+
}
|
|
155
|
+
res.cookie("refreshToken", refreshToken, {
|
|
156
|
+
httpOnly: true,
|
|
157
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
158
|
+
sameSite: "lax",
|
|
159
|
+
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function parseCookies(req) {
|
|
163
|
+
const cookies = req.headers.cookie;
|
|
164
|
+
if (!cookies) {
|
|
165
|
+
return {};
|
|
166
|
+
}
|
|
167
|
+
return cookies.split(";").reduce((acc, cookie) => {
|
|
168
|
+
const [key, value] = cookie.split("=").map((s) => s.trim());
|
|
169
|
+
acc[key] = value;
|
|
170
|
+
return acc;
|
|
171
|
+
}, {});
|
|
172
|
+
}
|
|
173
|
+
function clearCookies(res) {
|
|
174
|
+
res.clearCookie("accessToken", {
|
|
175
|
+
httpOnly: true,
|
|
176
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
177
|
+
sameSite: "strict",
|
|
178
|
+
path: "/"
|
|
179
|
+
});
|
|
180
|
+
res.clearCookie("refreshToken", {
|
|
181
|
+
httpOnly: true,
|
|
182
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
183
|
+
sameSite: "strict",
|
|
184
|
+
path: "/"
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/frameworks/express/middleware/ExpressAuthGneissClient.ts
|
|
189
|
+
import { AxiosError as AxiosError2 } from "axios";
|
|
190
|
+
import axios2 from "axios";
|
|
191
|
+
var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
192
|
+
constructor(config2) {
|
|
193
|
+
super(config2);
|
|
194
|
+
this.requireAuth = this.requireAuth.bind(this);
|
|
195
|
+
this.handleCallBack = this.handleCallBack.bind(this);
|
|
196
|
+
this.login = this.login.bind(this);
|
|
197
|
+
this.logout = this.logout.bind(this);
|
|
198
|
+
this.getUser = this.getUser.bind(this);
|
|
199
|
+
this.deleteUser = this.deleteUser.bind(this);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* requireAuth is a middleware function that checks if the access token is valid.
|
|
203
|
+
* If the access token is not valid, it attempts to refresh the token using the refresh token.
|
|
204
|
+
* If the refresh token is not valid, it redirects the user to the login page.
|
|
205
|
+
* @param req - The request object.
|
|
206
|
+
* @param res - The response object.
|
|
207
|
+
* @param next - The next middleware function.
|
|
208
|
+
*/
|
|
209
|
+
async requireAuth(req, res, next) {
|
|
210
|
+
const cookies = parseCookies(req);
|
|
211
|
+
console.log("DEBUG: cookies", cookies);
|
|
212
|
+
try {
|
|
213
|
+
const isAccessTokenValid = await this.validateToken(cookies?.accessToken);
|
|
214
|
+
if (!isAccessTokenValid) {
|
|
215
|
+
const newAccessToken = await this.refreshToken(cookies?.refreshToken);
|
|
216
|
+
if (newAccessToken) {
|
|
217
|
+
setAccessToken(res, newAccessToken);
|
|
218
|
+
res.redirect(req.originalUrl);
|
|
219
|
+
} else {
|
|
220
|
+
const returnToUrl = req.originalUrl;
|
|
221
|
+
res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}&return_to_url=${returnToUrl}`);
|
|
222
|
+
}
|
|
223
|
+
} else {
|
|
224
|
+
next();
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (error instanceof AxiosError2) {
|
|
228
|
+
res.status(error.response?.status || 500).send(error.response?.data || "Internal server error");
|
|
229
|
+
} else {
|
|
230
|
+
res.status(500).send("Internal server error");
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* getUserData is a middleware function that fetches user data using the access token.
|
|
236
|
+
* @param req - The request object.
|
|
237
|
+
* @param res - The response object.
|
|
238
|
+
* @param next - The next middleware function.
|
|
239
|
+
*/
|
|
240
|
+
async getUser(req, res) {
|
|
241
|
+
const cookies = parseCookies(req);
|
|
242
|
+
const accessToken = cookies?.accessToken;
|
|
243
|
+
if (!accessToken) {
|
|
244
|
+
throw new Error("No access token found in request cookies");
|
|
245
|
+
}
|
|
246
|
+
const userData = await this.getUserData(accessToken);
|
|
247
|
+
res.status(200).send(userData);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* handleCallBack is a middleware function that handles the callback from the authentication service.
|
|
251
|
+
* It extracts the auth code from the request URL parameters, exchanges it for tokens, and sets the access and refresh tokens in the response cookies.
|
|
252
|
+
* @param req - The request object.
|
|
253
|
+
* @param res - The response object.
|
|
254
|
+
* @param next - The next middleware function.
|
|
255
|
+
*/
|
|
256
|
+
async handleCallBack(req, res, next) {
|
|
257
|
+
try {
|
|
258
|
+
const authCode = req.query.auth_code;
|
|
259
|
+
const returnToUrl = req.query.return_to_url;
|
|
260
|
+
if (!authCode) {
|
|
261
|
+
throw new Error("No auth code found in request url parameters");
|
|
262
|
+
}
|
|
263
|
+
const tokens = await this.getTokens(authCode);
|
|
264
|
+
setAccessToken(res, tokens.accessToken);
|
|
265
|
+
setRefreshToken(res, tokens.refreshToken);
|
|
266
|
+
if (returnToUrl) {
|
|
267
|
+
res.redirect(returnToUrl);
|
|
268
|
+
} else {
|
|
269
|
+
res.redirect("/");
|
|
270
|
+
}
|
|
271
|
+
} catch (error) {
|
|
272
|
+
if (error instanceof AxiosError2) {
|
|
273
|
+
res.status(error.response?.status || 500).send(error.response?.data || "Internal server error");
|
|
274
|
+
console.error("DEBUG: error", error);
|
|
275
|
+
} else {
|
|
276
|
+
res.status(500).send("Internal server error");
|
|
277
|
+
console.error("DEBUG: error", error);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* login is a function that redirects the user to the Gneiss authentication service for authentication.
|
|
283
|
+
* @param req - The request object.
|
|
284
|
+
* @param res - The response object.
|
|
285
|
+
*/
|
|
286
|
+
login(req, res) {
|
|
287
|
+
try {
|
|
288
|
+
if (!this.loginUrl) {
|
|
289
|
+
throw new Error("Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.");
|
|
290
|
+
}
|
|
291
|
+
res.redirect(this.loginUrl + `?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}`);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
console.error("Error in login middleware:", error);
|
|
294
|
+
res.status(500).send("Internal server error");
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* logout is a function that redirects the user to the Gneiss logout service.
|
|
299
|
+
* @param req - The request object.
|
|
300
|
+
* @param res - The response object.
|
|
301
|
+
*/
|
|
302
|
+
logout(req, res) {
|
|
303
|
+
const cookies = parseCookies(req);
|
|
304
|
+
try {
|
|
305
|
+
if (!this.logoutUrl) {
|
|
306
|
+
throw new Error("Logout URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.");
|
|
307
|
+
}
|
|
308
|
+
if (cookies?.accessToken) {
|
|
309
|
+
axios2.post(this.logoutUrl, {}, {
|
|
310
|
+
// Logout
|
|
311
|
+
headers: {
|
|
312
|
+
"Authorization": `Bearer ${cookies?.accessToken}`
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
clearCookies(res);
|
|
317
|
+
res.redirect("/");
|
|
318
|
+
} catch (error) {
|
|
319
|
+
console.error("Error in logout middleware:", error);
|
|
320
|
+
res.status(500).send("Internal server error");
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Utility route handler for deleting a user
|
|
325
|
+
* This ensures that the user is fully logged out before
|
|
326
|
+
* deleting the user's data
|
|
327
|
+
*
|
|
328
|
+
* @param req - The request object.
|
|
329
|
+
* @param res - The response object.
|
|
330
|
+
*/
|
|
331
|
+
deleteUser(req, res) {
|
|
332
|
+
const cookies = parseCookies(req);
|
|
333
|
+
this.logout(req, res);
|
|
334
|
+
this.deleteUserData(cookies?.accessToken);
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
var ExpressAuthGneissClient_default = ExpressAuthGneissClient;
|
|
338
|
+
export {
|
|
339
|
+
AuthGneissCore_default as AuthGneissCore,
|
|
340
|
+
ExpressAuthGneissClient_default as ExpressAuthGneissClient,
|
|
341
|
+
parseCookies
|
|
342
|
+
};
|
|
343
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/core/AuthGneissCore.ts", "../../src/config.ts", "../../src/utils/storage/cookieHandling.ts", "../../src/frameworks/express/middleware/ExpressAuthGneissClient.ts"],
|
|
4
|
+
"sourcesContent": ["import { AuthGneissCoreConfig } from \"@core/types\";\nimport axios, { AxiosResponse } from \"axios\";\nimport { Tokens } from \"@core/types\";\nimport dotenv from \"dotenv\";\nimport { AxiosError } from \"axios\";\nimport { config as generalConfig } from \"@/config\";\nimport { AuthGneissGeneralConfig } from \"@/config\";\n\n//load environment variables if not already set\nif (!process.env.ENV) {\n dotenv.config();\n}\n\n/**\n * AuthGneissCore provides core functionality for OAuth2 authentication flow with Gneiss authentication service.\n * It handles token exchange, token refresh, user data fetching, and token validation.\n * \n * This class serves as a base class that can be extended by framework-specific implementations\n * to provide authentication middleware and handlers.\n */\nclass AuthGneissCore {\n protected config: AuthGneissCoreConfig & AuthGneissGeneralConfig; // Configuration object\n protected authUrl : string | undefined\n protected loginUrl : string | undefined\n protected logoutUrl : string | undefined\n\n constructor(\n devConfig: AuthGneissCoreConfig\n ) {\n this.config = {...devConfig, ...generalConfig};\n this.authUrl = this.config.authUrl // Gneiss endpoint\n this.loginUrl = this.authUrl ? `${this.authUrl}/auth/login` : undefined; // Login URL\n this.logoutUrl = this.authUrl ? `${this.authUrl}/auth/logout` : undefined; // Logout URL\n\n //check if environment variables are set\n let errorMsgs = [];\n if (!process.env.ENV) {\n errorMsgs.push(\"ENV is not set in environment variables\");\n }\n if (errorMsgs.length > 0) {\n throw new Error(errorMsgs.join(\"\\n\"));\n }\n }\n\n /**\n * getTokens is a method that exchanges an authentication code for access and refresh tokens.\n * The client id and secret are passed as basic auth headers to authenticate the client itself.\n * @param authCode - The authentication code received from the Gneiss authentication service.\n * @returns A promise that resolves to an object containing the access and refresh tokens.\n */\n protected async getTokens(authCode : string) : Promise<Tokens> {\n try {\n const url : string = `${this.authUrl}/auth/access_token?auth_code=${authCode}`;\n //Encode in base64 before transport\n const encodedClientId = btoa(this.config.clientId);\n const encodedClientSecret = btoa(this.config.clientSecret);\n const response : AxiosResponse = await axios.post(url, {}, {\n headers: {\n \"Authorization\": `Basic ${encodedClientId}:${encodedClientSecret}`\n }\n });\n return {\n accessToken: response.data.access_token,\n refreshToken: response.data.refresh_token,\n tokenType: response.data.token_type\n } as Tokens;\n } catch (error) {\n // console.error(\"Error in getTokens:\", error);\n throw error;\n }\n }\n \n /**\n * refreshToken is a method that refreshes the access token using the refresh token.\n * @param refreshToken - The refresh token to be used for token refresh.\n * @returns A promise that resolves to the refreshed access token.\n */\n protected async refreshToken(refreshToken: string): Promise<string | null> {\n try {\n const url : string = `${this.authUrl}/auth/refresh`;\n const response : AxiosResponse = await axios.post(url, {}, {\n headers: {\n \"Authorization\": `Bearer ${refreshToken}`\n }\n });\n return response.data.access_token as string;\n } catch (error) {\n // console.error(\"Error in refreshToken:\", error);\n return null;\n }\n }\n \n /**\n * getUserData is a method that fetches user data using the access token.\n * @param accessToken - The access token to be used for user data fetching.\n * @returns A promise that resolves to the user data.\n */\n async getUserData(accessToken: string) {\n const url : string = `${this.authUrl}/resource/user_data`;\n const response : AxiosResponse = await axios.get(url, {\n headers: {\n \"Authorization\": `Bearer ${accessToken}`\n }\n });\n if (response.status === 200) {\n return response.data;\n }\n throw new Error(\"Failed to fetch user data\");\n }\n \n /**\n * validateToken is a method that validates the access token.\n * @param token - The access token to be validated.\n * @returns A promise that resolves to a boolean indicating the validity of the token.\n */\n protected async validateToken(token: string): Promise<boolean> {\n try {\n console.log(\"DEBUG: token\", token);\n // Token validation logic\n if (!token) {\n return false;\n }\n const url : string = `${this.authUrl}/auth/validate_token`;\n const response : AxiosResponse = await axios.get(url, {\n headers: {\n \"Authorization\": `Bearer ${token}`\n }\n });\n return response.status === 200;\n } catch (error) {\n // console.error(\"Error in validateToken:\", error);\n if (error instanceof AxiosError && error.response?.status === 401) {\n return false;\n } else {\n throw error;\n }\n }\n }\n\n /**\n * getLoginUrl is a method that returns the login URL.\n * @returns The login URL.\n */\n public getLoginUrl() : string | undefined {\n return this.loginUrl;\n }\n\n /**\n * deleteUser deletes the user\n * */\n protected async deleteUserData(accessToken : string) : Promise<object> {\n const response : AxiosResponse = await axios.post(`${this.authUrl}/resource/delete_user`, {}, {\n headers: {\n \"Authorization\": `Bearer ${accessToken}`\n } \n });\n return response.data;\n }\n}\n\nexport default AuthGneissCore;\n", "export type AuthGneissGeneralConfig = {\n authUrl: string\n}\n\nexport const config : AuthGneissGeneralConfig = {\n authUrl: process.env.ENV === \"prod\" ? \"auth.gneiss.io\" : \n process.env.ENV === \"staging\" ? \"auth.gneiss.io/testing\" : \"localhost:5000\"\n}", "import { Response } from \"express\";\nimport { JwtPayload, decode } from \"jsonwebtoken\";\nimport { Request } from \"express\";\n\n/**\n * Set the access token in the response cookies.\n * @param res - The response object.\n * @param accessToken - The access token to set.\n */\nfunction setAccessToken(res: Response, accessToken: string) {\n\n const decodedToken = decode(accessToken) as JwtPayload;\n \n // decoded.exp is in seconds since epoch\n // Date.now() returns milliseconds since epoch\n // maxAge needs milliseconds remaining\n if (!decodedToken.exp) {\n throw new Error(\"Access token does not contain an expiration time\");\n }\n \n res.cookie('accessToken', accessToken, {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'lax',\n maxAge: (decodedToken.exp * 1000) - Date.now()\n });\n}\n\n/**\n * Set the refresh token in the response cookies.\n * @param res - The response object.\n * @param refreshToken - The refresh token to set.\n */\nfunction setRefreshToken(res: Response, refreshToken: string) {\n\n const decodedToken = decode(refreshToken) as JwtPayload;\n\n if (!decodedToken.exp) {\n throw new Error(\"Refresh token does not contain an expiration time\");\n }\n\n res.cookie('refreshToken', refreshToken, {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'lax',\n maxAge: (decodedToken.exp * 1000) - Date.now()\n });\n}\n\nfunction parseCookies(req: Request) : { [key: string]: string } {\n const cookies = req.headers.cookie;\n if (!cookies) {\n return {};\n }\n return cookies.split(';').reduce((acc: { [key: string]: string }, cookie) => {\n const [key, value] = cookie.split('=').map(s => s.trim());\n acc[key] = value;\n return acc;\n }, {});\n}\n\nfunction clearCookies(res: Response) {\n res.clearCookie(\"accessToken\", {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'strict',\n path: '/'\n });\n res.clearCookie(\"refreshToken\", {\n httpOnly: true,\n secure: process.env.ENV === 'prod' || process.env.ENV === 'staging',\n sameSite: 'strict',\n path: '/'\n });\n}\n\nexport { setAccessToken, setRefreshToken, parseCookies, clearCookies };\n", "import { AuthGneissCore, AuthGneissCoreConfig } from \"@core\";\nimport { Request, Response, NextFunction } from \"express\";\nimport { RequestWithTokens, Tokens } from \"@core/types\";\nimport { setAccessToken, setRefreshToken, parseCookies } from \"@utils\";\nimport { JwtPayload } from \"jsonwebtoken\";\nimport { AxiosError } from \"axios\";\nimport axios from \"axios\";\nimport { clearCookies } from \"@/utils/storage/cookieHandling\";\n\n/**\n * ExpressAuthGneissClient extends AuthGneissCore to provide Express-specific authentication middleware\n * and functionality for handling OAuth2 authentication flow with Gneiss authentication service.\n * \n * @extends AuthGneissCore\n * @example\n * const authClient = new ExpressAuthGneissClient({\n * clientId: 'your-client-id',\n * clientSecret: 'your-client-secret',\n * redirectUrl: 'your-redirect-url'\n * });\n */\nclass ExpressAuthGneissClient extends AuthGneissCore {\n\n constructor(\n config: AuthGneissCoreConfig\n ) {\n super(config);\n \n // Bind the methods in constructor\n this.requireAuth = this.requireAuth.bind(this);\n this.handleCallBack = this.handleCallBack.bind(this);\n this.login = this.login.bind(this);\n this.logout = this.logout.bind(this);\n this.getUser = this.getUser.bind(this);\n this.deleteUser = this.deleteUser.bind(this)\n }\n\n /**\n * requireAuth is a middleware function that checks if the access token is valid.\n * If the access token is not valid, it attempts to refresh the token using the refresh token.\n * If the refresh token is not valid, it redirects the user to the login page.\n * @param req - The request object.\n * @param res - The response object.\n * @param next - The next middleware function.\n */\n public async requireAuth(req: Request, res: Response, next: NextFunction): Promise<void> {\n const cookies = parseCookies(req);\n //Check for the existence of the access token\n console.log(\"DEBUG: cookies\", cookies);\n try {\n const isAccessTokenValid : boolean = await this.validateToken(cookies?.accessToken);\n if (!isAccessTokenValid) { //if the access token is not valid\n //try to refresh the token\n const newAccessToken : string | null = await this.refreshToken(cookies?.refreshToken);\n if (newAccessToken) { // set access token and then redirect to the original requested url to 'redo' the request with new access token\n setAccessToken(res, newAccessToken);\n res.redirect(req.originalUrl)\n }\n else {\n // no access token or valid refresh token, redirect to login\n const returnToUrl : string | undefined = req.originalUrl as string;\n res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}&return_to_url=${returnToUrl}`);\n }\n }\n else {\n // access token is valid, continue to the next middleware or route handler\n next();\n }\n } catch (error) {\n // console.error('Error in requireAuth middleware:', error);\n if (error instanceof AxiosError) {\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\n } else {\n res.status(500).send('Internal server error');\n }\n }\n }\n\n /**\n * getUserData is a middleware function that fetches user data using the access token.\n * @param req - The request object.\n * @param res - The response object.\n * @param next - The next middleware function.\n */\n public async getUser(req: Request, res: Response): Promise<void> {\n const cookies = parseCookies(req);\n const accessToken = cookies?.accessToken;\n if (!accessToken) {\n throw new Error(\"No access token found in request cookies\");\n }\n const userData = await this.getUserData(accessToken);\n res.status(200).send(userData);\n }\n\n /**\n * handleCallBack is a middleware function that handles the callback from the authentication service.\n * It extracts the auth code from the request URL parameters, exchanges it for tokens, and sets the access and refresh tokens in the response cookies.\n * @param req - The request object.\n * @param res - The response object.\n * @param next - The next middleware function.\n */\n public async handleCallBack(\n req: Request,\n res: Response,\n next: NextFunction\n ): Promise<void> {\n try {\n const authCode: string | undefined = req.query.auth_code as string\n const returnToUrl : string | undefined = req.query.return_to_url as string;\n if (!authCode) {\n throw new Error(\"No auth code found in request url parameters\");\n }\n\n const tokens: Tokens = await this.getTokens(authCode);\n \n // Set the access and refresh tokens in the response cookies\n setAccessToken(res, tokens.accessToken);\n setRefreshToken(res, tokens.refreshToken);\n\n if (returnToUrl) {\n // Go to the original request url\n res.redirect(returnToUrl);\n }\n else {\n // Go to the root url\n res.redirect(\"/\")\n }\n } catch (error) {\n // console.error('Error in handleCallBack middleware:', error);\n if (error instanceof AxiosError) {\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\n console.error(\"DEBUG: error\", error);\n } else {\n res.status(500).send('Internal server error');\n console.error(\"DEBUG: error\", error);\n }\n }\n }\n\n /**\n * login is a function that redirects the user to the Gneiss authentication service for authentication.\n * @param req - The request object.\n * @param res - The response object.\n */\n public login(req: Request, res: Response): void {\n try {\n if (!this.loginUrl) {\n throw new Error('Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\n }\n res.redirect(this.loginUrl + `?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}`);\n } catch (error) {\n console.error('Error in login middleware:', error);\n res.status(500).send('Internal server error');\n }\n }\n\n /**\n * logout is a function that redirects the user to the Gneiss logout service.\n * @param req - The request object.\n * @param res - The response object.\n */\n public logout(req: Request, res: Response): void {\n const cookies = parseCookies(req);\n try {\n if (!this.logoutUrl) {\n throw new Error('Logout URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\n }\n if (cookies?.accessToken) { // Only logout if the access token exists\n axios.post(this.logoutUrl, {}, { // Logout\n headers: {\n \"Authorization\": `Bearer ${cookies?.accessToken}`\n }\n });\n }\n clearCookies(res); // clear the access and refresh cookies\n res.redirect(\"/\") // Redirect back to home after logout\n } catch (error) {\n console.error('Error in logout middleware:', error);\n res.status(500).send('Internal server error');\n }\n }\n\n /**\n * Utility route handler for deleting a user\n * This ensures that the user is fully logged out before \n * deleting the user's data\n * \n * @param req - The request object.\n * @param res - The response object.\n */\n public deleteUser(req: Request, res: Response) {\n const cookies = parseCookies(req);\n this.logout(req, res)\n this.deleteUserData(cookies?.accessToken)\n }\n}\n\nexport default ExpressAuthGneissClient;\n"],
|
|
5
|
+
"mappings": ";AACA,OAAO,WAA8B;AAErC,OAAO,YAAY;AACnB,SAAS,kBAAkB;;;ACApB,IAAM,SAAmC;AAAA,EAC5C,SAAS,QAAQ,IAAI,QAAQ,SAAS,mBACtC,QAAQ,IAAI,QAAQ,YAAY,2BAA2B;AAC/D;;;ADEA,IAAI,CAAC,QAAQ,IAAI,KAAK;AAClB,SAAO,OAAO;AAClB;AASA,IAAM,iBAAN,MAAqB;AAAA,EAMjB,YACI,WACF;AACE,SAAK,SAAS,EAAC,GAAG,WAAW,GAAG,OAAa;AAC7C,SAAK,UAAU,KAAK,OAAO;AAC3B,SAAK,WAAW,KAAK,UAAU,GAAG,KAAK,OAAO,gBAAgB;AAC9D,SAAK,YAAY,KAAK,UAAU,GAAG,KAAK,OAAO,iBAAiB;AAGhE,QAAI,YAAY,CAAC;AACjB,QAAI,CAAC,QAAQ,IAAI,KAAK;AAClB,gBAAU,KAAK,yCAAyC;AAAA,IAC5D;AACA,QAAI,UAAU,SAAS,GAAG;AACtB,YAAM,IAAI,MAAM,UAAU,KAAK,IAAI,CAAC;AAAA,IACxC;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAgB,UAAU,UAAqC;AAC3D,QAAI;AACA,YAAM,MAAe,GAAG,KAAK,OAAO,gCAAgC,QAAQ;AAE5E,YAAM,kBAAkB,KAAK,KAAK,OAAO,QAAQ;AACjD,YAAM,sBAAsB,KAAK,KAAK,OAAO,YAAY;AACzD,YAAM,WAA2B,MA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AAS,GAAG;AAAA,IACpB,SAAS,OAAO;AACZ,cAAQ,MAAM,+BAA+B,KAAK;AAClD,UAAI,OAAO,GAAG,EAAE,KAAK,uBAAuB;AAAA,IAChD;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUO,WAAW,KAAc,KAAe;AAC3C,UAAM,UAAU,aAAa,GAAG;AAChC,SAAK,OAAO,KAAK,GAAG;AACpB,SAAK,eAAe,SAAS,WAAW;AAAA,EAC5C;AACJ;AAEA,IAAO,kCAAQ;",
|
|
6
|
+
"names": ["AxiosError", "axios", "config", "AxiosError", "axios"]
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/config.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,uBAAuB,GAAG;IAClC,OAAO,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,eAAO,MAAM,MAAM,EAAG,uBAGrB,CAAA"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { AuthGneissCoreConfig } from "@core/types";
|
|
2
|
+
import { Tokens } from "@core/types";
|
|
3
|
+
import { AuthGneissGeneralConfig } from "@/config";
|
|
4
|
+
/**
|
|
5
|
+
* AuthGneissCore provides core functionality for OAuth2 authentication flow with Gneiss authentication service.
|
|
6
|
+
* It handles token exchange, token refresh, user data fetching, and token validation.
|
|
7
|
+
*
|
|
8
|
+
* This class serves as a base class that can be extended by framework-specific implementations
|
|
9
|
+
* to provide authentication middleware and handlers.
|
|
10
|
+
*/
|
|
11
|
+
declare class AuthGneissCore {
|
|
12
|
+
protected config: AuthGneissCoreConfig & AuthGneissGeneralConfig;
|
|
13
|
+
protected authUrl: string | undefined;
|
|
14
|
+
protected loginUrl: string | undefined;
|
|
15
|
+
protected logoutUrl: string | undefined;
|
|
16
|
+
constructor(devConfig: AuthGneissCoreConfig);
|
|
17
|
+
/**
|
|
18
|
+
* getTokens is a method that exchanges an authentication code for access and refresh tokens.
|
|
19
|
+
* The client id and secret are passed as basic auth headers to authenticate the client itself.
|
|
20
|
+
* @param authCode - The authentication code received from the Gneiss authentication service.
|
|
21
|
+
* @returns A promise that resolves to an object containing the access and refresh tokens.
|
|
22
|
+
*/
|
|
23
|
+
protected getTokens(authCode: string): Promise<Tokens>;
|
|
24
|
+
/**
|
|
25
|
+
* refreshToken is a method that refreshes the access token using the refresh token.
|
|
26
|
+
* @param refreshToken - The refresh token to be used for token refresh.
|
|
27
|
+
* @returns A promise that resolves to the refreshed access token.
|
|
28
|
+
*/
|
|
29
|
+
protected refreshToken(refreshToken: string): Promise<string | null>;
|
|
30
|
+
/**
|
|
31
|
+
* getUserData is a method that fetches user data using the access token.
|
|
32
|
+
* @param accessToken - The access token to be used for user data fetching.
|
|
33
|
+
* @returns A promise that resolves to the user data.
|
|
34
|
+
*/
|
|
35
|
+
getUserData(accessToken: string): Promise<any>;
|
|
36
|
+
/**
|
|
37
|
+
* validateToken is a method that validates the access token.
|
|
38
|
+
* @param token - The access token to be validated.
|
|
39
|
+
* @returns A promise that resolves to a boolean indicating the validity of the token.
|
|
40
|
+
*/
|
|
41
|
+
protected validateToken(token: string): Promise<boolean>;
|
|
42
|
+
/**
|
|
43
|
+
* getLoginUrl is a method that returns the login URL.
|
|
44
|
+
* @returns The login URL.
|
|
45
|
+
*/
|
|
46
|
+
getLoginUrl(): string | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* deleteUser deletes the user
|
|
49
|
+
* */
|
|
50
|
+
protected deleteUserData(accessToken: string): Promise<object>;
|
|
51
|
+
}
|
|
52
|
+
export default AuthGneissCore;
|
|
53
|
+
//# sourceMappingURL=AuthGneissCore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AuthGneissCore.d.ts","sourceRoot":"","sources":["../../../../src/core/AuthGneissCore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIrC,OAAO,EAAE,uBAAuB,EAAE,MAAM,UAAU,CAAC;AAOnD;;;;;;GAMG;AACH,cAAM,cAAc;IAChB,SAAS,CAAC,MAAM,EAAE,oBAAoB,GAAG,uBAAuB,CAAC;IACjE,SAAS,CAAC,OAAO,EAAG,MAAM,GAAG,SAAS,CAAA;IACtC,SAAS,CAAC,QAAQ,EAAG,MAAM,GAAG,SAAS,CAAA;IACvC,SAAS,CAAC,SAAS,EAAG,MAAM,GAAG,SAAS,CAAA;gBAGpC,SAAS,EAAE,oBAAoB;IAiBnC;;;;;OAKG;cACa,SAAS,CAAC,QAAQ,EAAG,MAAM,GAAI,OAAO,CAAC,MAAM,CAAC;IAsB9D;;;;OAIG;cACa,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAe1E;;;;OAIG;IACG,WAAW,CAAC,WAAW,EAAE,MAAM;IAarC;;;;OAIG;cACa,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAwB9D;;;OAGG;IACI,WAAW,IAAK,MAAM,GAAG,SAAS;IAIzC;;SAEK;cACW,cAAc,CAAC,WAAW,EAAG,MAAM,GAAI,OAAO,CAAC,MAAM,CAAC;CAQzE;AAED,eAAe,cAAc,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,EAAE,cAAc,EAAC,CAAC;AACzB,YAAY,EAAE,oBAAoB,EAAE,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Request } from "express";
|
|
2
|
+
interface AuthGneissCoreConfig {
|
|
3
|
+
clientId: string;
|
|
4
|
+
clientSecret: string;
|
|
5
|
+
baseClientUrl: string;
|
|
6
|
+
callbackUrl: string;
|
|
7
|
+
}
|
|
8
|
+
interface Tokens {
|
|
9
|
+
accessToken: string;
|
|
10
|
+
refreshToken: string;
|
|
11
|
+
tokenType: string;
|
|
12
|
+
}
|
|
13
|
+
interface RequestWithTokens extends Request {
|
|
14
|
+
cookies: {
|
|
15
|
+
accessToken: string;
|
|
16
|
+
refreshToken: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export { AuthGneissCoreConfig, Tokens, RequestWithTokens };
|
|
20
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/core/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,UAAU,oBAAoB;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;CACvB;AAED,UAAU,MAAM;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,UAAU,iBAAkB,SAAQ,OAAO;IACvC,OAAO,EAAE;QACL,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,MAAM,CAAC;KACxB,CAAA;CACJ;AAED,OAAO,EAAE,oBAAoB,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { AuthGneissCore, AuthGneissCoreConfig } from "@core";
|
|
2
|
+
import { Request, Response, NextFunction } from "express";
|
|
3
|
+
/**
|
|
4
|
+
* ExpressAuthGneissClient extends AuthGneissCore to provide Express-specific authentication middleware
|
|
5
|
+
* and functionality for handling OAuth2 authentication flow with Gneiss authentication service.
|
|
6
|
+
*
|
|
7
|
+
* @extends AuthGneissCore
|
|
8
|
+
* @example
|
|
9
|
+
* const authClient = new ExpressAuthGneissClient({
|
|
10
|
+
* clientId: 'your-client-id',
|
|
11
|
+
* clientSecret: 'your-client-secret',
|
|
12
|
+
* redirectUrl: 'your-redirect-url'
|
|
13
|
+
* });
|
|
14
|
+
*/
|
|
15
|
+
declare class ExpressAuthGneissClient extends AuthGneissCore {
|
|
16
|
+
constructor(config: AuthGneissCoreConfig);
|
|
17
|
+
/**
|
|
18
|
+
* requireAuth is a middleware function that checks if the access token is valid.
|
|
19
|
+
* If the access token is not valid, it attempts to refresh the token using the refresh token.
|
|
20
|
+
* If the refresh token is not valid, it redirects the user to the login page.
|
|
21
|
+
* @param req - The request object.
|
|
22
|
+
* @param res - The response object.
|
|
23
|
+
* @param next - The next middleware function.
|
|
24
|
+
*/
|
|
25
|
+
requireAuth(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* getUserData is a middleware function that fetches user data using the access token.
|
|
28
|
+
* @param req - The request object.
|
|
29
|
+
* @param res - The response object.
|
|
30
|
+
* @param next - The next middleware function.
|
|
31
|
+
*/
|
|
32
|
+
getUser(req: Request, res: Response): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* handleCallBack is a middleware function that handles the callback from the authentication service.
|
|
35
|
+
* It extracts the auth code from the request URL parameters, exchanges it for tokens, and sets the access and refresh tokens in the response cookies.
|
|
36
|
+
* @param req - The request object.
|
|
37
|
+
* @param res - The response object.
|
|
38
|
+
* @param next - The next middleware function.
|
|
39
|
+
*/
|
|
40
|
+
handleCallBack(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* login is a function that redirects the user to the Gneiss authentication service for authentication.
|
|
43
|
+
* @param req - The request object.
|
|
44
|
+
* @param res - The response object.
|
|
45
|
+
*/
|
|
46
|
+
login(req: Request, res: Response): void;
|
|
47
|
+
/**
|
|
48
|
+
* logout is a function that redirects the user to the Gneiss logout service.
|
|
49
|
+
* @param req - The request object.
|
|
50
|
+
* @param res - The response object.
|
|
51
|
+
*/
|
|
52
|
+
logout(req: Request, res: Response): void;
|
|
53
|
+
/**
|
|
54
|
+
* Utility route handler for deleting a user
|
|
55
|
+
* This ensures that the user is fully logged out before
|
|
56
|
+
* deleting the user's data
|
|
57
|
+
*
|
|
58
|
+
* @param req - The request object.
|
|
59
|
+
* @param res - The response object.
|
|
60
|
+
*/
|
|
61
|
+
deleteUser(req: Request, res: Response): void;
|
|
62
|
+
}
|
|
63
|
+
export default ExpressAuthGneissClient;
|
|
64
|
+
//# sourceMappingURL=ExpressAuthGneissClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ExpressAuthGneissClient.d.ts","sourceRoot":"","sources":["../../../../../../src/frameworks/express/middleware/ExpressAuthGneissClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAQ1D;;;;;;;;;;;GAWG;AACH,cAAM,uBAAwB,SAAQ,cAAc;gBAG5C,MAAM,EAAE,oBAAoB;IAahC;;;;;;;OAOG;IACU,WAAW,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAiCxF;;;;;OAKG;IACU,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAUhE;;;;;;OAMG;IACU,cAAc,CACvB,GAAG,EAAE,OAAO,EACZ,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,YAAY,GACnB,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;OAIG;IACI,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,IAAI;IAY/C;;;;OAIG;IACI,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,IAAI;IAqBhD;;;;;;;OAOG;IACI,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ;CAKhD;AAED,eAAe,uBAAuB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/frameworks/index.ts"],"names":[],"mappings":"AAAA,OAAO,uBAAuB,MAAM,8CAA8C,CAAC;AAEnF,OAAO,EAAE,uBAAuB,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAA;AACrC,YAAY,EAAE,oBAAoB,EAAE,MAAM,QAAQ,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/utils/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Response } from "express";
|
|
2
|
+
import { Request } from "express";
|
|
3
|
+
/**
|
|
4
|
+
* Set the access token in the response cookies.
|
|
5
|
+
* @param res - The response object.
|
|
6
|
+
* @param accessToken - The access token to set.
|
|
7
|
+
*/
|
|
8
|
+
declare function setAccessToken(res: Response, accessToken: string): void;
|
|
9
|
+
/**
|
|
10
|
+
* Set the refresh token in the response cookies.
|
|
11
|
+
* @param res - The response object.
|
|
12
|
+
* @param refreshToken - The refresh token to set.
|
|
13
|
+
*/
|
|
14
|
+
declare function setRefreshToken(res: Response, refreshToken: string): void;
|
|
15
|
+
declare function parseCookies(req: Request): {
|
|
16
|
+
[key: string]: string;
|
|
17
|
+
};
|
|
18
|
+
declare function clearCookies(res: Response): void;
|
|
19
|
+
export { setAccessToken, setRefreshToken, parseCookies, clearCookies };
|
|
20
|
+
//# sourceMappingURL=cookieHandling.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cookieHandling.d.ts","sourceRoot":"","sources":["../../../../../src/utils/storage/cookieHandling.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAEnC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC;;;;GAIG;AACH,iBAAS,cAAc,CAAC,GAAG,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,QAiBzD;AAED;;;;GAIG;AACH,iBAAS,eAAe,CAAC,GAAG,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,QAc3D;AAED,iBAAS,YAAY,CAAC,GAAG,EAAE,OAAO,GAAI;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,CAU9D;AAED,iBAAS,YAAY,CAAC,GAAG,EAAE,QAAQ,QAalC;AAED,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ExpressAuthGneissClient.integration.test.d.ts","sourceRoot":"","sources":["../../../../../../tests/frameworks/express/middleware/ExpressAuthGneissClient.integration.test.ts"],"names":[],"mappings":""}
|