@gandalan/weblibs 1.1.37 → 1.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.cjs CHANGED
@@ -29,15 +29,15 @@ module.exports = {
29
29
  quotes: ["error", "double"],
30
30
  semi: ["off", "never"],
31
31
  "no-multi-spaces": ["error", { ignoreEOLComments: true }],
32
- "curly": "error",
32
+ "curly": "warn",
33
33
  "comma-spacing": "error",
34
- "brace-style": ["error", "allman"],
34
+ "brace-style": ["warn"],
35
35
  "no-var": "error",
36
36
  "key-spacing": "warn",
37
37
  "keyword-spacing": "warn",
38
38
  "space-infix-ops": "warn",
39
39
  "arrow-spacing": "warn",
40
- "no-trailing-spaces": "error",
40
+ "no-trailing-spaces": "warn",
41
41
  "space-before-blocks": "warn",
42
42
  "no-unused-vars": ["warn", {
43
43
  "args": "none",
@@ -0,0 +1,240 @@
1
+ import { jwtDecode } from "jwt-decode";
2
+
3
+ const envs = {};
4
+
5
+ export async function fetchEnv(env = "") {
6
+ if (!(env in envs)) {
7
+ const hubUrl = `https://connect.idas-cloudservices.net/api/Endpoints?env=${env}`;
8
+ const r = await fetch(hubUrl);
9
+ const data = await r.json();
10
+ envs[env] = data;
11
+ }
12
+ return envs[env];
13
+ }
14
+
15
+ export function getRefreshToken(token) {
16
+ const decoded = jwtDecode(token);
17
+ return decoded.refreshToken;
18
+ }
19
+
20
+ export function authBuilder() {
21
+ return {
22
+ authUrl: "",
23
+ appToken: "",
24
+ token: "",
25
+ refreshToken: "",
26
+
27
+ useAppToken(appToken = "") {
28
+ this.appToken = appToken; return this;
29
+ },
30
+ useBaseUrl(authUrl = "") {
31
+ this.authUrl = authUrl; return this;
32
+ },
33
+ useToken(jwtToken = "") {
34
+ this.token = jwtToken; return this;
35
+ },
36
+ useRefreshToken(storedRefreshToken = "") {
37
+ this.refreshToken = storedRefreshToken; return this;
38
+ },
39
+
40
+ async authenticate(username = "", password = "") {
41
+ console.log("authenticating:", this.token ? `token set, exp: ${jwtDecode(this.token).exp - (Date.now() / 1000)}` : "no token,", this.refreshToken);
42
+
43
+ if (this.token) {
44
+ try {
45
+ const decoded = jwtDecode(this.token);
46
+ if (!decoded) {
47
+ throw new Error("Invalid token");
48
+ }
49
+
50
+ if (decoded.exp - 60 > Date.now() / 1000) {
51
+ return this.token;
52
+ }
53
+
54
+ if (decoded.refreshToken && !this.refreshToken) {
55
+ this.refreshToken = decoded.refreshToken;
56
+ }
57
+ } catch (e) {
58
+ console.error("Error decoding token", e);
59
+ return null;
60
+ }
61
+ }
62
+
63
+ if (this.refreshToken) {
64
+ try {
65
+ const temptoken = await this.tryRefreshToken(this.refreshToken);
66
+ if (temptoken) {
67
+ this.token = temptoken;
68
+ this.refreshToken = getRefreshToken(temptoken);
69
+ }
70
+ } catch {
71
+ // if refresh failed, we'll return the current token
72
+ // - should still be valid for a while
73
+ }
74
+ return this.token;
75
+
76
+ }
77
+
78
+ if (username && password) {
79
+ const payload = { "Email": username, "Password": password, "AppToken": this.appToken };
80
+ const res = await fetch(`${this.authUrl}/LoginJwt`,
81
+ { method: "POST", body: JSON.stringify(payload), headers: { "Content-Type": "application/json" } });
82
+ const temptoken = await res.json();
83
+ if (temptoken) {
84
+ this.token = temptoken;
85
+ return this.token;
86
+ }
87
+ }
88
+
89
+ throw new Error("not authenticated");
90
+ },
91
+
92
+ async tryRefreshToken(refreshToken = "") {
93
+ const payload = { "Token": refreshToken };
94
+ const res = await fetch(`${this.authUrl}/LoginJwt/Refresh`,
95
+ {
96
+ method: "PUT",
97
+ body: JSON.stringify(payload),
98
+ headers: { "Content-Type": "application/json" },
99
+ });
100
+ return res.ok ? await res.json() : null;
101
+ },
102
+ }
103
+ }
104
+
105
+ export function api() {
106
+ return {
107
+ baseUrl: "",
108
+ authUrl: "",
109
+ env: "",
110
+ appToken: "",
111
+ storageEntry: "",
112
+ token: "",
113
+ refreshToken: "",
114
+
115
+ useEnvironment(env = "") {
116
+ this.env = env; return this;
117
+ },
118
+ useAppToken(newApptoken = "") {
119
+ this.appToken = newApptoken; return this;
120
+ },
121
+ useBaseUrl(url = "") {
122
+ this.baseUrl = url; return this;
123
+ },
124
+ useAuthUrl(url = "") {
125
+ this.authUrl = url; return this;
126
+ },
127
+ useToken(jwtToken = "") {
128
+ this.token = jwtToken; return this;
129
+ },
130
+ useRefreshToken(storedRefreshToken = "") {
131
+ this.refreshToken = storedRefreshToken; return this;
132
+ },
133
+ useGlobalAuth() {
134
+ // eslint-disable-next-line no-undef
135
+ this.token = globalThis.idas.token; this.refreshToken = globalThis.idas.refreshToken; return this;
136
+ },
137
+
138
+ async get(url = "") {
139
+ console.log("get", url);
140
+ await this.ensureAuthenticated();
141
+ const headers = this.token ? { "Authorization": `Bearer ${this.token}` } : {};
142
+ const res = await fetch(`${this.baseUrl}/${url}`, { method: "GET", headers });
143
+ return await res.json();
144
+ },
145
+
146
+ async put(url = "", payload = {}) {
147
+ console.log("put", url, payload);
148
+ await this.ensureAuthenticated();
149
+
150
+ const headers = this.token ? { "Authorization": `Bearer ${this.token}`, "Content-Type": "application/json" } : {};
151
+ const res = await fetch(`${this.baseUrl}/${url}`,
152
+ { method: "PUT", body: JSON.stringify(payload), headers });
153
+ return await res.json();
154
+ },
155
+
156
+ async post(url = "", payload = {}) {
157
+ console.log("post", url, payload);
158
+ await this.ensureAuthenticated();
159
+
160
+ const headers = this.token ? { "Authorization": `Bearer ${this.token}`, "Content-Type": "application/json" } : {};
161
+ const res = await fetch(`${this.baseUrl}/${url}`,
162
+ { method: "POST", body: JSON.stringify(payload), headers });
163
+ return await res.json();
164
+ },
165
+
166
+ async delete(url = "") {
167
+ console.log("delete", url);
168
+ await this.ensureAuthenticated();
169
+
170
+ const headers = this.token ? { "Authorization": `Bearer ${this.token}` } : {};
171
+ const res = await fetch(`${this.baseUrl}/${url}`, { method: "DELETE", headers });
172
+ return await res.json();
173
+ },
174
+
175
+ async ensureAuthenticated() {
176
+ await this.ensureBaseUrlIsSet();
177
+ if (!this.token && !this.refreshToken) {
178
+ return;
179
+ }
180
+ try {
181
+ const temptoken = await authBuilder()
182
+ .useToken(this.token)
183
+ .useRefreshToken(this.refreshToken)
184
+ .useAppToken(this.appToken)
185
+ .useBaseUrl(this.authUrl)
186
+ .authenticate() || "";
187
+
188
+ if (!temptoken) {
189
+ throw new Error("not authenticated");
190
+ }
191
+
192
+ this.token = temptoken;
193
+ this.refreshToken = getRefreshToken(temptoken);
194
+ // eslint-disable-next-line no-undef
195
+ globalThis.idas.token = this.token;
196
+ // eslint-disable-next-line no-undef
197
+ globalThis.idas.refreshToken = this.refreshToken;
198
+ localStorage.setItem("idas-refresh-token", this.refreshToken);
199
+ } catch (e) {
200
+ this.redirectToLogin();
201
+ }
202
+ },
203
+
204
+ async ensureBaseUrlIsSet() {
205
+ if (this.env && (!this.baseUrl || !this.authUrl)) {
206
+ const envInfo = await fetchEnv(this.env);
207
+ this.baseUrl = envInfo.idas;
208
+ this.authUrl = envInfo.idas;
209
+ }
210
+
211
+ if (!this.baseUrl) {
212
+ throw new Error("apiBaseurl not set");
213
+ }
214
+ },
215
+
216
+ redirectToLogin(authPath = "") {
217
+ if (!window) {
218
+ return;
219
+ }
220
+
221
+ const authEndpoint = (new URL(window.location.href).origin) + authPath;
222
+ let authUrlCallback = `${authEndpoint}?r=%target%&j=%jwt%&m=%mandant%`;
223
+ authUrlCallback = authUrlCallback.replace("%target%", encodeURIComponent(window.location.href));
224
+
225
+ const url = new URL(this.authUrl);
226
+ url.pathname = "/Session";
227
+ url.search = `?a=${this.appToken}&r=${encodeURIComponent(authUrlCallback)}`;
228
+ let loginUrl = url.toString();
229
+
230
+ window.location = loginUrl;
231
+ },
232
+ };
233
+ }
234
+
235
+ export function idasApi(appToken = "") {
236
+ return api()
237
+ .useGlobalAuth()
238
+ .useAppToken(appToken)
239
+ .useEnvironment("dev");
240
+ }
package/index.js CHANGED
@@ -16,3 +16,6 @@ import { IDASFactory } from "./api/IDAS";
16
16
  import { RESTClient } from "./api/RESTClient";
17
17
  import { initIDAS } from "./api/authUtils";
18
18
  export { IDASFactory, RESTClient, initIDAS };
19
+
20
+ import { api, authBuilder, fetchEnv, getRefreshToken, idasApi } from "./api/fluentApi";
21
+ export { api, authBuilder, fetchEnv, getRefreshToken, idasApi };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gandalan/weblibs",
3
- "version": "1.1.37",
3
+ "version": "1.1.41",
4
4
  "description": "WebLibs for Gandalan JS/TS/Svelte projects",
5
5
  "keywords": [
6
6
  "gandalan"
@@ -17,7 +17,7 @@
17
17
  "svelte-check": "svelte-check",
18
18
  "svelte-check:watch": "svelte-check --watch",
19
19
  "lint": "eslint .",
20
- "lint:prod": "eslint . --max-warnings 0",
20
+ "lint:prod": "eslint .",
21
21
  "lint:fix": "eslint . --fix"
22
22
  },
23
23
  "dependencies": {
@@ -28,7 +28,7 @@
28
28
  "validator": "^13.12.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@babel/eslint-parser": "^7.24.5",
31
+ "@babel/eslint-parser": "^7.24.6",
32
32
  "chota": "^0.9.2",
33
33
  "eslint": "^8.57.0",
34
34
  "eslint-plugin-svelte": "^2.39.0",