@stack-spot/auth-react 2.14.0 → 2.14.1-beta.1

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/out/index.js CHANGED
@@ -1,786 +1,26 @@
1
1
  'use strict';
2
2
 
3
- var jsxRuntime = require('react/jsx-runtime');
4
- var core = require('@citric/core');
5
- var portalComponents = require('@stack-spot/portal-components');
6
- var portalTheme = require('@stack-spot/portal-theme');
7
- require('@stack-spot/portal-theme/dist/theme.css');
8
- var portalTranslate = require('@stack-spot/portal-translate');
9
- var react = require('react');
10
- var ui = require('@citric/ui');
11
- var auth = require('@stack-spot/auth');
12
- var svg = require('@stack-spot/portal-components/svg');
13
- var styledComponents = require('styled-components');
14
- var icons = require('@citric/icons');
15
- var lodash = require('lodash');
3
+ var Authenticated_tsx = require('./Authenticated.tsx');
4
+ var hooks_ts = require('./hooks.ts');
5
+ var Login_tsx = require('./Login.tsx');
6
+ var SessionManager_ts = require('./SessionManager.ts');
16
7
 
17
- const dictionary = {
18
- en: {
19
- welcome: "Welcome to StackSpot AI",
20
- loginWithEmail: "Log in with your email.",
21
- loginWithSocialAccount1: "Sign up or access your ",
22
- loginWithSocialAccount2: " freemium account ",
23
- loginWithSocialAccount3: " with a social login",
24
- label: "Corporate email",
25
- placeholder: "email@company.com",
26
- continue: "Continue",
27
- or: "Or",
28
- loginWith: "Continue with $0",
29
- emailNotAllowedTitle: "Your email is linked to an Enterprise account.",
30
- emailNotAllowedSubtitle: "Please log in with your corporate email.",
31
- socialLogin: "Login or register with a social account",
32
- corporateLoginTitle: "Already have a StackSpot Enterprise account?",
33
- corporateLoginButton: "Enter Enterprise account",
34
- socialLoginTitle: "Do you want to access another way?",
35
- emailNotFoundError: "We couldn't find an account for this email.",
36
- errorMobileDesktop: "It looks like you are using a mobile device in desktop mode. We recommend adjusting this setting before continuing for a complete experience.",
37
- loginTemporarilyUnavailable: "Login temporarily unavailable."
38
- },
39
- pt: {
40
- welcome: "Boas vindas \xE0 StackSpot AI",
41
- loginWithEmail: "Fa\xE7a login com seu e-mail.",
42
- loginWithSocialAccount1: "Cadastre-se ou acesse sua ",
43
- loginWithSocialAccount2: " conta freemium ",
44
- loginWithSocialAccount3: " com uma conta social",
45
- label: "Email corporativo",
46
- placeholder: "email@empresa.com",
47
- continue: "Continuar",
48
- or: "Ou",
49
- loginWith: "Continuar com $0",
50
- emailNotAllowedTitle: '"Este e-mail est\xE1 vinculado a uma conta Enterprise.',
51
- emailNotAllowedSubtitle: "Fa\xE7a login com seu email corporativo.",
52
- socialLogin: "Entre ou cadastre-se com uma conta social",
53
- corporateLoginTitle: "J\xE1 possui uma conta StackSpot Enterprise?",
54
- corporateLoginButton: "Entrar na conta Enterprise",
55
- socialLoginTitle: "Voc\xEA quer entrar de outro jeito?",
56
- emailNotFoundError: "N\xE3o encontramos uma conta para este e-mail.",
57
- errorMobileDesktop: "Parece que voc\xEA est\xE1 utilizando um dispositivo m\xF3vel na vers\xE3o desktop. Recomendamos ajustar essa configura\xE7\xE3o antes de continuar para uma experi\xEAncia completa.",
58
- loginTemporarilyUnavailable: "Login indispon\xEDvel temporariamente."
59
- }
60
- };
61
- const useTranslation = () => portalTranslate.useTranslate(dictionary);
62
8
 
63
- const sessionKey$1 = `stk-session${portalComponents.getCookieDomain()}`;
64
- const sessionCookie = Object.freeze({
65
- /**
66
- * Sets the user's session cookie
67
- * @param data session to be saved in the cookie
68
- * @param customAttributes Accepted values: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes.
69
- */
70
- set: (data, customAttributes = {}) => portalComponents.setCookie(sessionKey$1, JSON.stringify(data), customAttributes),
71
- get: () => {
72
- try {
73
- const cookie = portalComponents.getCookie(sessionKey$1);
74
- return cookie ? JSON.parse(cookie) : void 0;
75
- } catch (error) {
76
- console.error(error);
77
- }
78
- },
79
- delete: () => portalComponents.removeCookie(sessionKey$1)
80
- });
81
-
82
- const isValidDomain = (url) => {
83
- const portalDomainRegex = new RegExp(`^https?://[a-zA-Z0-9.-]*${portalComponents.getCookieDomain().replaceAll(".", ".")}(:[0-9]{2,4})*.*$`, "g");
84
- const platformDomainRegex = new RegExp(/^https:\/\/[a-zA-Z0-9.-]+\.stackspot\.com.*$/, "g");
85
- const result = portalDomainRegex.test(url) || platformDomainRegex.test(url);
86
- return result;
87
- };
88
- const redirect = async (url) => {
89
- if (!isValidDomain(url))
90
- throw new Error("Redirect URL invalid domain");
91
- window.location.href = url;
92
- await new Promise(() => "");
93
- };
94
-
95
- var __defProp$4 = Object.defineProperty;
96
- var __defProps$4 = Object.defineProperties;
97
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
98
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
99
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
100
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
101
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
102
- var __spreadValues$4 = (a, b) => {
103
- for (var prop in b || (b = {}))
104
- if (__hasOwnProp$4.call(b, prop))
105
- __defNormalProp$4(a, prop, b[prop]);
106
- if (__getOwnPropSymbols$4)
107
- for (var prop of __getOwnPropSymbols$4(b)) {
108
- if (__propIsEnum$4.call(b, prop))
109
- __defNormalProp$4(a, prop, b[prop]);
110
- }
111
- return a;
112
- };
113
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
114
- var __publicField = (obj, key, value) => {
115
- __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
116
- return value;
117
- };
118
- const sessionKey = "session";
119
- const _SessionManager = class _SessionManager {
120
- constructor(config) {
121
- __publicField(this, "current");
122
- __publicField(this, "auth");
123
- __publicField(this, "config");
124
- __publicField(this, "changeListeners", []);
125
- __publicField(this, "logger");
126
- config.loginUrl || (config.loginUrl = location.origin);
127
- const redirectUrl = (config.redirectUrl || config.loginUrl).replace(/([^/])$/, "$1/");
128
- this.config = config;
129
- this.auth = new auth.AuthManager(__spreadProps$4(__spreadValues$4({}, config), {
130
- redirectUrl,
131
- storage: localStorage,
132
- sessionPersistence: {
133
- load: () => localStorage.getItem(sessionKey),
134
- save: (session) => localStorage.setItem(sessionKey, session)
135
- }
136
- }));
137
- this.logger = this.auth.config.logger;
138
- _SessionManager.instance = this;
139
- addEventListener("focus", () => this.validateSharedSession());
140
- }
141
- static create(config) {
142
- var _a;
143
- return (_a = _SessionManager.instance) != null ? _a : new _SessionManager(config);
144
- }
145
- setSession(session) {
146
- this.current = session;
147
- this.changeListeners.forEach((l) => l(session));
148
- if (session)
149
- this.setSessionCookie(session);
150
- }
151
- async restoreSession() {
152
- const session = await this.auth.restoreSession();
153
- this.logger.log("Validating shared session.");
154
- const sessionValid = await this.validateSharedSession(session);
155
- this.setSession(sessionValid ? session : void 0);
156
- }
157
- async validateSharedSession(session = this.current) {
158
- var _a;
159
- if (this.urlHasThirdPartyLoginData()) {
160
- this.logger.log("Session is invalid because there's another authentication in progress.");
161
- return false;
162
- }
163
- const sharedSessionCookie = sessionCookie.get();
164
- if (!sharedSessionCookie) {
165
- this.logger.log("Session is invalid because no shared session cookie was found, i.e, a logout was performed in another portal. Forcing log off.");
166
- session && await this.logout();
167
- return false;
168
- }
169
- const isDifferentSessionActive = sharedSessionCookie.sub != (session == null ? void 0 : session.getTokenData().sub);
170
- const isSharedSessionTypeBlocked = (_a = this.config.blockedAuthTypes) == null ? void 0 : _a.includes(sharedSessionCookie.type);
171
- if (isSharedSessionTypeBlocked) {
172
- this.logger.log("Session is invalid because shared sessions have been blocked in the SessionManager's configuration (blockedAuthTypes).");
173
- return false;
174
- } else if (isDifferentSessionActive || !session) {
175
- this.logger.log(
176
- isDifferentSessionActive ? "Session is invalid because a different session is already active." : "Session is invalid because it's undefined."
177
- );
178
- this.logger.log("Starting login with tenant from the session cookie.");
179
- await this.startThirdPartyLoginUsingTenant(sharedSessionCookie);
180
- return false;
181
- }
182
- return true;
183
- }
184
- hasSession() {
185
- return !!this.current && !this.current.isExpired();
186
- }
187
- getSession() {
188
- if (!this.hasSession()) {
189
- this.endSession();
190
- throw new Error("Session is not available, redirecting to login.");
191
- }
192
- return this.current;
193
- }
194
- async endSession(redirectToLogin = true) {
195
- this.current = void 0;
196
- localStorage.removeItem(sessionKey);
197
- sessionCookie.delete();
198
- if (redirectToLogin && this.config.loginUrl)
199
- await redirect(this.config.loginUrl);
200
- }
201
- async restartSession() {
202
- await this.logout({ endSession: false });
203
- this.current = void 0;
204
- localStorage.removeItem(sessionKey);
205
- await this.restoreSession();
206
- }
207
- async logout({ endSession } = { endSession: true }) {
208
- var _a;
209
- try {
210
- await ((_a = this.current) == null ? void 0 : _a.logout());
211
- } catch (error) {
212
- console.error(`Could not logout from IDM.
213
- ${error}`);
214
- }
215
- if (!endSession)
216
- return;
217
- await this.endSession();
218
- }
219
- async startThirdPartyLogin(data) {
220
- const params = new URLSearchParams(location.search);
221
- const authUrl = await this.auth.startThirdPartyLogin(data, {
222
- from: location.href,
223
- finalRedirect: params.get("finalRedirect")
224
- });
225
- await redirect(authUrl);
226
- }
227
- urlHasThirdPartyLoginData() {
228
- const url = new URL(location.toString());
229
- return url.searchParams.has("state") && !url.searchParams.has("error");
230
- }
231
- async startThirdPartyLoginUsingTenant(data) {
232
- const params = new URLSearchParams(location.search);
233
- const cookie = sessionCookie.get();
234
- if (!cookie || !cookie.tenant) {
235
- this.logger.log("Login out because no tenant information is available in the following data:", JSON.stringify(data));
236
- await this.logout();
237
- return;
238
- }
239
- const authUrl = await this.auth.getThirdPartyLoginFromTenant(
240
- data,
241
- cookie.tenant,
242
- {
243
- from: location.href,
244
- finalRedirect: params.get("finalRedirect")
245
- }
246
- );
247
- await redirect(authUrl);
248
- }
249
- async completeThirdPartyLogin() {
250
- var _a;
251
- const url = new URL(location.toString());
252
- if (url.searchParams.has("error")) {
253
- throw new Error(`Error while signing in: ${url.searchParams.get("error_description")}`);
254
- }
255
- const { session, data: { from, finalRedirect } } = await this.auth.completeThirdPartyLogin(location.search);
256
- this.setSession(session);
257
- history.replaceState(null, "", from || location.toString().replace(/\?.*$/, ""));
258
- this.sendLoginEventRd((_a = this.current) == null ? void 0 : _a.getTokenData());
259
- if (finalRedirect)
260
- await redirect(finalRedirect);
261
- }
262
- getEmailForLogin() {
263
- const session = sessionCookie.get();
264
- return (session == null ? void 0 : session.type) == "sso" ? session.email : void 0;
265
- }
266
- async switchAccount(accountId) {
267
- var _a;
268
- this.logger.log("Switching accounts", accountId, (_a = this.current) == null ? void 0 : _a.getTokenData().account_id_v2);
269
- try {
270
- this.current && await this.auth.switchAccount(accountId, this.current);
271
- } catch (error) {
272
- this.logger.error("Error while switching accounts", error);
273
- throw error;
274
- }
275
- this.setSession(this.current);
276
- }
277
- onChange(listener) {
278
- this.changeListeners.push(listener);
279
- return () => {
280
- const index = this.changeListeners.indexOf(listener);
281
- if (index != -1)
282
- this.changeListeners.splice(index, 1);
283
- };
284
- }
285
- setSessionCookie(session) {
286
- const { email, account_type, sub, tenant } = session.getTokenData();
287
- const { provider, refresh_expires_in } = session.getSessionData();
288
- if (!email || !sub || !tenant)
289
- return;
290
- const isFreemium = account_type == "FREEMIUM";
291
- const cookieAttributes = { "Max-Age": refresh_expires_in, path: "/" };
292
- if (isFreemium) {
293
- sessionCookie.set({ type: "idp", provider, sub, tenant }, cookieAttributes);
294
- } else {
295
- sessionCookie.set({ email, type: "sso", sub, tenant }, cookieAttributes);
296
- }
297
- }
298
- async sendLoginEventRd(tokenData) {
299
- if (!this.config.rdUrl)
300
- return;
301
- if (!tokenData) {
302
- console.error("Unable to trigger login hook. No sessionEmail or name identified.");
303
- return;
304
- }
305
- const { email, name, account_type, client_id, account_name, trial_account_status } = tokenData;
306
- const isLoginAI = client_id === "stackspot-portal-ai";
307
- const isLoginEDP = client_id === "stackspot-portal";
308
- if (!isLoginAI && !isLoginEDP && trial_account_status === "PENDING")
309
- return;
310
- const leadType = account_type === "FREEMIUM" ? "TRIAL" : "ENTERPRISE";
311
- const rdObject = {
312
- event_type: "CONVERSION",
313
- event_family: "CDP",
314
- payload: {
315
- email,
316
- name,
317
- conversion_identifier: isLoginAI ? "login_ai" : "login_edp",
318
- cf_leadtype: leadType,
319
- cf_account_name: leadType === "TRIAL" ? leadType : account_name
320
- }
321
- };
322
- const response = await fetch(this.config.rdUrl, {
323
- method: "POST",
324
- body: JSON.stringify(rdObject),
325
- headers: {
326
- "content-type": "application/json"
327
- }
328
- });
329
- const data = await response.json();
330
- if (!response.ok) {
331
- console.error("Error while sending event to RD Station", data);
332
- }
333
- }
334
- async getTrialEnabledProviders() {
335
- try {
336
- const response = await fetch(`${this.config.accountUrl}/v1/accounts/trial/sso`);
337
- const trialProviders = await response.json();
338
- if (!response.ok) {
339
- console.error("Error while fetching available login providers", trialProviders);
340
- }
341
- const providerKeys = Object.keys(trialProviders || {});
342
- return providerKeys.filter((key) => trialProviders[key] === true);
343
- } catch (error) {
344
- console.error("Error while fetching available login providers", error);
345
- return [];
346
- }
347
- }
348
- };
349
- __publicField(_SessionManager, "instance");
350
- let SessionManager = _SessionManager;
351
-
352
- function useSession() {
353
- const manager = SessionManager.instance;
354
- const [session, setSession] = react.useState((manager == null ? void 0 : manager.hasSession()) ? manager.getSession() : void 0);
355
- react.useEffect(() => {
356
- return manager == null ? void 0 : manager.onChange(setSession);
357
- }, []);
358
- return session;
359
- }
360
- const useTrialProviders = ({ enabled = true }) => {
361
- const [isLoadingTrialProviders, setIsLoadingTrialProviders] = react.useState(enabled);
362
- const [trialProviders, setTrialProviders] = react.useState([]);
363
- react.useEffect(() => {
364
- (async () => {
365
- if (!SessionManager.instance || !enabled)
366
- return;
367
- try {
368
- const providers = await SessionManager.instance.getTrialEnabledProviders();
369
- setTrialProviders(providers);
370
- setIsLoadingTrialProviders(false);
371
- } catch (error) {
372
- console.error(error);
373
- setIsLoadingTrialProviders(false);
374
- }
375
- })();
376
- }, [SessionManager.instance]);
377
- return [trialProviders, isLoadingTrialProviders];
378
- };
379
-
380
- var __defProp$3 = Object.defineProperty;
381
- var __defProps$3 = Object.defineProperties;
382
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
383
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
384
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
385
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
386
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
387
- var __spreadValues$3 = (a, b) => {
388
- for (var prop in b || (b = {}))
389
- if (__hasOwnProp$3.call(b, prop))
390
- __defNormalProp$3(a, prop, b[prop]);
391
- if (__getOwnPropSymbols$3)
392
- for (var prop of __getOwnPropSymbols$3(b)) {
393
- if (__propIsEnum$3.call(b, prop))
394
- __defNormalProp$3(a, prop, b[prop]);
395
- }
396
- return a;
397
- };
398
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
399
- const Github = react.forwardRef((props, ref) => /* @__PURE__ */ jsxRuntime.jsxs("svg", __spreadProps$3(__spreadValues$3({ ref }, props), { width: "25", height: "25", viewBox: "0 0 25 25", xmlns: "http://www.w3.org/2000/svg", children: [
400
- /* @__PURE__ */ jsxRuntime.jsxs("g", { "clip-path": "url(#clip0_1215_2072)", children: [
401
- /* @__PURE__ */ jsxRuntime.jsx("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M12.0011 4.38525C10.1019 4.38624 8.26498 5.05889 6.81881 6.28294C5.37263 7.50698 4.4115 9.20259 4.10726 11.0666C3.80302 12.9306 4.17551 14.8414 5.15814 16.4574C6.14077 18.0733 7.66946 19.2891 9.47085 19.8872C9.86827 19.961 10.018 19.7147 10.018 19.5053C10.018 19.2958 10.01 18.6886 10.0074 18.0247C7.78183 18.5055 7.31155 17.0856 7.31155 17.0856C6.94858 16.1635 6.42399 15.9212 6.42399 15.9212C5.69804 15.4286 6.4783 15.4378 6.4783 15.4378C7.28241 15.4944 7.705 16.2584 7.705 16.2584C8.4177 17.4741 9.57683 17.1225 10.0325 16.917C10.1041 16.402 10.312 16.0516 10.5412 15.8527C8.76345 15.6525 6.89559 14.9702 6.89559 11.9222C6.88457 11.1317 7.17958 10.3673 7.71957 9.78704C7.63744 9.58683 7.36321 8.77808 7.79772 7.67954C7.79772 7.67954 8.46936 7.46616 9.99809 8.49488C11.3093 8.13834 12.6928 8.13834 14.0041 8.49488C15.5315 7.46616 16.2018 7.67954 16.2018 7.67954C16.6376 8.77544 16.3634 9.58419 16.2813 9.78704C16.823 10.3674 17.1186 11.1332 17.1066 11.9248C17.1066 14.9794 15.2347 15.6525 13.4543 15.8487C13.7404 16.0964 13.9961 16.5798 13.9961 17.3227C13.9961 18.387 13.9868 19.2431 13.9868 19.5053C13.9868 19.7173 14.1312 19.9649 14.5366 19.8872C16.3382 19.289 17.867 18.0731 18.8496 16.4568C19.8323 14.8406 20.2046 12.9295 19.9 11.0653C19.5954 9.20112 18.6338 7.50549 17.1871 6.28166C15.7405 5.05782 13.9031 4.38561 12.0037 4.38525H12.0011Z", fill: "white" }),
402
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M9.35091 17.3684C9.35091 17.4329 9.27673 17.4882 9.18135 17.4896C9.08597 17.4909 9.00781 17.4382 9.00781 17.3736C9.00781 17.3091 9.08199 17.2538 9.17737 17.2525C9.27275 17.2511 9.35091 17.3025 9.35091 17.3684Z", fill: "white" }),
403
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M9.96094 17.2672C9.97286 17.3317 9.90662 17.3989 9.81124 17.4147C9.71586 17.4305 9.63241 17.3923 9.62048 17.3291C9.60856 17.2659 9.67745 17.1974 9.77018 17.1803C9.86291 17.1631 9.94902 17.2027 9.96094 17.2672Z", fill: "white" }),
404
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M8.6968 17.324C8.67693 17.3859 8.58685 17.4136 8.49676 17.3872C8.40668 17.3609 8.34707 17.2871 8.36429 17.2239C8.38151 17.1607 8.47292 17.1317 8.56433 17.1607C8.65573 17.1897 8.71402 17.2595 8.6968 17.324Z", fill: "white" }),
405
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M8.09774 17.0658C8.05402 17.1145 7.96527 17.1013 7.89241 17.0355C7.81955 16.9696 7.80232 16.88 7.84604 16.8326C7.88975 16.7852 7.97851 16.7984 8.05402 16.8629C8.12953 16.9274 8.1441 17.0183 8.09774 17.0658V17.0658Z", fill: "white" }),
406
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M7.6686 16.6231C7.61959 16.6574 7.53612 16.6231 7.48976 16.5546C7.47694 16.5423 7.46674 16.5276 7.45978 16.5113C7.45281 16.495 7.44922 16.4775 7.44922 16.4598C7.44922 16.4421 7.45281 16.4246 7.45978 16.4083C7.46674 16.392 7.47694 16.3772 7.48976 16.3649C7.53877 16.332 7.62224 16.3649 7.6686 16.4321C7.71497 16.4993 7.71629 16.5889 7.6686 16.6231V16.6231Z", fill: "white" }),
407
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M7.3535 16.1662C7.32607 16.1799 7.29468 16.1838 7.26472 16.177C7.23475 16.1703 7.20807 16.1534 7.18924 16.1293C7.13757 16.074 7.12697 15.9976 7.16671 15.9633C7.20645 15.9291 7.27799 15.9449 7.32966 16.0002C7.38132 16.0555 7.39324 16.1319 7.3535 16.1662Z", fill: "white" }),
408
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M7.02905 15.8062C7.01183 15.8457 6.94825 15.8576 6.89658 15.8299C6.84492 15.8022 6.8065 15.7509 6.82505 15.71C6.8436 15.6692 6.90586 15.6587 6.95752 15.6863C7.00919 15.714 7.04893 15.7667 7.02905 15.8062Z", fill: "white" })
409
- ] }),
410
- /* @__PURE__ */ jsxRuntime.jsx("defs", { children: /* @__PURE__ */ jsxRuntime.jsx("clipPath", { id: "clip0_1215_2072", children: /* @__PURE__ */ jsxRuntime.jsx("rect", { width: "16", height: "16", fill: "white", transform: "translate(4 4.05176)" }) }) })
411
- ] })));
412
-
413
- var __defProp$2 = Object.defineProperty;
414
- var __defProps$2 = Object.defineProperties;
415
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
416
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
417
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
418
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
419
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
420
- var __spreadValues$2 = (a, b) => {
421
- for (var prop in b || (b = {}))
422
- if (__hasOwnProp$2.call(b, prop))
423
- __defNormalProp$2(a, prop, b[prop]);
424
- if (__getOwnPropSymbols$2)
425
- for (var prop of __getOwnPropSymbols$2(b)) {
426
- if (__propIsEnum$2.call(b, prop))
427
- __defNormalProp$2(a, prop, b[prop]);
428
- }
429
- return a;
430
- };
431
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
432
- const Google = react.forwardRef((props, ref) => /* @__PURE__ */ jsxRuntime.jsxs("svg", __spreadProps$2(__spreadValues$2({ ref }, props), { width: "25", height: "25", viewBox: "0 0 25 25", xmlns: "http://www.w3.org/2000/svg", children: [
433
- /* @__PURE__ */ jsxRuntime.jsxs("g", { "clip-path": "url(#clip0_1215_2403)", children: [
434
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M20.3442 12.2359C20.3442 11.6921 20.3001 11.1454 20.206 10.6104H12.6602V13.691H16.9813C16.802 14.6846 16.2258 15.5635 15.3822 16.122V18.1209H17.9602C19.4741 16.7276 20.3442 14.6699 20.3442 12.2359Z", fill: "#4285F4" }),
435
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12.6607 20.0525C14.8184 20.0525 16.6379 19.344 17.9637 18.1212L15.3857 16.1223C14.6684 16.6103 13.7425 16.8866 12.6637 16.8866C10.5766 16.8866 8.80696 15.4785 8.17202 13.5854H5.51172V15.6461C6.86979 18.3475 9.63592 20.0525 12.6607 20.0525V20.0525Z", fill: "#34A853" }),
436
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M8.16852 13.5856C7.83341 12.592 7.83341 11.5161 8.16852 10.5225V8.46191H5.51116C4.37649 10.7224 4.37649 13.3857 5.51116 15.6462L8.16852 13.5856V13.5856Z", fill: "#FBBC04" }),
437
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12.6607 7.2182C13.8013 7.20056 14.9036 7.62974 15.7296 8.41754L18.0136 6.1335C16.5674 4.77543 14.6479 4.02878 12.6607 4.0523C9.63592 4.0523 6.86979 5.75724 5.51172 8.46163L8.16908 10.5223C8.80108 8.62625 10.5736 7.2182 12.6607 7.2182V7.2182Z", fill: "#EA4335" })
438
- ] }),
439
- /* @__PURE__ */ jsxRuntime.jsx("defs", { children: /* @__PURE__ */ jsxRuntime.jsx("clipPath", { id: "clip0_1215_2403", children: /* @__PURE__ */ jsxRuntime.jsx("rect", { width: "16", height: "16", fill: "white", transform: "translate(4.5 4.05176)" }) }) })
440
- ] })));
441
-
442
- var __defProp$1 = Object.defineProperty;
443
- var __defProps$1 = Object.defineProperties;
444
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
445
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
446
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
447
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
448
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
449
- var __spreadValues$1 = (a, b) => {
450
- for (var prop in b || (b = {}))
451
- if (__hasOwnProp$1.call(b, prop))
452
- __defNormalProp$1(a, prop, b[prop]);
453
- if (__getOwnPropSymbols$1)
454
- for (var prop of __getOwnPropSymbols$1(b)) {
455
- if (__propIsEnum$1.call(b, prop))
456
- __defNormalProp$1(a, prop, b[prop]);
457
- }
458
- return a;
459
- };
460
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
461
- const Microsoft = react.forwardRef((props, ref) => /* @__PURE__ */ jsxRuntime.jsxs("svg", __spreadProps$1(__spreadValues$1({ ref }, props), { width: "25", height: "25", viewBox: "0 0 25 25", xmlns: "http://www.w3.org/2000/svg", children: [
462
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M5.19531 4.74707H12.1518V11.7036H5.19531V4.74707Z", fill: "#F35325" }),
463
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12.8477 4.74707H19.8042V11.7036H12.8477V4.74707Z", fill: "#81BC06" }),
464
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M5.19531 12.3994H12.1518V19.3559H5.19531V12.3994Z", fill: "#05A6F0" }),
465
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12.8477 12.3994H19.8042V19.3559H12.8477V12.3994Z", fill: "#FFBA08" })
466
- ] })));
467
-
468
- const providerIcons = {
469
- github: /* @__PURE__ */ jsxRuntime.jsx(Github, {}),
470
- google: /* @__PURE__ */ jsxRuntime.jsx(Google, {}),
471
- microsoft: /* @__PURE__ */ jsxRuntime.jsx(Microsoft, {})
472
- };
473
- const ButtonProvider = ({ provider, login, loading, disabled }) => {
474
- const t = useTranslation();
475
- return /* @__PURE__ */ jsxRuntime.jsx(core.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(
476
- core.Button,
477
- {
478
- colorScheme: "light",
479
- type: "button",
480
- size: "md",
481
- sx: { width: "100%" },
482
- onClick: () => login("idp", provider),
483
- disabled: loading || disabled,
484
- children: loading ? /* @__PURE__ */ jsxRuntime.jsx(ui.LoadingCircular, {}) : /* @__PURE__ */ jsxRuntime.jsxs(core.Flex, { alignItems: "center", style: { gap: "4px" }, children: [
485
- providerIcons[provider],
486
- portalTranslate.interpolate(t.loginWith, lodash.capitalize(provider))
487
- ] })
488
- }
489
- ) });
490
- };
491
- function hasTouchSupport() {
492
- return "ontouchstart" in window || navigator.maxTouchPoints > 0;
493
- }
494
- function isMobileUserAgent() {
495
- return /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
496
- }
497
- function isMobileWithDesktopView() {
498
- return !isMobileUserAgent() && hasTouchSupport();
499
- }
500
- const IDPLogin = ({ trialProviders, loading, loginProvider, onSubmit, onChangeMode }) => {
501
- const t = useTranslation();
502
- const showErrorMessage = isMobileWithDesktopView();
503
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
504
- showErrorMessage && /* @__PURE__ */ jsxRuntime.jsxs(core.Flex, { bg: "warning", p: 4, role: "alert", flexWrap: "nowrap", children: [
505
- /* @__PURE__ */ jsxRuntime.jsx(core.IconBox, { colorIcon: "warning.contrastText", children: /* @__PURE__ */ jsxRuntime.jsx(icons.ExclamationTriangle, {}) }),
506
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "body2", ml: 2, colorScheme: "warning.contrastText", children: t.errorMobileDesktop })
507
- ] }),
508
- /* @__PURE__ */ jsxRuntime.jsx(core.Flex, { flexDirection: "column", gap: true, children: trialProviders == null ? void 0 : trialProviders.map((provider) => /* @__PURE__ */ jsxRuntime.jsx(
509
- ButtonProvider,
510
- {
511
- provider,
512
- login: onSubmit,
513
- loading: loading && loginProvider === provider,
514
- disabled: loading
515
- },
516
- provider
517
- )) }),
518
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "separator", children: /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "microtext1", colorScheme: "light.700", children: t.or }) }),
519
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { colorScheme: "light.700", align: "center", children: t.corporateLoginTitle }),
520
- /* @__PURE__ */ jsxRuntime.jsx(core.Button, { size: "md", disabled: loading, colorScheme: "light", onClick: () => onChangeMode("sso"), children: t.corporateLoginButton })
521
- ] });
522
- };
523
-
524
- const lastLoginTypeKey = "lastLoginType";
525
- const fallbackKeys = ["guided-tour", "@stack-spot/opa:user", "CHAT_AGENTS", "RATED_US_IN"];
526
- function getLastLoginType() {
527
- const type = localStorage.getItem(lastLoginTypeKey);
528
- if (type === "idp" || type === "sso")
529
- return type;
530
- if (portalComponents.getCookie("stk-session.stackspot.com"))
531
- return "sso";
532
- for (const key of fallbackKeys) {
533
- if (localStorage.getItem(key))
534
- return "sso";
535
- }
536
- return "idp";
537
- }
538
- function setLastLoginType(type) {
539
- localStorage.setItem(lastLoginTypeKey, type);
540
- }
541
-
542
- const SSOLogin = ({ value, onChange, loading, disabled, hasProvider, onChangeMode, idpLoginEnabled }) => {
543
- const t = useTranslation();
544
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
545
- /* @__PURE__ */ jsxRuntime.jsxs(core.Flex, { flexDirection: "column", style: { gap: "4px", marginTop: "4px" }, children: [
546
- /* @__PURE__ */ jsxRuntime.jsx(core.Label, { htmlFor: "email", children: t.label }),
547
- /* @__PURE__ */ jsxRuntime.jsx(core.Input, { id: "email", type: "email", name: "email", value, onChange: (e) => onChange(e.target.value), placeholder: t.placeholder }),
548
- /* @__PURE__ */ jsxRuntime.jsx(core.Button, { colorScheme: "primary", size: "md", style: { marginTop: "12px" }, disabled: disabled || loading, children: loading && !hasProvider ? /* @__PURE__ */ jsxRuntime.jsx(ui.LoadingCircular, {}) : /* @__PURE__ */ jsxRuntime.jsx(core.Text, { children: t.continue }) })
549
- ] }),
550
- idpLoginEnabled && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
551
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "separator", children: /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "microtext1", colorScheme: "light.700", children: t.or }) }),
552
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { colorScheme: "light.700", align: "center", children: t.socialLoginTitle }),
553
- /* @__PURE__ */ jsxRuntime.jsx(core.Button, { size: "md", disabled: loading, colorScheme: "light", onClick: () => onChangeMode("idp"), children: t.socialLogin })
554
- ] })
555
- ] });
556
- };
557
9
 
558
- const LoginBox = styledComponents.styled.form`
559
- display: flex;
560
- flex-direction: column;
561
- justify-content: center;
562
- gap: 24px;
563
-
564
- header {
565
- display: flex;
566
- flex-direction: column;
567
- align-items: center;
568
- gap: 24px;
569
- }
570
-
571
- .separator {
572
- padding: 0 8px;
573
- display: flex;
574
- flex-direction: row;
575
- align-items: center;
576
- justify-content: center;
577
- gap: 8px;
578
- margin: 0;
579
-
580
- &:before, &:after {
581
- content: '';
582
- height: 1px;
583
- flex: 1;
584
- background-color: ${portalTheme.theme.color.light["500"]};
585
- }
586
- }
587
-
588
- .error {
589
- color: ${portalTheme.theme.color.danger["500"]};
590
- line-height: 1.5rem;
591
- }
592
- `;
593
- const EmailNotAllowed = () => {
594
- const t = useTranslation();
595
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(core.Flex, { justifyContent: "center", children: [
596
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "body2", children: t.emailNotAllowedTitle }),
597
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "body2", colorScheme: "light.700", children: t.emailNotAllowedSubtitle })
598
- ] }) });
599
- };
600
- const stylesBanner = {
601
- position: "fixed",
602
- top: 0,
603
- left: 0,
604
- width: "100%"
605
- };
606
- const Login = ({ onSubmit, initialValue = "", showLogin = true, welcomeText, removeLoadingOnSuccess, className, style, banner, loginTypes = ["idp", "sso"] }) => {
607
- const t = useTranslation();
608
- const [trialProviders, isLoadingTrialProviders] = useTrialProviders({ enabled: loginTypes.includes("idp") });
609
- const searchParams = new URLSearchParams(location.search);
610
- const [error, setError] = react.useState(searchParams.get("error_description") || searchParams.get("error") || "");
611
- const [errorCode] = react.useState(searchParams.get("error_code") || "");
612
- const [loading, setLoading] = react.useState(false);
613
- const providerQueryParam = searchParams.get("provider");
614
- const [loginProvider, setLoginProvider] = react.useState();
615
- const [email, setEmail] = react.useState(initialValue || searchParams.get("email") || "");
616
- const disabled = !email.match(/\w+@\w+/);
617
- const idpLoginEnabled = loginTypes.includes("idp") && !!(trialProviders == null ? void 0 : trialProviders.length);
618
- const [mode, setMode] = react.useState();
619
- react.useEffect(() => {
620
- setMode(idpLoginEnabled ? getLastLoginType() : "sso");
621
- }, [idpLoginEnabled]);
622
- react.useEffect(() => {
623
- if (!providerQueryParam)
624
- return;
625
- if (providerQueryParam === "email")
626
- login("sso");
627
- else if (trialProviders == null ? void 0 : trialProviders.includes(providerQueryParam))
628
- login("idp", providerQueryParam);
629
- }, [trialProviders, isLoadingTrialProviders]);
630
- async function login(type, provider) {
631
- setError("");
632
- setLoading(true);
633
- provider !== loginProvider && setLoginProvider(provider);
634
- try {
635
- const data = type === "idp" && !!provider ? { type: "idp", provider: `external-idp:${provider}` } : { type: "sso", email };
636
- setLastLoginType(data.type);
637
- await onSubmit(data);
638
- if (removeLoadingOnSuccess)
639
- setLoading(false);
640
- } catch (error2) {
641
- setLoading(false);
642
- setLoginProvider(void 0);
643
- if (error2 instanceof auth.AuthMethodUnavailable) {
644
- setError(t.emailNotFoundError);
645
- } else {
646
- setError(error2.message || error2.toString());
647
- }
648
- }
649
- }
650
- react.useEffect(() => {
651
- const meta = document.createElement("meta");
652
- meta.name = "adopt-website-id";
653
- meta.content = "a32fe656-2333-4dc5-8039-dddac6464587";
654
- document.head.appendChild(meta);
655
- const script = document.createElement("script");
656
- script.src = "//tag.goadopt.io/injector.js?website_code=a32fe656-2333-4dc5-8039-dddac6464587";
657
- script.className = "adopt-injector";
658
- script.async = true;
659
- document.body.appendChild(script);
660
- return () => {
661
- document.head.removeChild(meta);
662
- document.body.removeChild(script);
663
- };
664
- }, []);
665
- function submitForm(e) {
666
- e.preventDefault();
667
- if (disabled)
668
- return;
669
- login("sso");
670
- }
671
- if (isLoadingTrialProviders || !mode) {
672
- return /* @__PURE__ */ jsxRuntime.jsxs(core.Flex, { alignContent: "center", justifyContent: "center", my: 5, children: [
673
- /* @__PURE__ */ jsxRuntime.jsx(ui.LoadingCircular, {}),
674
- " "
675
- ] });
676
- }
677
- const loginWithSocialAccount = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
678
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: t.loginWithSocialAccount1 }),
679
- /* @__PURE__ */ jsxRuntime.jsx("span", { style: { fontWeight: "bold" }, children: t.loginWithSocialAccount2 }),
680
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: t.loginWithSocialAccount3 })
681
- ] });
682
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
683
- banner && /* @__PURE__ */ jsxRuntime.jsx(core.Box, { style: stylesBanner, children: /* @__PURE__ */ jsxRuntime.jsx(portalComponents.BannerWarning, { showCloseButton: false, children: banner }) }),
684
- showLogin ? /* @__PURE__ */ jsxRuntime.jsxs(LoginBox, { onSubmit: submitForm, className, style, children: [
685
- /* @__PURE__ */ jsxRuntime.jsxs("header", { children: [
686
- /* @__PURE__ */ jsxRuntime.jsx(svg.MiniLogo, {}),
687
- /* @__PURE__ */ jsxRuntime.jsxs(core.Flex, { flexDirection: "column", alignItems: "center", children: [
688
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "body1", weight: "medium", children: welcomeText || t.welcome }),
689
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "body2", colorScheme: "light.700", align: "center", children: mode === "idp" ? loginWithSocialAccount : t.loginWithEmail })
690
- ] })
691
- ] }),
692
- errorCode && errorCode === "EMAIL_IS_NOT_ALLOWED" && /* @__PURE__ */ jsxRuntime.jsx(EmailNotAllowed, {}),
693
- mode === "sso" ? /* @__PURE__ */ jsxRuntime.jsx(
694
- SSOLogin,
695
- {
696
- disabled,
697
- loading,
698
- hasProvider: !loginProvider,
699
- value: email,
700
- onChange: setEmail,
701
- onChangeMode: setMode,
702
- idpLoginEnabled
703
- }
704
- ) : /* @__PURE__ */ jsxRuntime.jsx(
705
- IDPLogin,
706
- {
707
- loading,
708
- loginProvider,
709
- onSubmit: login,
710
- trialProviders,
711
- onChangeMode: setMode
712
- }
713
- ),
714
- error && /* @__PURE__ */ jsxRuntime.jsx(core.Text, { className: "error", align: "center", children: error })
715
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(core.Flex, { flexDirection: "column", alignItems: "center", children: [
716
- /* @__PURE__ */ jsxRuntime.jsx(svg.MiniLogo, {}),
717
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { appearance: "body1", weight: "medium", children: welcomeText || t.welcome }),
718
- /* @__PURE__ */ jsxRuntime.jsx(core.Text, { mt: 4, children: t.loginTemporarilyUnavailable })
719
- ] })
720
- ] });
721
- };
722
-
723
- var __defProp = Object.defineProperty;
724
- var __defProps = Object.defineProperties;
725
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
726
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
727
- var __hasOwnProp = Object.prototype.hasOwnProperty;
728
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
729
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
730
- var __spreadValues = (a, b) => {
731
- for (var prop in b || (b = {}))
732
- if (__hasOwnProp.call(b, prop))
733
- __defNormalProp(a, prop, b[prop]);
734
- if (__getOwnPropSymbols)
735
- for (var prop of __getOwnPropSymbols(b)) {
736
- if (__propIsEnum.call(b, prop))
737
- __defNormalProp(a, prop, b[prop]);
738
- }
739
- return a;
740
- };
741
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
742
- const Authenticated = ({ children, onLogin, onSession, customLoginProps, sessionManager, onChangeStatus }) => {
743
- const [authStatus, setAuthStatus] = react.useState("unknown");
744
- const language = portalTranslate.useLanguage(portalTranslate.ptEn);
745
- sessionManager != null ? sessionManager : sessionManager = SessionManager.instance;
746
- if (!sessionManager)
747
- throw new Error("Please, provide a sessionManager");
748
- portalComponents.useEffectOnce(() => {
749
- async function checkAuth() {
750
- if (!sessionManager)
751
- throw new Error("Please, provide a sessionManager");
752
- await sessionManager.restoreSession();
753
- if (sessionManager.urlHasThirdPartyLoginData()) {
754
- await sessionManager.completeThirdPartyLogin();
755
- onLogin == null ? void 0 : onLogin();
756
- }
757
- if (sessionManager.hasSession()) {
758
- setAuthStatus("authenticated");
759
- onSession == null ? void 0 : onSession();
760
- onChangeStatus == null ? void 0 : onChangeStatus("authenticated");
761
- } else {
762
- setAuthStatus("unauthenticated");
763
- onChangeStatus == null ? void 0 : onChangeStatus("unauthenticated");
764
- }
765
- }
766
- checkAuth();
767
- });
768
- if (authStatus === "unknown")
769
- return null;
770
- if (authStatus === "authenticated")
771
- return children;
772
- return /* @__PURE__ */ jsxRuntime.jsx(portalTheme.CSSToCitricAdapter, { children: /* @__PURE__ */ jsxRuntime.jsx(core.Flex, { justifyContent: "center", alignItems: "center", flex: 1, style: { height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
773
- Login,
774
- __spreadValues({
775
- style: { width: "360px" },
776
- onSubmit: (data) => sessionManager.startThirdPartyLogin(__spreadProps(__spreadValues({}, data), { locale: language })),
777
- initialValue: sessionManager.getEmailForLogin()
778
- }, customLoginProps || {})
779
- ) }) });
780
- };
781
-
782
- exports.Authenticated = Authenticated;
783
- exports.Login = Login;
784
- exports.SessionManager = SessionManager;
785
- exports.useSession = useSession;
10
+ Object.defineProperty(exports, 'Authenticated', {
11
+ enumerable: true,
12
+ get: function () { return Authenticated_tsx.Authenticated; }
13
+ });
14
+ Object.defineProperty(exports, 'useSession', {
15
+ enumerable: true,
16
+ get: function () { return hooks_ts.useSession; }
17
+ });
18
+ Object.defineProperty(exports, 'Login', {
19
+ enumerable: true,
20
+ get: function () { return Login_tsx.Login; }
21
+ });
22
+ Object.defineProperty(exports, 'SessionManager', {
23
+ enumerable: true,
24
+ get: function () { return SessionManager_ts.SessionManager; }
25
+ });
786
26
  //# sourceMappingURL=index.js.map