@gneiss/client-auth 1.0.3 → 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/README.md +58 -76
- package/dist/cjs/index.js +34 -26
- package/dist/cjs/index.js.map +4 -4
- package/dist/esm/index.js +32 -25
- package/dist/esm/index.js.map +4 -4
- 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 +5 -4
- package/dist/types/src/core/AuthGneissCore.d.ts.map +1 -1
- package/dist/types/src/core/types.d.ts +2 -2
- package/dist/types/src/core/types.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,76 +1,58 @@
|
|
|
1
|
-
# js-gneiss-auth-client
|
|
2
|
-
|
|
3
|
-
A JavaScript client library for integrating with the Gneiss Authentication service. Provides OAuth2 authentication flow with support for access and refresh tokens.
|
|
4
|
-
|
|
5
|
-
## Installation
|
|
6
|
-
### Installing from npm registry:
|
|
7
|
-
```bash
|
|
8
|
-
npm install @gneiss/client-auth
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
//
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
app.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
res.send('This is a protected route');
|
|
60
|
-
});
|
|
61
|
-
// Protected user data route
|
|
62
|
-
app.get("/user", auth.requireAuth, auth.getUser);
|
|
63
|
-
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
* `ExpressAuthGneissClient` is a class that provides middleware for handling authentication in an Express.js application. Parameters are:
|
|
67
|
-
* `clientId` - This is the client id of your application. This will be provided to you by the appropriate Gneiss team member.
|
|
68
|
-
* `clientSecret` - This is the client secret of your application. This will be provided to you by the appropriate Gneiss team member.
|
|
69
|
-
* `baseUrl` - This is the base url (without any endpoints) of your service/app. Note that this may be different depending on your environment (prod or dev)
|
|
70
|
-
* `redirectUrl` - This is the route that the user will be redirected to for authentication. This should be the same as your callback route.
|
|
71
|
-
* `auth.login` is a function that redirects the user to the Gneiss authentication service for authentication.
|
|
72
|
-
* `auth.logout` is a function that removes all tokens and logs the user out of the auth system.
|
|
73
|
-
* `auth.handleCallBack` is a function that handles the callback from the Gneiss authentication service. 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.
|
|
74
|
-
* `auth.requireAuth` is a middleware function that checks if the user is authenticated. If the user is not authenticated, it redirects the user to the login page.
|
|
75
|
-
* `auth.getUser` is an included utility route to allow one to retrieve the current user's data. It is important to include the `auth.requireAuth` middleware to ensure the access token is present before accessing the user's data. If it is not, an exeption will be thrown.
|
|
76
|
-
|
|
1
|
+
# js-gneiss-auth-client
|
|
2
|
+
|
|
3
|
+
A JavaScript client library for integrating with the Gneiss Authentication service. Provides OAuth2 authentication flow with support for access and refresh tokens.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
### Installing from npm registry:
|
|
7
|
+
```bash
|
|
8
|
+
npm install @gneiss/client-auth
|
|
9
|
+
```
|
|
10
|
+
## Usage
|
|
11
|
+
Example for an Express.js application:
|
|
12
|
+
```typescript
|
|
13
|
+
import express from 'express';
|
|
14
|
+
import { ExpressAuthGneissClient } from "@gneiss/client-auth";
|
|
15
|
+
import { AuthGneissCoreConfig } from '@gneiss/client-auth';
|
|
16
|
+
|
|
17
|
+
// Create express app
|
|
18
|
+
const app = express();
|
|
19
|
+
|
|
20
|
+
// Initialize auth config
|
|
21
|
+
const config: AuthGneissCoreConfig = {
|
|
22
|
+
clientId: "<Your app's client ID>,
|
|
23
|
+
clientSecret: "<Your app's client secret>",
|
|
24
|
+
baseClientUrl: "<Your app's base url>",
|
|
25
|
+
callbackUrl: "/callback"
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
//Instantiate the auth client with config
|
|
29
|
+
const auth = new ExpressAuthGneissClient(config);
|
|
30
|
+
|
|
31
|
+
// Login route - redirects to Gneiss login page
|
|
32
|
+
app.get("/login", auth.login);
|
|
33
|
+
|
|
34
|
+
// Logout route - redirects to Gneiss logout page
|
|
35
|
+
app.get("/logout", auth.logout);
|
|
36
|
+
|
|
37
|
+
// Callback route - handles OAuth callback from Gneiss
|
|
38
|
+
app.get("/callback", auth.handleCallBack);
|
|
39
|
+
|
|
40
|
+
// Protected route example
|
|
41
|
+
app.get("/dashboard", auth.requireAuth, (req, res) => {
|
|
42
|
+
res.send('This is a protected route');
|
|
43
|
+
});
|
|
44
|
+
// Protected user data route
|
|
45
|
+
app.get("/user", auth.requireAuth, auth.getUser);
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
* `ExpressAuthGneissClient` is a class that provides middleware for handling authentication in an Express.js application. Parameters are:
|
|
50
|
+
* `clientId` - This is the client id of your application. This will be provided to you by the appropriate Gneiss team member.
|
|
51
|
+
* `clientSecret` - This is the client secret of your application. This will be provided to you by the appropriate Gneiss team member.
|
|
52
|
+
* `baseClientUrl` - This is the base url (without any endpoints) of your service/app. Note that this may be different depending on your environment (prod or dev)
|
|
53
|
+
* `callbackUrl` - This is the route that the user will be redirected to for authentication. This should be the same as your callback route.
|
|
54
|
+
* `auth.login` is a function that redirects the user to the Gneiss authentication service for authentication.
|
|
55
|
+
* `auth.handleCallBack` is a function that handles the callback from the Gneiss authentication service. 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.
|
|
56
|
+
* `auth.requireAuth` is a middleware function that checks if the user is authenticated. If the user is not authenticated, it redirects the user to the login page.
|
|
57
|
+
* `auth.getUser` is an included utility route to allow one to retrieve the current user's data. It is important to include the `auth.requireAuth` middleware to ensure the access token is present before accessing the user's data. If it is not, an exeption will be thrown.
|
|
58
|
+
|
package/dist/cjs/index.js
CHANGED
|
@@ -31,7 +31,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
AuthGneissCore: () => AuthGneissCore_default,
|
|
34
|
-
ExpressAuthGneissClient: () => ExpressAuthGneissClient_default
|
|
34
|
+
ExpressAuthGneissClient: () => ExpressAuthGneissClient_default,
|
|
35
|
+
parseCookies: () => parseCookies
|
|
35
36
|
});
|
|
36
37
|
module.exports = __toCommonJS(index_exports);
|
|
37
38
|
|
|
@@ -39,19 +40,25 @@ module.exports = __toCommonJS(index_exports);
|
|
|
39
40
|
var import_axios = __toESM(require("axios"), 1);
|
|
40
41
|
var import_dotenv = __toESM(require("dotenv"), 1);
|
|
41
42
|
var import_axios2 = require("axios");
|
|
42
|
-
|
|
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
|
+
}
|
|
43
53
|
var AuthGneissCore = class {
|
|
44
|
-
constructor(
|
|
45
|
-
this.config = config;
|
|
46
|
-
this.
|
|
47
|
-
this.loginUrl = this.
|
|
48
|
-
this.logoutUrl = this.
|
|
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;
|
|
49
59
|
let errorMsgs = [];
|
|
50
|
-
if (!process.env.
|
|
51
|
-
errorMsgs.push("
|
|
52
|
-
}
|
|
53
|
-
if (!process.env.NODE_ENV) {
|
|
54
|
-
errorMsgs.push("NODE_ENV is not set in environment variables");
|
|
60
|
+
if (!process.env.ENV) {
|
|
61
|
+
errorMsgs.push("ENV is not set in environment variables");
|
|
55
62
|
}
|
|
56
63
|
if (errorMsgs.length > 0) {
|
|
57
64
|
throw new Error(errorMsgs.join("\n"));
|
|
@@ -65,7 +72,7 @@ var AuthGneissCore = class {
|
|
|
65
72
|
*/
|
|
66
73
|
async getTokens(authCode) {
|
|
67
74
|
try {
|
|
68
|
-
const url = `${this.
|
|
75
|
+
const url = `${this.authUrl}/auth/access_token?auth_code=${authCode}`;
|
|
69
76
|
const encodedClientId = btoa(this.config.clientId);
|
|
70
77
|
const encodedClientSecret = btoa(this.config.clientSecret);
|
|
71
78
|
const response = await import_axios.default.post(url, {}, {
|
|
@@ -89,7 +96,7 @@ var AuthGneissCore = class {
|
|
|
89
96
|
*/
|
|
90
97
|
async refreshToken(refreshToken) {
|
|
91
98
|
try {
|
|
92
|
-
const url = `${this.
|
|
99
|
+
const url = `${this.authUrl}/auth/refresh`;
|
|
93
100
|
const response = await import_axios.default.post(url, {}, {
|
|
94
101
|
headers: {
|
|
95
102
|
"Authorization": `Bearer ${refreshToken}`
|
|
@@ -106,7 +113,7 @@ var AuthGneissCore = class {
|
|
|
106
113
|
* @returns A promise that resolves to the user data.
|
|
107
114
|
*/
|
|
108
115
|
async getUserData(accessToken) {
|
|
109
|
-
const url = `${this.
|
|
116
|
+
const url = `${this.authUrl}/resource/user_data`;
|
|
110
117
|
const response = await import_axios.default.get(url, {
|
|
111
118
|
headers: {
|
|
112
119
|
"Authorization": `Bearer ${accessToken}`
|
|
@@ -128,7 +135,7 @@ var AuthGneissCore = class {
|
|
|
128
135
|
if (!token) {
|
|
129
136
|
return false;
|
|
130
137
|
}
|
|
131
|
-
const url = `${this.
|
|
138
|
+
const url = `${this.authUrl}/auth/validate_token`;
|
|
132
139
|
const response = await import_axios.default.get(url, {
|
|
133
140
|
headers: {
|
|
134
141
|
"Authorization": `Bearer ${token}`
|
|
@@ -154,7 +161,7 @@ var AuthGneissCore = class {
|
|
|
154
161
|
* deleteUser deletes the user
|
|
155
162
|
* */
|
|
156
163
|
async deleteUserData(accessToken) {
|
|
157
|
-
const response = await import_axios.default.post(`${this.
|
|
164
|
+
const response = await import_axios.default.post(`${this.authUrl}/resource/delete_user`, {}, {
|
|
158
165
|
headers: {
|
|
159
166
|
"Authorization": `Bearer ${accessToken}`
|
|
160
167
|
}
|
|
@@ -173,7 +180,7 @@ function setAccessToken(res, accessToken) {
|
|
|
173
180
|
}
|
|
174
181
|
res.cookie("accessToken", accessToken, {
|
|
175
182
|
httpOnly: true,
|
|
176
|
-
secure: process.env.
|
|
183
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
177
184
|
sameSite: "lax",
|
|
178
185
|
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
179
186
|
});
|
|
@@ -185,7 +192,7 @@ function setRefreshToken(res, refreshToken) {
|
|
|
185
192
|
}
|
|
186
193
|
res.cookie("refreshToken", refreshToken, {
|
|
187
194
|
httpOnly: true,
|
|
188
|
-
secure: process.env.
|
|
195
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
189
196
|
sameSite: "lax",
|
|
190
197
|
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
191
198
|
});
|
|
@@ -204,13 +211,13 @@ function parseCookies(req) {
|
|
|
204
211
|
function clearCookies(res) {
|
|
205
212
|
res.clearCookie("accessToken", {
|
|
206
213
|
httpOnly: true,
|
|
207
|
-
secure: process.env.
|
|
214
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
208
215
|
sameSite: "strict",
|
|
209
216
|
path: "/"
|
|
210
217
|
});
|
|
211
218
|
res.clearCookie("refreshToken", {
|
|
212
219
|
httpOnly: true,
|
|
213
|
-
secure: process.env.
|
|
220
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
214
221
|
sameSite: "strict",
|
|
215
222
|
path: "/"
|
|
216
223
|
});
|
|
@@ -220,8 +227,8 @@ function clearCookies(res) {
|
|
|
220
227
|
var import_axios3 = require("axios");
|
|
221
228
|
var import_axios4 = __toESM(require("axios"), 1);
|
|
222
229
|
var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
223
|
-
constructor(
|
|
224
|
-
super(
|
|
230
|
+
constructor(config2) {
|
|
231
|
+
super(config2);
|
|
225
232
|
this.requireAuth = this.requireAuth.bind(this);
|
|
226
233
|
this.handleCallBack = this.handleCallBack.bind(this);
|
|
227
234
|
this.login = this.login.bind(this);
|
|
@@ -249,7 +256,7 @@ var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
|
249
256
|
res.redirect(req.originalUrl);
|
|
250
257
|
} else {
|
|
251
258
|
const returnToUrl = req.originalUrl;
|
|
252
|
-
res.redirect(`${this.loginUrl}?redirect_url=${this.config.
|
|
259
|
+
res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}&return_to_url=${returnToUrl}`);
|
|
253
260
|
}
|
|
254
261
|
} else {
|
|
255
262
|
next();
|
|
@@ -319,7 +326,7 @@ var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
|
319
326
|
if (!this.loginUrl) {
|
|
320
327
|
throw new Error("Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.");
|
|
321
328
|
}
|
|
322
|
-
res.redirect(this.loginUrl + `?redirect_url=${this.config.
|
|
329
|
+
res.redirect(this.loginUrl + `?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}`);
|
|
323
330
|
} catch (error) {
|
|
324
331
|
console.error("Error in login middleware:", error);
|
|
325
332
|
res.status(500).send("Internal server error");
|
|
@@ -369,6 +376,7 @@ var ExpressAuthGneissClient_default = ExpressAuthGneissClient;
|
|
|
369
376
|
// Annotate the CommonJS export names for ESM import in node:
|
|
370
377
|
0 && (module.exports = {
|
|
371
378
|
AuthGneissCore,
|
|
372
|
-
ExpressAuthGneissClient
|
|
379
|
+
ExpressAuthGneissClient,
|
|
380
|
+
parseCookies
|
|
373
381
|
});
|
|
374
382
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/index.ts", "../../src/core/AuthGneissCore.ts", "../../src/utils/storage/cookieHandling.ts", "../../src/frameworks/express/middleware/ExpressAuthGneissClient.ts"],
|
|
4
|
-
"sourcesContent": ["export { ExpressAuthGneissClient } from \"./frameworks\";\r\nexport { AuthGneissCore } from \"./core\";\r\nexport type { AuthGneissCoreConfig } from \"./core\";\r\n", "import { AuthGneissCoreConfig } from \"@core/types\";\r\nimport axios, { AxiosResponse } from \"axios\";\r\nimport { Tokens } from \"@core/types\";\r\nimport dotenv from \"dotenv\";\r\nimport { AxiosError } from \"axios\";\r\n\r\n//load environment variables\r\ndotenv.config();\r\n\r\n/**\r\n * AuthGneissCore provides core functionality for OAuth2 authentication flow with Gneiss authentication service.\r\n * It handles token exchange, token refresh, user data fetching, and token validation.\r\n * \r\n * This class serves as a base class that can be extended by framework-specific implementations\r\n * to provide authentication middleware and handlers.\r\n */\r\nclass AuthGneissCore {\r\n protected config: AuthGneissCoreConfig; // Configuration object\r\n protected gneissEnpoint : string | undefined\r\n protected loginUrl : string | undefined\r\n protected logoutUrl : string | undefined\r\n\r\n constructor(\r\n config: AuthGneissCoreConfig\r\n ) {\r\n this.config = config;\r\n this.gneissEnpoint = process.env.GNEISS_ENDPOINT // Gneiss endpoint\r\n this.loginUrl = this.gneissEnpoint ? `${this.gneissEnpoint}/auth/login` : undefined; // Login URL\r\n this.logoutUrl = this.gneissEnpoint ? `${this.gneissEnpoint}/auth/logout` : undefined; // Logout URL\r\n\r\n //check if environment variables are set\r\n let errorMsgs = [];\r\n if (!process.env.GNEISS_ENDPOINT) {\r\n errorMsgs.push(\"GNEISS_ENDPOINT is not set in environment variables\");\r\n }\r\n if (!process.env.NODE_ENV) {\r\n errorMsgs.push(\"NODE_ENV is not set in environment variables\");\r\n }\r\n if (errorMsgs.length > 0) {\r\n throw new Error(errorMsgs.join(\"\\n\"));\r\n }\r\n }\r\n\r\n /**\r\n * getTokens is a method that exchanges an authentication code for access and refresh tokens.\r\n * The client id and secret are passed as basic auth headers to authenticate the client itself.\r\n * @param authCode - The authentication code received from the Gneiss authentication service.\r\n * @returns A promise that resolves to an object containing the access and refresh tokens.\r\n */\r\n protected async getTokens(authCode : string) : Promise<Tokens> {\r\n try {\r\n const url : string = `${this.gneissEnpoint}/auth/access_token?auth_code=${authCode}`;\r\n //Encode in base64 before transport\r\n const encodedClientId = btoa(this.config.clientId);\r\n const encodedClientSecret = btoa(this.config.clientSecret);\r\n const response : AxiosResponse = await axios.post(url, {}, {\r\n headers: {\r\n \"Authorization\": `Basic ${encodedClientId}:${encodedClientSecret}`\r\n }\r\n });\r\n return {\r\n accessToken: response.data.access_token,\r\n refreshToken: response.data.refresh_token,\r\n tokenType: response.data.token_type\r\n } as Tokens;\r\n } catch (error) {\r\n // console.error(\"Error in getTokens:\", error);\r\n throw error;\r\n }\r\n }\r\n \r\n /**\r\n * refreshToken is a method that refreshes the access token using the refresh token.\r\n * @param refreshToken - The refresh token to be used for token refresh.\r\n * @returns A promise that resolves to the refreshed access token.\r\n */\r\n protected async refreshToken(refreshToken: string): Promise<string | null> {\r\n try {\r\n const url : string = `${this.gneissEnpoint}/auth/refresh`;\r\n const response : AxiosResponse = await axios.post(url, {}, {\r\n headers: {\r\n \"Authorization\": `Bearer ${refreshToken}`\r\n }\r\n });\r\n return response.data.access_token as string;\r\n } catch (error) {\r\n // console.error(\"Error in refreshToken:\", error);\r\n return null;\r\n }\r\n }\r\n \r\n /**\r\n * getUserData is a method that fetches user data using the access token.\r\n * @param accessToken - The access token to be used for user data fetching.\r\n * @returns A promise that resolves to the user data.\r\n */\r\n protected async getUserData(accessToken: string) {\r\n const url : string = `${this.gneissEnpoint}/resource/user_data`;\r\n const response : AxiosResponse = await axios.get(url, {\r\n headers: {\r\n \"Authorization\": `Bearer ${accessToken}`\r\n }\r\n });\r\n if (response.status === 200) {\r\n return response.data;\r\n }\r\n throw new Error(\"Failed to fetch user data\");\r\n }\r\n \r\n /**\r\n * validateToken is a method that validates the access token.\r\n * @param token - The access token to be validated.\r\n * @returns A promise that resolves to a boolean indicating the validity of the token.\r\n */\r\n protected async validateToken(token: string): Promise<boolean> {\r\n try {\r\n console.log(\"DEBUG: token\", token);\r\n // Token validation logic\r\n if (!token) {\r\n return false;\r\n }\r\n const url : string = `${this.gneissEnpoint}/auth/validate_token`;\r\n const response : AxiosResponse = await axios.get(url, {\r\n headers: {\r\n \"Authorization\": `Bearer ${token}`\r\n }\r\n });\r\n return response.status === 200;\r\n } catch (error) {\r\n // console.error(\"Error in validateToken:\", error);\r\n if (error instanceof AxiosError && error.response?.status === 401) {\r\n return false;\r\n } else {\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * getLoginUrl is a method that returns the login URL.\r\n * @returns The login URL.\r\n */\r\n public getLoginUrl() : string | undefined {\r\n return this.loginUrl;\r\n }\r\n\r\n /**\r\n * deleteUser deletes the user\r\n * */\r\n protected async deleteUserData(accessToken : string) : Promise<object> {\r\n const response : AxiosResponse = await axios.post(`${this.gneissEnpoint}/resource/delete_user`, {}, {\r\n headers: {\r\n \"Authorization\": `Bearer ${accessToken}`\r\n } \r\n });\r\n return response.data;\r\n }\r\n}\r\n\r\nexport default AuthGneissCore;\r\n", "import { Response } from \"express\";\r\nimport { JwtPayload, decode } from \"jsonwebtoken\";\r\nimport { Request } from \"express\";\r\n\r\n/**\r\n * Set the access token in the response cookies.\r\n * @param res - The response object.\r\n * @param accessToken - The access token to set.\r\n */\r\nfunction setAccessToken(res: Response, accessToken: string) {\r\n\r\n const decodedToken = decode(accessToken) as JwtPayload;\r\n \r\n // decoded.exp is in seconds since epoch\r\n // Date.now() returns milliseconds since epoch\r\n // maxAge needs milliseconds remaining\r\n if (!decodedToken.exp) {\r\n throw new Error(\"Access token does not contain an expiration time\");\r\n }\r\n \r\n res.cookie('accessToken', accessToken, {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'lax',\r\n maxAge: (decodedToken.exp * 1000) - Date.now()\r\n });\r\n}\r\n\r\n/**\r\n * Set the refresh token in the response cookies.\r\n * @param res - The response object.\r\n * @param refreshToken - The refresh token to set.\r\n */\r\nfunction setRefreshToken(res: Response, refreshToken: string) {\r\n\r\n const decodedToken = decode(refreshToken) as JwtPayload;\r\n\r\n if (!decodedToken.exp) {\r\n throw new Error(\"Refresh token does not contain an expiration time\");\r\n }\r\n\r\n res.cookie('refreshToken', refreshToken, {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'lax',\r\n maxAge: (decodedToken.exp * 1000) - Date.now()\r\n });\r\n}\r\n\r\nfunction parseCookies(req: Request) : { [key: string]: string } {\r\n const cookies = req.headers.cookie;\r\n if (!cookies) {\r\n return {};\r\n }\r\n return cookies.split(';').reduce((acc: { [key: string]: string }, cookie) => {\r\n const [key, value] = cookie.split('=').map(s => s.trim());\r\n acc[key] = value;\r\n return acc;\r\n }, {});\r\n}\r\n\r\nfunction clearCookies(res: Response) {\r\n res.clearCookie(\"accessToken\", {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'strict',\r\n path: '/'\r\n });\r\n res.clearCookie(\"refreshToken\", {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'strict',\r\n path: '/'\r\n });\r\n}\r\n\r\nexport { setAccessToken, setRefreshToken, parseCookies, clearCookies };\r\n", "import { AuthGneissCore, AuthGneissCoreConfig } from \"@core\";\r\nimport { Request, Response, NextFunction } from \"express\";\r\nimport { RequestWithTokens, Tokens } from \"@core/types\";\r\nimport { setAccessToken, setRefreshToken, parseCookies } from \"@utils\";\r\nimport { JwtPayload } from \"jsonwebtoken\";\r\nimport { AxiosError } from \"axios\";\r\nimport axios from \"axios\";\r\nimport { clearCookies } from \"@/utils/storage/cookieHandling\";\r\n\r\n/**\r\n * ExpressAuthGneissClient extends AuthGneissCore to provide Express-specific authentication middleware\r\n * and functionality for handling OAuth2 authentication flow with Gneiss authentication service.\r\n * \r\n * @extends AuthGneissCore\r\n * @example\r\n * const authClient = new ExpressAuthGneissClient({\r\n * clientId: 'your-client-id',\r\n * clientSecret: 'your-client-secret',\r\n * redirectUrl: 'your-redirect-url'\r\n * });\r\n */\r\nclass ExpressAuthGneissClient extends AuthGneissCore {\r\n\r\n constructor(\r\n config: AuthGneissCoreConfig\r\n ) {\r\n super(config);\r\n \r\n // Bind the methods in constructor\r\n this.requireAuth = this.requireAuth.bind(this);\r\n this.handleCallBack = this.handleCallBack.bind(this);\r\n this.login = this.login.bind(this);\r\n this.logout = this.logout.bind(this);\r\n this.getUser = this.getUser.bind(this);\r\n this.deleteUser = this.deleteUser.bind(this)\r\n }\r\n\r\n /**\r\n * requireAuth is a middleware function that checks if the access token is valid.\r\n * If the access token is not valid, it attempts to refresh the token using the refresh token.\r\n * If the refresh token is not valid, it redirects the user to the login page.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n * @param next - The next middleware function.\r\n */\r\n public async requireAuth(req: Request, res: Response, next: NextFunction): Promise<void> {\r\n const cookies = parseCookies(req);\r\n //Check for the existence of the access token\r\n console.log(\"DEBUG: cookies\", cookies);\r\n try {\r\n const isAccessTokenValid : boolean = await this.validateToken(cookies?.accessToken);\r\n if (!isAccessTokenValid) { //if the access token is not valid\r\n //try to refresh the token\r\n const newAccessToken : string | null = await this.refreshToken(cookies?.refreshToken);\r\n if (newAccessToken) { // set access token and then redirect to the original requested url to 'redo' the request with new access token\r\n setAccessToken(res, newAccessToken);\r\n res.redirect(req.originalUrl)\r\n }\r\n else {\r\n // no access token or valid refresh token, redirect to login\r\n const returnToUrl : string | undefined = req.originalUrl as string;\r\n res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseUrl}${this.config.redirectUrl}&return_to_url=${returnToUrl}`);\r\n }\r\n }\r\n else {\r\n // access token is valid, continue to the next middleware or route handler\r\n next();\r\n }\r\n } catch (error) {\r\n // console.error('Error in requireAuth middleware:', error);\r\n if (error instanceof AxiosError) {\r\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\r\n } else {\r\n res.status(500).send('Internal server error');\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * getUserData is a middleware function that fetches user data using the access token.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n * @param next - The next middleware function.\r\n */\r\n public async getUser(req: Request, res: Response): Promise<void> {\r\n const cookies = parseCookies(req);\r\n const accessToken = cookies?.accessToken;\r\n if (!accessToken) {\r\n throw new Error(\"No access token found in request cookies\");\r\n }\r\n const userData = await this.getUserData(accessToken);\r\n res.status(200).send(userData);\r\n }\r\n\r\n /**\r\n * handleCallBack is a middleware function that handles the callback from the authentication service.\r\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.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n * @param next - The next middleware function.\r\n */\r\n public async handleCallBack(\r\n req: Request,\r\n res: Response,\r\n next: NextFunction\r\n ): Promise<void> {\r\n try {\r\n const authCode: string | undefined = req.query.auth_code as string\r\n const returnToUrl : string | undefined = req.query.return_to_url as string;\r\n if (!authCode) {\r\n throw new Error(\"No auth code found in request url parameters\");\r\n }\r\n\r\n const tokens: Tokens = await this.getTokens(authCode);\r\n \r\n // Set the access and refresh tokens in the response cookies\r\n setAccessToken(res, tokens.accessToken);\r\n setRefreshToken(res, tokens.refreshToken);\r\n\r\n if (returnToUrl) {\r\n // Go to the original request url\r\n res.redirect(returnToUrl);\r\n }\r\n else {\r\n // Go to the root url\r\n res.redirect(\"/\")\r\n }\r\n } catch (error) {\r\n // console.error('Error in handleCallBack middleware:', error);\r\n if (error instanceof AxiosError) {\r\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\r\n console.error(\"DEBUG: error\", error);\r\n } else {\r\n res.status(500).send('Internal server error');\r\n console.error(\"DEBUG: error\", error);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * login is a function that redirects the user to the Gneiss authentication service for authentication.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n */\r\n public login(req: Request, res: Response): void {\r\n try {\r\n if (!this.loginUrl) {\r\n throw new Error('Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\r\n }\r\n res.redirect(this.loginUrl + `?redirect_url=${this.config.baseUrl}${this.config.redirectUrl}`);\r\n } catch (error) {\r\n console.error('Error in login middleware:', error);\r\n res.status(500).send('Internal server error');\r\n }\r\n }\r\n\r\n /**\r\n * logout is a function that redirects the user to the Gneiss logout service.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n */\r\n public logout(req: Request, res: Response): void {\r\n const cookies = parseCookies(req);\r\n try {\r\n if (!this.logoutUrl) {\r\n throw new Error('Logout URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\r\n }\r\n if (cookies?.accessToken) { // Only logout if the access token exists\r\n axios.post(this.logoutUrl, {}, { // Logout\r\n headers: {\r\n \"Authorization\": `Bearer ${cookies?.accessToken}`\r\n }\r\n });\r\n }\r\n clearCookies(res); // clear the access and refresh cookies\r\n res.redirect(\"/\") // Redirect back to home after logout\r\n } catch (error) {\r\n console.error('Error in logout middleware:', error);\r\n res.status(500).send('Internal server error');\r\n }\r\n }\r\n\r\n /**\r\n * Utility route handler for deleting a user\r\n * This ensures that the user is fully logged out before \r\n * deleting the user's data\r\n * \r\n * @param req - The request object.\r\n * @param res - The response object.\r\n */\r\n public deleteUser(req: Request, res: Response) {\r\n const cookies = parseCookies(req);\r\n this.logout(req, res)\r\n this.deleteUserData(cookies?.accessToken)\r\n }\r\n}\r\n\r\nexport default ExpressAuthGneissClient;\r\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,mBAAqC;AAErC,oBAAmB;AACnB,IAAAA,gBAA2B;
|
|
6
|
-
"names": ["import_axios", "dotenv", "axios", "import_axios", "axios"]
|
|
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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iB,KAAK,OAAO,aAAa,GAAG,KAAK,OAAO,WAAW,EAAE;AAAA,IACvG,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
7
|
}
|
package/dist/esm/index.js
CHANGED
|
@@ -2,19 +2,25 @@
|
|
|
2
2
|
import axios from "axios";
|
|
3
3
|
import dotenv from "dotenv";
|
|
4
4
|
import { AxiosError } from "axios";
|
|
5
|
-
|
|
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
|
+
}
|
|
6
15
|
var AuthGneissCore = class {
|
|
7
|
-
constructor(
|
|
8
|
-
this.config = config;
|
|
9
|
-
this.
|
|
10
|
-
this.loginUrl = this.
|
|
11
|
-
this.logoutUrl = this.
|
|
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;
|
|
12
21
|
let errorMsgs = [];
|
|
13
|
-
if (!process.env.
|
|
14
|
-
errorMsgs.push("
|
|
15
|
-
}
|
|
16
|
-
if (!process.env.NODE_ENV) {
|
|
17
|
-
errorMsgs.push("NODE_ENV is not set in environment variables");
|
|
22
|
+
if (!process.env.ENV) {
|
|
23
|
+
errorMsgs.push("ENV is not set in environment variables");
|
|
18
24
|
}
|
|
19
25
|
if (errorMsgs.length > 0) {
|
|
20
26
|
throw new Error(errorMsgs.join("\n"));
|
|
@@ -28,7 +34,7 @@ var AuthGneissCore = class {
|
|
|
28
34
|
*/
|
|
29
35
|
async getTokens(authCode) {
|
|
30
36
|
try {
|
|
31
|
-
const url = `${this.
|
|
37
|
+
const url = `${this.authUrl}/auth/access_token?auth_code=${authCode}`;
|
|
32
38
|
const encodedClientId = btoa(this.config.clientId);
|
|
33
39
|
const encodedClientSecret = btoa(this.config.clientSecret);
|
|
34
40
|
const response = await axios.post(url, {}, {
|
|
@@ -52,7 +58,7 @@ var AuthGneissCore = class {
|
|
|
52
58
|
*/
|
|
53
59
|
async refreshToken(refreshToken) {
|
|
54
60
|
try {
|
|
55
|
-
const url = `${this.
|
|
61
|
+
const url = `${this.authUrl}/auth/refresh`;
|
|
56
62
|
const response = await axios.post(url, {}, {
|
|
57
63
|
headers: {
|
|
58
64
|
"Authorization": `Bearer ${refreshToken}`
|
|
@@ -69,7 +75,7 @@ var AuthGneissCore = class {
|
|
|
69
75
|
* @returns A promise that resolves to the user data.
|
|
70
76
|
*/
|
|
71
77
|
async getUserData(accessToken) {
|
|
72
|
-
const url = `${this.
|
|
78
|
+
const url = `${this.authUrl}/resource/user_data`;
|
|
73
79
|
const response = await axios.get(url, {
|
|
74
80
|
headers: {
|
|
75
81
|
"Authorization": `Bearer ${accessToken}`
|
|
@@ -91,7 +97,7 @@ var AuthGneissCore = class {
|
|
|
91
97
|
if (!token) {
|
|
92
98
|
return false;
|
|
93
99
|
}
|
|
94
|
-
const url = `${this.
|
|
100
|
+
const url = `${this.authUrl}/auth/validate_token`;
|
|
95
101
|
const response = await axios.get(url, {
|
|
96
102
|
headers: {
|
|
97
103
|
"Authorization": `Bearer ${token}`
|
|
@@ -117,7 +123,7 @@ var AuthGneissCore = class {
|
|
|
117
123
|
* deleteUser deletes the user
|
|
118
124
|
* */
|
|
119
125
|
async deleteUserData(accessToken) {
|
|
120
|
-
const response = await axios.post(`${this.
|
|
126
|
+
const response = await axios.post(`${this.authUrl}/resource/delete_user`, {}, {
|
|
121
127
|
headers: {
|
|
122
128
|
"Authorization": `Bearer ${accessToken}`
|
|
123
129
|
}
|
|
@@ -136,7 +142,7 @@ function setAccessToken(res, accessToken) {
|
|
|
136
142
|
}
|
|
137
143
|
res.cookie("accessToken", accessToken, {
|
|
138
144
|
httpOnly: true,
|
|
139
|
-
secure: process.env.
|
|
145
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
140
146
|
sameSite: "lax",
|
|
141
147
|
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
142
148
|
});
|
|
@@ -148,7 +154,7 @@ function setRefreshToken(res, refreshToken) {
|
|
|
148
154
|
}
|
|
149
155
|
res.cookie("refreshToken", refreshToken, {
|
|
150
156
|
httpOnly: true,
|
|
151
|
-
secure: process.env.
|
|
157
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
152
158
|
sameSite: "lax",
|
|
153
159
|
maxAge: decodedToken.exp * 1e3 - Date.now()
|
|
154
160
|
});
|
|
@@ -167,13 +173,13 @@ function parseCookies(req) {
|
|
|
167
173
|
function clearCookies(res) {
|
|
168
174
|
res.clearCookie("accessToken", {
|
|
169
175
|
httpOnly: true,
|
|
170
|
-
secure: process.env.
|
|
176
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
171
177
|
sameSite: "strict",
|
|
172
178
|
path: "/"
|
|
173
179
|
});
|
|
174
180
|
res.clearCookie("refreshToken", {
|
|
175
181
|
httpOnly: true,
|
|
176
|
-
secure: process.env.
|
|
182
|
+
secure: process.env.ENV === "prod" || process.env.ENV === "staging",
|
|
177
183
|
sameSite: "strict",
|
|
178
184
|
path: "/"
|
|
179
185
|
});
|
|
@@ -183,8 +189,8 @@ function clearCookies(res) {
|
|
|
183
189
|
import { AxiosError as AxiosError2 } from "axios";
|
|
184
190
|
import axios2 from "axios";
|
|
185
191
|
var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
186
|
-
constructor(
|
|
187
|
-
super(
|
|
192
|
+
constructor(config2) {
|
|
193
|
+
super(config2);
|
|
188
194
|
this.requireAuth = this.requireAuth.bind(this);
|
|
189
195
|
this.handleCallBack = this.handleCallBack.bind(this);
|
|
190
196
|
this.login = this.login.bind(this);
|
|
@@ -212,7 +218,7 @@ var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
|
212
218
|
res.redirect(req.originalUrl);
|
|
213
219
|
} else {
|
|
214
220
|
const returnToUrl = req.originalUrl;
|
|
215
|
-
res.redirect(`${this.loginUrl}?redirect_url=${this.config.
|
|
221
|
+
res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}&return_to_url=${returnToUrl}`);
|
|
216
222
|
}
|
|
217
223
|
} else {
|
|
218
224
|
next();
|
|
@@ -282,7 +288,7 @@ var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
|
282
288
|
if (!this.loginUrl) {
|
|
283
289
|
throw new Error("Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.");
|
|
284
290
|
}
|
|
285
|
-
res.redirect(this.loginUrl + `?redirect_url=${this.config.
|
|
291
|
+
res.redirect(this.loginUrl + `?redirect_url=${this.config.baseClientUrl}${this.config.callbackUrl}`);
|
|
286
292
|
} catch (error) {
|
|
287
293
|
console.error("Error in login middleware:", error);
|
|
288
294
|
res.status(500).send("Internal server error");
|
|
@@ -331,6 +337,7 @@ var ExpressAuthGneissClient = class extends AuthGneissCore_default {
|
|
|
331
337
|
var ExpressAuthGneissClient_default = ExpressAuthGneissClient;
|
|
332
338
|
export {
|
|
333
339
|
AuthGneissCore_default as AuthGneissCore,
|
|
334
|
-
ExpressAuthGneissClient_default as ExpressAuthGneissClient
|
|
340
|
+
ExpressAuthGneissClient_default as ExpressAuthGneissClient,
|
|
341
|
+
parseCookies
|
|
335
342
|
};
|
|
336
343
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/core/AuthGneissCore.ts", "../../src/utils/storage/cookieHandling.ts", "../../src/frameworks/express/middleware/ExpressAuthGneissClient.ts"],
|
|
4
|
-
"sourcesContent": ["import { AuthGneissCoreConfig } from \"@core/types\";\r\nimport axios, { AxiosResponse } from \"axios\";\r\nimport { Tokens } from \"@core/types\";\r\nimport dotenv from \"dotenv\";\r\nimport { AxiosError } from \"axios\";\r\n\r\n//load environment variables\r\ndotenv.config();\r\n\r\n/**\r\n * AuthGneissCore provides core functionality for OAuth2 authentication flow with Gneiss authentication service.\r\n * It handles token exchange, token refresh, user data fetching, and token validation.\r\n * \r\n * This class serves as a base class that can be extended by framework-specific implementations\r\n * to provide authentication middleware and handlers.\r\n */\r\nclass AuthGneissCore {\r\n protected config: AuthGneissCoreConfig; // Configuration object\r\n protected gneissEnpoint : string | undefined\r\n protected loginUrl : string | undefined\r\n protected logoutUrl : string | undefined\r\n\r\n constructor(\r\n config: AuthGneissCoreConfig\r\n ) {\r\n this.config = config;\r\n this.gneissEnpoint = process.env.GNEISS_ENDPOINT // Gneiss endpoint\r\n this.loginUrl = this.gneissEnpoint ? `${this.gneissEnpoint}/auth/login` : undefined; // Login URL\r\n this.logoutUrl = this.gneissEnpoint ? `${this.gneissEnpoint}/auth/logout` : undefined; // Logout URL\r\n\r\n //check if environment variables are set\r\n let errorMsgs = [];\r\n if (!process.env.GNEISS_ENDPOINT) {\r\n errorMsgs.push(\"GNEISS_ENDPOINT is not set in environment variables\");\r\n }\r\n if (!process.env.NODE_ENV) {\r\n errorMsgs.push(\"NODE_ENV is not set in environment variables\");\r\n }\r\n if (errorMsgs.length > 0) {\r\n throw new Error(errorMsgs.join(\"\\n\"));\r\n }\r\n }\r\n\r\n /**\r\n * getTokens is a method that exchanges an authentication code for access and refresh tokens.\r\n * The client id and secret are passed as basic auth headers to authenticate the client itself.\r\n * @param authCode - The authentication code received from the Gneiss authentication service.\r\n * @returns A promise that resolves to an object containing the access and refresh tokens.\r\n */\r\n protected async getTokens(authCode : string) : Promise<Tokens> {\r\n try {\r\n const url : string = `${this.gneissEnpoint}/auth/access_token?auth_code=${authCode}`;\r\n //Encode in base64 before transport\r\n const encodedClientId = btoa(this.config.clientId);\r\n const encodedClientSecret = btoa(this.config.clientSecret);\r\n const response : AxiosResponse = await axios.post(url, {}, {\r\n headers: {\r\n \"Authorization\": `Basic ${encodedClientId}:${encodedClientSecret}`\r\n }\r\n });\r\n return {\r\n accessToken: response.data.access_token,\r\n refreshToken: response.data.refresh_token,\r\n tokenType: response.data.token_type\r\n } as Tokens;\r\n } catch (error) {\r\n // console.error(\"Error in getTokens:\", error);\r\n throw error;\r\n }\r\n }\r\n \r\n /**\r\n * refreshToken is a method that refreshes the access token using the refresh token.\r\n * @param refreshToken - The refresh token to be used for token refresh.\r\n * @returns A promise that resolves to the refreshed access token.\r\n */\r\n protected async refreshToken(refreshToken: string): Promise<string | null> {\r\n try {\r\n const url : string = `${this.gneissEnpoint}/auth/refresh`;\r\n const response : AxiosResponse = await axios.post(url, {}, {\r\n headers: {\r\n \"Authorization\": `Bearer ${refreshToken}`\r\n }\r\n });\r\n return response.data.access_token as string;\r\n } catch (error) {\r\n // console.error(\"Error in refreshToken:\", error);\r\n return null;\r\n }\r\n }\r\n \r\n /**\r\n * getUserData is a method that fetches user data using the access token.\r\n * @param accessToken - The access token to be used for user data fetching.\r\n * @returns A promise that resolves to the user data.\r\n */\r\n protected async getUserData(accessToken: string) {\r\n const url : string = `${this.gneissEnpoint}/resource/user_data`;\r\n const response : AxiosResponse = await axios.get(url, {\r\n headers: {\r\n \"Authorization\": `Bearer ${accessToken}`\r\n }\r\n });\r\n if (response.status === 200) {\r\n return response.data;\r\n }\r\n throw new Error(\"Failed to fetch user data\");\r\n }\r\n \r\n /**\r\n * validateToken is a method that validates the access token.\r\n * @param token - The access token to be validated.\r\n * @returns A promise that resolves to a boolean indicating the validity of the token.\r\n */\r\n protected async validateToken(token: string): Promise<boolean> {\r\n try {\r\n console.log(\"DEBUG: token\", token);\r\n // Token validation logic\r\n if (!token) {\r\n return false;\r\n }\r\n const url : string = `${this.gneissEnpoint}/auth/validate_token`;\r\n const response : AxiosResponse = await axios.get(url, {\r\n headers: {\r\n \"Authorization\": `Bearer ${token}`\r\n }\r\n });\r\n return response.status === 200;\r\n } catch (error) {\r\n // console.error(\"Error in validateToken:\", error);\r\n if (error instanceof AxiosError && error.response?.status === 401) {\r\n return false;\r\n } else {\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * getLoginUrl is a method that returns the login URL.\r\n * @returns The login URL.\r\n */\r\n public getLoginUrl() : string | undefined {\r\n return this.loginUrl;\r\n }\r\n\r\n /**\r\n * deleteUser deletes the user\r\n * */\r\n protected async deleteUserData(accessToken : string) : Promise<object> {\r\n const response : AxiosResponse = await axios.post(`${this.gneissEnpoint}/resource/delete_user`, {}, {\r\n headers: {\r\n \"Authorization\": `Bearer ${accessToken}`\r\n } \r\n });\r\n return response.data;\r\n }\r\n}\r\n\r\nexport default AuthGneissCore;\r\n", "import { Response } from \"express\";\r\nimport { JwtPayload, decode } from \"jsonwebtoken\";\r\nimport { Request } from \"express\";\r\n\r\n/**\r\n * Set the access token in the response cookies.\r\n * @param res - The response object.\r\n * @param accessToken - The access token to set.\r\n */\r\nfunction setAccessToken(res: Response, accessToken: string) {\r\n\r\n const decodedToken = decode(accessToken) as JwtPayload;\r\n \r\n // decoded.exp is in seconds since epoch\r\n // Date.now() returns milliseconds since epoch\r\n // maxAge needs milliseconds remaining\r\n if (!decodedToken.exp) {\r\n throw new Error(\"Access token does not contain an expiration time\");\r\n }\r\n \r\n res.cookie('accessToken', accessToken, {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'lax',\r\n maxAge: (decodedToken.exp * 1000) - Date.now()\r\n });\r\n}\r\n\r\n/**\r\n * Set the refresh token in the response cookies.\r\n * @param res - The response object.\r\n * @param refreshToken - The refresh token to set.\r\n */\r\nfunction setRefreshToken(res: Response, refreshToken: string) {\r\n\r\n const decodedToken = decode(refreshToken) as JwtPayload;\r\n\r\n if (!decodedToken.exp) {\r\n throw new Error(\"Refresh token does not contain an expiration time\");\r\n }\r\n\r\n res.cookie('refreshToken', refreshToken, {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'lax',\r\n maxAge: (decodedToken.exp * 1000) - Date.now()\r\n });\r\n}\r\n\r\nfunction parseCookies(req: Request) : { [key: string]: string } {\r\n const cookies = req.headers.cookie;\r\n if (!cookies) {\r\n return {};\r\n }\r\n return cookies.split(';').reduce((acc: { [key: string]: string }, cookie) => {\r\n const [key, value] = cookie.split('=').map(s => s.trim());\r\n acc[key] = value;\r\n return acc;\r\n }, {});\r\n}\r\n\r\nfunction clearCookies(res: Response) {\r\n res.clearCookie(\"accessToken\", {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'strict',\r\n path: '/'\r\n });\r\n res.clearCookie(\"refreshToken\", {\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'strict',\r\n path: '/'\r\n });\r\n}\r\n\r\nexport { setAccessToken, setRefreshToken, parseCookies, clearCookies };\r\n", "import { AuthGneissCore, AuthGneissCoreConfig } from \"@core\";\r\nimport { Request, Response, NextFunction } from \"express\";\r\nimport { RequestWithTokens, Tokens } from \"@core/types\";\r\nimport { setAccessToken, setRefreshToken, parseCookies } from \"@utils\";\r\nimport { JwtPayload } from \"jsonwebtoken\";\r\nimport { AxiosError } from \"axios\";\r\nimport axios from \"axios\";\r\nimport { clearCookies } from \"@/utils/storage/cookieHandling\";\r\n\r\n/**\r\n * ExpressAuthGneissClient extends AuthGneissCore to provide Express-specific authentication middleware\r\n * and functionality for handling OAuth2 authentication flow with Gneiss authentication service.\r\n * \r\n * @extends AuthGneissCore\r\n * @example\r\n * const authClient = new ExpressAuthGneissClient({\r\n * clientId: 'your-client-id',\r\n * clientSecret: 'your-client-secret',\r\n * redirectUrl: 'your-redirect-url'\r\n * });\r\n */\r\nclass ExpressAuthGneissClient extends AuthGneissCore {\r\n\r\n constructor(\r\n config: AuthGneissCoreConfig\r\n ) {\r\n super(config);\r\n \r\n // Bind the methods in constructor\r\n this.requireAuth = this.requireAuth.bind(this);\r\n this.handleCallBack = this.handleCallBack.bind(this);\r\n this.login = this.login.bind(this);\r\n this.logout = this.logout.bind(this);\r\n this.getUser = this.getUser.bind(this);\r\n this.deleteUser = this.deleteUser.bind(this)\r\n }\r\n\r\n /**\r\n * requireAuth is a middleware function that checks if the access token is valid.\r\n * If the access token is not valid, it attempts to refresh the token using the refresh token.\r\n * If the refresh token is not valid, it redirects the user to the login page.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n * @param next - The next middleware function.\r\n */\r\n public async requireAuth(req: Request, res: Response, next: NextFunction): Promise<void> {\r\n const cookies = parseCookies(req);\r\n //Check for the existence of the access token\r\n console.log(\"DEBUG: cookies\", cookies);\r\n try {\r\n const isAccessTokenValid : boolean = await this.validateToken(cookies?.accessToken);\r\n if (!isAccessTokenValid) { //if the access token is not valid\r\n //try to refresh the token\r\n const newAccessToken : string | null = await this.refreshToken(cookies?.refreshToken);\r\n if (newAccessToken) { // set access token and then redirect to the original requested url to 'redo' the request with new access token\r\n setAccessToken(res, newAccessToken);\r\n res.redirect(req.originalUrl)\r\n }\r\n else {\r\n // no access token or valid refresh token, redirect to login\r\n const returnToUrl : string | undefined = req.originalUrl as string;\r\n res.redirect(`${this.loginUrl}?redirect_url=${this.config.baseUrl}${this.config.redirectUrl}&return_to_url=${returnToUrl}`);\r\n }\r\n }\r\n else {\r\n // access token is valid, continue to the next middleware or route handler\r\n next();\r\n }\r\n } catch (error) {\r\n // console.error('Error in requireAuth middleware:', error);\r\n if (error instanceof AxiosError) {\r\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\r\n } else {\r\n res.status(500).send('Internal server error');\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * getUserData is a middleware function that fetches user data using the access token.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n * @param next - The next middleware function.\r\n */\r\n public async getUser(req: Request, res: Response): Promise<void> {\r\n const cookies = parseCookies(req);\r\n const accessToken = cookies?.accessToken;\r\n if (!accessToken) {\r\n throw new Error(\"No access token found in request cookies\");\r\n }\r\n const userData = await this.getUserData(accessToken);\r\n res.status(200).send(userData);\r\n }\r\n\r\n /**\r\n * handleCallBack is a middleware function that handles the callback from the authentication service.\r\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.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n * @param next - The next middleware function.\r\n */\r\n public async handleCallBack(\r\n req: Request,\r\n res: Response,\r\n next: NextFunction\r\n ): Promise<void> {\r\n try {\r\n const authCode: string | undefined = req.query.auth_code as string\r\n const returnToUrl : string | undefined = req.query.return_to_url as string;\r\n if (!authCode) {\r\n throw new Error(\"No auth code found in request url parameters\");\r\n }\r\n\r\n const tokens: Tokens = await this.getTokens(authCode);\r\n \r\n // Set the access and refresh tokens in the response cookies\r\n setAccessToken(res, tokens.accessToken);\r\n setRefreshToken(res, tokens.refreshToken);\r\n\r\n if (returnToUrl) {\r\n // Go to the original request url\r\n res.redirect(returnToUrl);\r\n }\r\n else {\r\n // Go to the root url\r\n res.redirect(\"/\")\r\n }\r\n } catch (error) {\r\n // console.error('Error in handleCallBack middleware:', error);\r\n if (error instanceof AxiosError) {\r\n res.status((error as AxiosError).response?.status || 500).send((error as AxiosError).response?.data || 'Internal server error');\r\n console.error(\"DEBUG: error\", error);\r\n } else {\r\n res.status(500).send('Internal server error');\r\n console.error(\"DEBUG: error\", error);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * login is a function that redirects the user to the Gneiss authentication service for authentication.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n */\r\n public login(req: Request, res: Response): void {\r\n try {\r\n if (!this.loginUrl) {\r\n throw new Error('Login URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\r\n }\r\n res.redirect(this.loginUrl + `?redirect_url=${this.config.baseUrl}${this.config.redirectUrl}`);\r\n } catch (error) {\r\n console.error('Error in login middleware:', error);\r\n res.status(500).send('Internal server error');\r\n }\r\n }\r\n\r\n /**\r\n * logout is a function that redirects the user to the Gneiss logout service.\r\n * @param req - The request object.\r\n * @param res - The response object.\r\n */\r\n public logout(req: Request, res: Response): void {\r\n const cookies = parseCookies(req);\r\n try {\r\n if (!this.logoutUrl) {\r\n throw new Error('Logout URL is not configured. Check if GNEISS_ENDPOINT environment variable is set.');\r\n }\r\n if (cookies?.accessToken) { // Only logout if the access token exists\r\n axios.post(this.logoutUrl, {}, { // Logout\r\n headers: {\r\n \"Authorization\": `Bearer ${cookies?.accessToken}`\r\n }\r\n });\r\n }\r\n clearCookies(res); // clear the access and refresh cookies\r\n res.redirect(\"/\") // Redirect back to home after logout\r\n } catch (error) {\r\n console.error('Error in logout middleware:', error);\r\n res.status(500).send('Internal server error');\r\n }\r\n }\r\n\r\n /**\r\n * Utility route handler for deleting a user\r\n * This ensures that the user is fully logged out before \r\n * deleting the user's data\r\n * \r\n * @param req - The request object.\r\n * @param res - The response object.\r\n */\r\n public deleteUser(req: Request, res: Response) {\r\n const cookies = parseCookies(req);\r\n this.logout(req, res)\r\n this.deleteUserData(cookies?.accessToken)\r\n }\r\n}\r\n\r\nexport default ExpressAuthGneissClient;\r\n"],
|
|
5
|
-
"mappings": ";AACA,OAAO,WAA8B;AAErC,OAAO,YAAY;AACnB,SAAS,kBAAkB;
|
|
6
|
-
"names": ["AxiosError", "axios", "AxiosError", "axios"]
|
|
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,UA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c,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,QAAAC,OAAM,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": ["AxiosError", "axios", "config", "AxiosError", "axios"]
|
|
7
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"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AuthGneissCoreConfig } from "@core/types";
|
|
2
2
|
import { Tokens } from "@core/types";
|
|
3
|
+
import { AuthGneissGeneralConfig } from "@/config";
|
|
3
4
|
/**
|
|
4
5
|
* AuthGneissCore provides core functionality for OAuth2 authentication flow with Gneiss authentication service.
|
|
5
6
|
* It handles token exchange, token refresh, user data fetching, and token validation.
|
|
@@ -8,11 +9,11 @@ import { Tokens } from "@core/types";
|
|
|
8
9
|
* to provide authentication middleware and handlers.
|
|
9
10
|
*/
|
|
10
11
|
declare class AuthGneissCore {
|
|
11
|
-
protected config: AuthGneissCoreConfig;
|
|
12
|
-
protected
|
|
12
|
+
protected config: AuthGneissCoreConfig & AuthGneissGeneralConfig;
|
|
13
|
+
protected authUrl: string | undefined;
|
|
13
14
|
protected loginUrl: string | undefined;
|
|
14
15
|
protected logoutUrl: string | undefined;
|
|
15
|
-
constructor(
|
|
16
|
+
constructor(devConfig: AuthGneissCoreConfig);
|
|
16
17
|
/**
|
|
17
18
|
* getTokens is a method that exchanges an authentication code for access and refresh tokens.
|
|
18
19
|
* The client id and secret are passed as basic auth headers to authenticate the client itself.
|
|
@@ -31,7 +32,7 @@ declare class AuthGneissCore {
|
|
|
31
32
|
* @param accessToken - The access token to be used for user data fetching.
|
|
32
33
|
* @returns A promise that resolves to the user data.
|
|
33
34
|
*/
|
|
34
|
-
|
|
35
|
+
getUserData(accessToken: string): Promise<any>;
|
|
35
36
|
/**
|
|
36
37
|
* validateToken is a method that validates the access token.
|
|
37
38
|
* @param token - The access token to be validated.
|
|
@@ -1 +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;
|
|
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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/core/types.ts"],"names":[],"mappings":"
|
|
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"}
|
|
@@ -1 +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,YAAY,EAAE,oBAAoB,EAAE,MAAM,QAAQ,CAAC"}
|
|
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"}
|