@griddo/ax 12.14.3 → 12.15.0-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.
Files changed (53) hide show
  1. package/README.md +1 -0
  2. package/package.json +7 -4
  3. package/src/GlobalStore.tsx +32 -25
  4. package/src/__tests__/GlobalStore.session.test.tsx +98 -0
  5. package/src/__tests__/api/global.test.ts +64 -0
  6. package/src/__tests__/api/session.test.ts +311 -0
  7. package/src/__tests__/api/sessionRenewal.test.ts +705 -0
  8. package/src/__tests__/api/utils.test.ts +373 -0
  9. package/src/__tests__/components/Fields/FileField/FileField.test.tsx +33 -6
  10. package/src/__tests__/components/FieldsBehavior/FieldsBehavior.test.tsx +5 -3
  11. package/src/__tests__/components/Login/LoginGriddoId.test.tsx +195 -0
  12. package/src/__tests__/components/SsoDenied/SsoDenied.test.tsx +86 -0
  13. package/src/__tests__/containers/App/reducer.griddoId.test.ts +18 -0
  14. package/src/__tests__/containers/App/session.test.ts +397 -0
  15. package/src/__tests__/helpers/griddoId.test.ts +56 -0
  16. package/src/__tests__/locales/loginLocale.test.ts +52 -0
  17. package/src/__tests__/modules/App/Routing/NavMenu.test.tsx +54 -0
  18. package/src/__tests__/modules/Login/Login.test.tsx +151 -0
  19. package/src/__tests__/modules/Redirects/Redirects/Redirects.create.test.tsx +19 -0
  20. package/src/__tests__/modules/Redirects/Redirects/Redirects.edit.test.tsx +19 -0
  21. package/src/__tests__/modules/Redirects/Redirects/Redirects.filter.test.tsx +19 -0
  22. package/src/__tests__/modules/SsoDenied/SsoDenied.test.tsx +30 -0
  23. package/src/__tests__/routes/publicRoutes.test.ts +36 -0
  24. package/src/api/global.tsx +24 -1
  25. package/src/api/session.tsx +197 -0
  26. package/src/api/sessionRenewal.tsx +114 -0
  27. package/src/api/utils.tsx +22 -12
  28. package/src/{helpers/categoryColumns.tsx → components/CategoryCell/buildCategoryColumns.tsx} +3 -2
  29. package/src/{helpers/fields.tsx → components/FieldsBehavior/getFieldByPath.tsx} +1 -1
  30. package/src/components/FieldsBehavior/index.tsx +3 -1
  31. package/src/components/Login/LoginForm/index.tsx +7 -2
  32. package/src/components/Login/LoginGriddoId/index.tsx +46 -0
  33. package/src/components/Login/LoginGriddoId/style.tsx +35 -0
  34. package/src/components/Login/index.tsx +13 -1
  35. package/src/components/SsoDenied/index.tsx +46 -0
  36. package/src/components/SsoDenied/style.tsx +37 -0
  37. package/src/components/index.tsx +11 -7
  38. package/src/containers/App/actions.tsx +110 -5
  39. package/src/containers/App/interfaces.tsx +2 -2
  40. package/src/containers/App/reducer.tsx +9 -0
  41. package/src/containers/Users/actions.tsx +28 -24
  42. package/src/helpers/griddoId.ts +28 -0
  43. package/src/helpers/index.tsx +4 -5
  44. package/src/locales/en-US.ts +7 -0
  45. package/src/locales/es-ES.ts +7 -0
  46. package/src/locales/index.ts +10 -0
  47. package/src/modules/App/Routing/NavMenu/index.tsx +4 -4
  48. package/src/modules/Content/PageItem/index.tsx +6 -8
  49. package/src/modules/Login/index.tsx +12 -2
  50. package/src/modules/SsoDenied/index.tsx +9 -0
  51. package/src/modules/StructuredData/StructuredDataList/GlobalPageItem/index.tsx +6 -8
  52. package/src/modules/StructuredData/StructuredDataList/StructuredDataItem/index.tsx +9 -11
  53. package/src/routes/publicRoutes.tsx +3 -0
package/src/api/utils.tsx CHANGED
@@ -1,6 +1,9 @@
1
1
  import axios, { type AxiosRequestConfig, type AxiosResponse, type Method, type ResponseType } from "axios";
2
+
2
3
  import { SET_ERROR } from "./../containers/App/constants";
3
4
  import { getStore } from "../storeRegistry";
5
+ import { getSession } from "./session";
6
+ import { requestWithRenewal } from "./sessionRenewal";
4
7
 
5
8
  export interface IServiceConfig {
6
9
  host: string | undefined;
@@ -11,19 +14,24 @@ export interface IServiceConfig {
11
14
  dynamicUrl?: string;
12
15
  responseType?: ResponseType;
13
16
  onUploadProgress?: any;
17
+ /**
18
+ * El 401 de este servicio es un error normal: no renueva ni cierra la sesión (login, SSO,
19
+ * `password/init`, logout y la propia renovación).
20
+ */
21
+ skipAuthRenewal?: boolean;
14
22
  }
15
23
 
16
24
  const getToken = (): Record<string, unknown> | null => {
17
- const app = localStorage.getItem("persist:app");
18
- if (!app) return null;
19
-
20
- let { token } = JSON.parse(app);
21
- token = JSON.parse(token);
22
- const authorization = { Authorization: `bearer ${token}` };
25
+ const session = getSession();
26
+ if (!session) return null;
23
27
 
24
- return authorization;
28
+ return { Authorization: `bearer ${session.token}` };
25
29
  };
26
30
 
31
+ /** `axios(config)`, con renovación de sesión ante 401 salvo en los servicios excluidos. */
32
+ const send = (serviceConfig: IServiceConfig, config: AxiosRequestConfig) =>
33
+ serviceConfig.skipAuthRenewal ? axios(config) : requestWithRenewal(config);
34
+
27
35
  const getLang = (): Record<string, unknown> => {
28
36
  const store = getStore();
29
37
  if (store) return { lang: store.getState()?.app?.lang?.id ?? null };
@@ -114,7 +122,7 @@ export const sendInitialRequest = async (
114
122
  method,
115
123
  headers: {
116
124
  ...configHeaders,
117
- Authorization: "bearer " + token,
125
+ Authorization: `bearer ${token}`,
118
126
  },
119
127
  };
120
128
 
@@ -122,10 +130,10 @@ export const sendInitialRequest = async (
122
130
  const isPost = method === "PUT" || method === "POST";
123
131
  if (isPost) {
124
132
  const postConfig = { ...config, data };
125
- const postResponse = await axios(postConfig);
133
+ const postResponse = await send(serviceConfig, postConfig);
126
134
  return postResponse;
127
135
  }
128
- const response = await axios(config);
136
+ const response = await send(serviceConfig, config);
129
137
  return response;
130
138
  } catch (e) {
131
139
  if (e.message !== "Network Error") {
@@ -169,7 +177,7 @@ export const sendRequest = async (
169
177
  // requestCache.save(requestConfig, response);
170
178
 
171
179
  // return response;
172
- return await axios(requestConfig);
180
+ return await send(serviceConfig, requestConfig);
173
181
  } catch (e) {
174
182
  if (e.message !== "Network Error") {
175
183
  return (
@@ -202,7 +210,7 @@ export const sendUploadRequest = async (
202
210
  };
203
211
  }
204
212
 
205
- return await axios(requestConfig);
213
+ return await send(serviceConfig, requestConfig);
206
214
  } catch (e) {
207
215
  if (e.message !== "Network Error") {
208
216
  return (
@@ -235,6 +243,8 @@ export function handleResponse(
235
243
  }
236
244
  }
237
245
 
246
+ export { getToken };
247
+
238
248
  export default {
239
249
  getToken,
240
250
  getHeaders,
@@ -1,11 +1,12 @@
1
1
  import React from "react";
2
2
 
3
- import { CategoryCell } from "@ax/components";
4
- import { Cell } from "@ax/components/TableList/TableItem/style";
5
3
  import type { ISchemaField } from "@ax/types";
6
4
 
7
5
  import styled from "styled-components";
8
6
 
7
+ import { Cell } from "../TableList/TableItem/style";
8
+ import CategoryCell from "./index";
9
+
9
10
  const ColumnCell = styled(Cell)`
10
11
  flex: 0 0 215px;
11
12
  position: relative;
@@ -1,4 +1,4 @@
1
- import * as components from "@ax/components/Fields";
1
+ import * as components from "../Fields";
2
2
 
3
3
  const getFieldByPath = (name: string): ((props: any) => JSX.Element) => (components as Record<string, any>)[name];
4
4
 
@@ -2,9 +2,11 @@ import { useCallback, useEffect, useState } from "react";
2
2
 
3
3
  import { IconAction, Tooltip } from "@ax/components";
4
4
  import { getValidity } from "@ax/forms";
5
- import { getFieldByPath, isEmptyContainer, slugify } from "@ax/helpers";
5
+ import { isEmptyContainer, slugify } from "@ax/helpers";
6
6
  import type { IErrorItem } from "@ax/types";
7
7
 
8
+ import { getFieldByPath } from "./getFieldByPath";
9
+
8
10
  import * as S from "./style";
9
11
 
10
12
  const FieldsBehavior = (props: IFieldsBehaviorProps): JSX.Element => {
@@ -1,8 +1,9 @@
1
- import { useState, useEffect } from "react";
1
+ import { type ReactNode, useEffect, useState } from "react";
2
2
 
3
+ import { Button, ErrorToast, FieldsBehavior } from "@ax/components";
3
4
  import type { IGlobalSettings } from "@ax/containers/App/reducer";
4
5
  import { useModal } from "@ax/hooks";
5
- import { Button, FieldsBehavior, ErrorToast } from "@ax/components";
6
+
6
7
  import RecoveryModal from "./RecoveryModal";
7
8
 
8
9
  import * as S from "./style";
@@ -24,6 +25,7 @@ const LoginForm = (props: ILoginFormProps): JSX.Element => {
24
25
  settings,
25
26
  rememberMe,
26
27
  handleRememberMe,
28
+ footer,
27
29
  } = props;
28
30
 
29
31
  const [viewPass, setViewPass] = useState(false);
@@ -114,6 +116,7 @@ const LoginForm = (props: ILoginFormProps): JSX.Element => {
114
116
  </Button>
115
117
  <RecoveryModal isOpen={isOpen} toggleModal={toggleModal} />
116
118
  </S.Form>
119
+ {footer}
117
120
  </S.Main>
118
121
  <S.Secuoyas>
119
122
  Made with care at{" "}
@@ -135,6 +138,8 @@ export interface ILoginFormProps {
135
138
  settings: IGlobalSettings;
136
139
  rememberMe: boolean;
137
140
  handleRememberMe: () => void;
141
+ /** Alternativas de acceso bajo el formulario (p. ej. SSO de Griddo). */
142
+ footer?: ReactNode;
138
143
  }
139
144
 
140
145
  export default LoginForm;
@@ -0,0 +1,46 @@
1
+ import { useRef } from "react";
2
+
3
+ import { getLoginLocale } from "@ax/locales";
4
+
5
+ import * as S from "./style";
6
+
7
+ /**
8
+ * «Entrar con Griddo» (`auth.griddo.io`) con su separador «o», bajo el formulario de usuario y contraseña. Solo existe
9
+ * junto al login normal: con el SSO de Comillas activo no se muestra.
10
+ */
11
+ const LoginGriddoId = (props: ILoginGriddoIdProps): JSX.Element => {
12
+ const { handleGriddoId, errorSSO } = props;
13
+
14
+ const text = getLoginLocale();
15
+ const hasNavigated = useRef(false);
16
+
17
+ // Un doble clic no debe iniciar dos flujos: la segunda pulsación se ignora.
18
+ const handleClick = () => {
19
+ if (hasNavigated.current) return;
20
+
21
+ hasNavigated.current = true;
22
+ handleGriddoId();
23
+ };
24
+
25
+ return (
26
+ <S.Alternatives>
27
+ <S.Divider>
28
+ <span>{text.or}</span>
29
+ </S.Divider>
30
+ {errorSSO && <S.StyledNotification text={errorSSO} type="error" closeButton={false} />}
31
+ <S.FullWidthButton type="button" onClick={handleClick}>
32
+ <S.ContentButton>
33
+ <S.TextButton>{text.griddoIdButton}</S.TextButton>
34
+ </S.ContentButton>
35
+ </S.FullWidthButton>
36
+ </S.Alternatives>
37
+ );
38
+ };
39
+
40
+ interface ILoginGriddoIdProps {
41
+ handleGriddoId: () => void;
42
+ /** Error a mostrar sobre el botón; omitir si la pantalla que lo contiene ya lo muestra. */
43
+ errorSSO?: string | null;
44
+ }
45
+
46
+ export default LoginGriddoId;
@@ -0,0 +1,35 @@
1
+ import styled from "styled-components";
2
+
3
+ import { StyledButton } from "../LoginSSO/style";
4
+
5
+ export { ContentButton, IconButton, StyledNotification, TextButton } from "../LoginSSO/style";
6
+
7
+ const Alternatives = styled.div`
8
+ display: flex;
9
+ flex-direction: column;
10
+ gap: ${(p) => p.theme.spacing.s};
11
+ margin-top: ${(p) => p.theme.spacing.m};
12
+ `;
13
+
14
+ const Divider = styled.div`
15
+ ${(p) => p.theme.textStyle.uiS};
16
+ display: flex;
17
+ align-items: center;
18
+ gap: ${(p) => p.theme.spacing.s};
19
+ color: ${(p) => p.theme.color.textMediumEmphasisInverse};
20
+
21
+ &::before,
22
+ &::after {
23
+ content: "";
24
+ flex: 1;
25
+ height: 1px;
26
+ background: ${(p) => p.theme.color.textMediumEmphasisInverse};
27
+ opacity: 0.4;
28
+ }
29
+ `;
30
+
31
+ const FullWidthButton = styled(StyledButton)`
32
+ width: 100%;
33
+ `;
34
+
35
+ export { Alternatives, Divider, FullWidthButton };
@@ -1,8 +1,10 @@
1
1
  import { useEffect, useRef, useState } from "react";
2
2
 
3
- import type { IGlobalSettings } from "@ax/containers/App/reducer";
4
3
  import { Circle } from "@ax/components";
4
+ import type { IGlobalSettings } from "@ax/containers/App/reducer";
5
+
5
6
  import LoginForm from "./LoginForm";
7
+ import LoginGriddoId from "./LoginGriddoId";
6
8
  import LoginSSO from "./LoginSSO";
7
9
 
8
10
  import * as S from "./style";
@@ -21,6 +23,7 @@ const Login = (props: ILoginProps): JSX.Element => {
21
23
  isLoginSuccess,
22
24
  handleLoginSuccess,
23
25
  handleSSO,
26
+ handleGriddoId,
24
27
  errorSSO,
25
28
  } = props;
26
29
 
@@ -49,6 +52,8 @@ const Login = (props: ILoginProps): JSX.Element => {
49
52
  <S.LeftWrapper className={isLoginSuccess ? "animate" : ""} onAnimationEnd={_handleAnimationEnd} ref={wrapperRef}>
50
53
  <S.LoginWrapper className={isLoginSuccess ? "animate" : ""} width={wrapperWidth}>
51
54
  {settings.SSOActivated ? (
55
+ // SSO de Comillas: la pantalla de siempre, sin formulario y sin «Entrar con Griddo» (ese botón
56
+ // solo existe junto al login normal), con o sin `GriddoIdEnabled`.
52
57
  <LoginSSO handleSSO={handleSSO} errorSSO={errorSSO} settings={settings} />
53
58
  ) : (
54
59
  <LoginForm
@@ -61,6 +66,11 @@ const Login = (props: ILoginProps): JSX.Element => {
61
66
  settings={settings}
62
67
  rememberMe={rememberMe}
63
68
  handleRememberMe={handleRememberMe}
69
+ footer={
70
+ settings.GriddoIdEnabled && (
71
+ <LoginGriddoId handleGriddoId={handleGriddoId ?? (() => undefined)} errorSSO={errorSSO} />
72
+ )
73
+ }
64
74
  />
65
75
  )}
66
76
  </S.LoginWrapper>
@@ -87,6 +97,8 @@ export interface ILoginProps {
87
97
  isLoginSuccess: boolean;
88
98
  handleLoginSuccess: () => void;
89
99
  handleSSO: () => void;
100
+ /** Navega a `/sso/start` de la API (login con auth.griddo.io). */
101
+ handleGriddoId?: () => void;
90
102
  errorSSO: string | null;
91
103
  }
92
104
 
@@ -0,0 +1,46 @@
1
+ import { useEffect, useRef } from "react";
2
+
3
+ import { Circle } from "@ax/components";
4
+ import { getLoginLocale } from "@ax/locales";
5
+
6
+ import * as S from "./style";
7
+
8
+ /**
9
+ * S6: acceso denegado tras el login con `auth.griddo.io`. Texto fijo: no lee parámetros de la URL ni distingue
10
+ * la causa (la API redirige aquí igual para todas). «Entrar con otra cuenta» cierra la sesión central y empieza
11
+ * un login nuevo.
12
+ */
13
+ const SsoDenied = (props: ISsoDeniedProps): JSX.Element => {
14
+ const { switchAccountUrl } = props;
15
+
16
+ const text = getLoginLocale();
17
+ const titleRef = useRef<HTMLHeadingElement>(null);
18
+
19
+ useEffect(() => {
20
+ titleRef.current?.focus();
21
+ }, []);
22
+
23
+ return (
24
+ <S.Wrapper data-testid="sso-denied-wrapper">
25
+ <S.LeftWrapper>
26
+ <S.Content>
27
+ <S.Title ref={titleRef} tabIndex={-1}>
28
+ {text.deniedTitle}
29
+ </S.Title>
30
+ <S.SwitchAccount href={switchAccountUrl}>{text.switchAccount}</S.SwitchAccount>
31
+ </S.Content>
32
+ </S.LeftWrapper>
33
+ <S.RightWrapper>
34
+ <Circle animation={1} />
35
+ <Circle animation={2} />
36
+ </S.RightWrapper>
37
+ </S.Wrapper>
38
+ );
39
+ };
40
+
41
+ export interface ISsoDeniedProps {
42
+ /** URL absoluta de `GET /sso/switch-account` de la API. */
43
+ switchAccountUrl: string;
44
+ }
45
+
46
+ export default SsoDenied;
@@ -0,0 +1,37 @@
1
+ import styled from "styled-components";
2
+
3
+ import * as Login from "../Login/style";
4
+
5
+ const Title = styled.h1`
6
+ ${(p) => p.theme.textStyle.headingL};
7
+ color: ${(p) => p.theme.color.textHighEmphasisInverse};
8
+ margin-bottom: ${(p) => p.theme.spacing.m};
9
+ max-width: 416px;
10
+
11
+ &:focus {
12
+ outline: none;
13
+ }
14
+ `;
15
+
16
+ const SwitchAccount = styled.a`
17
+ ${(p) => p.theme.textStyle.uiM};
18
+ color: ${(p) => p.theme.color.textMediumEmphasisInverse};
19
+ text-decoration: underline;
20
+
21
+ &:hover,
22
+ &:focus-visible {
23
+ color: ${(p) => p.theme.color.textHighEmphasisInverse};
24
+ }
25
+ `;
26
+
27
+ const Content = styled.div`
28
+ display: flex;
29
+ flex-direction: column;
30
+ justify-content: center;
31
+ align-items: flex-start;
32
+ width: 100%;
33
+ padding: 0 ${(p) => p.theme.spacing.l};
34
+ `;
35
+
36
+ export const { Wrapper, LeftWrapper, RightWrapper } = Login;
37
+ export { Content, SwitchAccount, Title };
@@ -7,9 +7,10 @@ import BrowserContent from "./BrowserContent";
7
7
  import BulkSelectionOptions from "./BulkSelectionOptions";
8
8
  import Button from "./Button";
9
9
  import CategoryCell from "./CategoryCell";
10
+ import { buildCategoryColumns } from "./CategoryCell/buildCategoryColumns";
10
11
  import Circle from "./Circle";
11
- import ContentItem from "./ContentItem";
12
12
  import ConfigPanel from "./ConfigPanel";
13
+ import ContentItem from "./ContentItem";
13
14
  import ContextMenu from "./ContextMenu";
14
15
  import DragAndDrop from "./DragAndDrop";
15
16
  import ElementsTooltip from "./ElementsTooltip";
@@ -104,6 +105,7 @@ import SearchTagsBar from "./SearchTagsBar";
104
105
  import SelectionComponent from "./SelectionComponent";
105
106
  import SharePageModal from "./SharePageModal";
106
107
  import SideModal from "./SideModal";
108
+ import SsoDenied from "./SsoDenied";
107
109
  import StatusTile from "./StatusTile";
108
110
  import SubNav from "./SubNav";
109
111
  import TableCounter from "./TableCounter";
@@ -146,6 +148,7 @@ export {
146
148
  BrowserContent,
147
149
  BulkSelectionOptions,
148
150
  Button,
151
+ buildCategoryColumns,
149
152
  CancelScheduleModal,
150
153
  CategoryCell,
151
154
  CategoryFilter,
@@ -155,9 +158,9 @@ export {
155
158
  Circle,
156
159
  ComponentArray,
157
160
  ComponentContainer,
158
- ContentItem,
159
161
  ConditionalField,
160
162
  ConfigPanel,
163
+ ContentItem,
161
164
  ContextMenu,
162
165
  CustomizeFilters,
163
166
  DateField,
@@ -186,8 +189,8 @@ export {
186
189
  FormFieldArray,
187
190
  Gallery,
188
191
  GuardModal,
189
- HeadingsPreviewModal,
190
192
  HeadingField,
193
+ HeadingsPreviewModal,
191
194
  HiddenField,
192
195
  Icon,
193
196
  IconAction,
@@ -195,8 +198,8 @@ export {
195
198
  ImageDragAndDrop,
196
199
  ImageField,
197
200
  InformativeMenu,
198
- KeywordsPreviewModal,
199
201
  IntegrationsField,
202
+ KeywordsPreviewModal,
200
203
  LanguageMenu,
201
204
  LastAccessFilter,
202
205
  LinkField,
@@ -218,8 +221,8 @@ export {
218
221
  OcassionalToast,
219
222
  PageFinder,
220
223
  Pagination,
221
- ProfileImage,
222
224
  PermissionsFilter,
225
+ ProfileImage,
223
226
  ProgressBar,
224
227
  RadioField,
225
228
  RadioGroup,
@@ -231,14 +234,15 @@ export {
231
234
  RichText,
232
235
  RoleFilter,
233
236
  ScheduleModal,
237
+ SEOPreview,
234
238
  SearchField,
235
239
  SearchTagsBar,
236
240
  Select,
237
241
  SelectionComponent,
238
- SEOPreview,
239
242
  SharePageModal,
240
243
  SideModal,
241
244
  SiteFilter,
245
+ SsoDenied,
242
246
  StateFilter,
243
247
  StatusFilter,
244
248
  StatusTile,
@@ -260,8 +264,8 @@ export {
260
264
  TypeFilter,
261
265
  UniqueCheck,
262
266
  UrlField,
263
- UsersFilter,
264
267
  UserRolesAndSites,
268
+ UsersFilter,
265
269
  VisualOption,
266
270
  VisualUniqueSelection,
267
271
  Wysiwyg,
@@ -7,6 +7,7 @@ import type { AxiosResponse } from "axios";
7
7
  import differenceInSeconds from "date-fns/differenceInSeconds";
8
8
  import type { Dispatch } from "redux";
9
9
 
10
+ import { clearSession, getSession, type ISession, markSessionEnded, setSession } from "../../api/session";
10
11
  import history from "../../routes/history";
11
12
  import {
12
13
  IS_LOGGING_IN,
@@ -82,15 +83,116 @@ function setToken(token: string): ISetTokenAction {
82
83
  return { type: SET_TOKEN, payload: { token } };
83
84
  }
84
85
 
85
- function logout(): ILogoutAction {
86
+ /** Acción que refleja en el store un par de sesión ya guardado (renovación o login). */
87
+ function setSessionTokens(session: ISession): ISetTokenAction {
88
+ return {
89
+ type: SET_TOKEN,
90
+ payload: { token: session.token, refreshToken: session.refreshToken ?? "", sessionUpdatedAt: session.updatedAt },
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Guarda un par de sesión nuevo (login, SSO, creación o cambio de contraseña) en memoria y disco, y lo
96
+ * refleja en el store. `refreshToken` ausente = API antigua: el 401 cerrará sesión sin renovar.
97
+ */
98
+ function applySession(token: string, refreshToken?: string | null): (dispatch: Dispatch) => void {
99
+ return (dispatch) => {
100
+ dispatch(setSessionTokens(setSession(token, refreshToken ?? null)));
101
+ };
102
+ }
103
+
104
+ /** Limpia el estado local de la sesión (almacenamiento y memoria) y devuelve la acción que vacía el store. */
105
+ function clearLocalSession(): ILogoutAction {
86
106
  const listConfig = localStorage.getItem("sitesConfig") || "";
87
107
  localStorage.clear();
88
108
  localStorage.setItem("sitesConfig", listConfig);
89
- return { type: LOGOUT, payload: { token: "" } };
109
+ clearSession();
110
+ return { type: LOGOUT, payload: { token: "", refreshToken: "", sessionUpdatedAt: 0 } };
111
+ }
112
+
113
+ /**
114
+ * Limpia la sesión local y avisa a la API en segundo plano (revoca la familia de refresh). El cierre local
115
+ * no espera ni depende de la respuesta; un 401 del logout no dispara renovación ni otro cierre.
116
+ */
117
+ function logout(): ILogoutAction {
118
+ const session = getSession();
119
+ if (session) {
120
+ Promise.resolve(global.logout({ token: session.token, refreshToken: session.refreshToken })).catch(() => undefined);
121
+ }
122
+ return clearLocalSession();
123
+ }
124
+
125
+ /** Espera máxima de `POST /logout` en el cierre manual: más allá, AX cierra solo en local. */
126
+ const END_SESSION_TIMEOUT_MS = 5000;
127
+
128
+ /** `endSessionUrl` de la respuesta de `POST /logout` si es una URL http(s); `null` si no hay o no vale. */
129
+ function readEndSessionUrl(
130
+ response: { status?: number; data?: { endSessionUrl?: unknown } } | undefined,
131
+ ): string | null {
132
+ const url = response?.status === 200 ? response.data?.endSessionUrl : undefined;
133
+
134
+ if (typeof url !== "string" || !URL.canParse(url)) return null;
135
+
136
+ return ["https:", "http:"].includes(new URL(url).protocol) ? url : null;
137
+ }
138
+
139
+ /**
140
+ * «Logout» del menú. Avisa a la API esperando la respuesta (máximo 5 s) para saber si la sesión nació de
141
+ * `auth.griddo.io`: en ese caso limpia lo local y navega a la URL de cierre de la sesión central (la persona acaba en
142
+ * «Sesión cerrada» de auth.griddo.io; Hydra avisa a las demás instancias). En cualquier otro caso (sesión con
143
+ * contraseña, error, timeout, URL no válida) se comporta como `logoutAndNavigate`. Solo con `GriddoIdEnabled`: sin él
144
+ * (SSO de Comillas o contraseña) es exactamente `logoutAndNavigate`. La expiración por 401 y el logout por broadcast
145
+ * siguen siendo solo locales.
146
+ */
147
+ function logoutAndEndCentralSession(): (dispatch: Dispatch, getState: () => IRootState) => Promise<void> {
148
+ return async (dispatch, getState) => {
149
+ // Sin Griddo ID (SSO de Comillas o contraseña) el logout es el de siempre: local, sin esperar a la API.
150
+ if (!getState().app.globalSettings.GriddoIdEnabled) {
151
+ await logoutAndNavigate()(dispatch);
152
+
153
+ return;
154
+ }
155
+
156
+ markSessionEnded();
157
+
158
+ const session = getSession();
159
+ let endSessionUrl: string | null = null;
160
+
161
+ if (session) {
162
+ let timer: ReturnType<typeof setTimeout> | undefined;
163
+
164
+ try {
165
+ const response = await Promise.race([
166
+ Promise.resolve(global.logout({ token: session.token, refreshToken: session.refreshToken })),
167
+ new Promise<undefined>((resolve) => {
168
+ timer = setTimeout(() => resolve(undefined), END_SESSION_TIMEOUT_MS);
169
+ }),
170
+ ]);
171
+
172
+ endSessionUrl = readEndSessionUrl(response as Parameters<typeof readEndSessionUrl>[0]);
173
+ } catch {
174
+ endSessionUrl = null;
175
+ } finally {
176
+ clearTimeout(timer);
177
+ }
178
+ }
179
+
180
+ dispatch(clearLocalSession());
181
+
182
+ if (endSessionUrl) {
183
+ window.location.assign(endSessionUrl);
184
+
185
+ return;
186
+ }
187
+
188
+ await setHistoryPush("/logout")(dispatch);
189
+ };
90
190
  }
91
191
 
92
192
  function logoutAndNavigate(): (dispatch: Dispatch) => Promise<void> {
93
193
  return async (dispatch) => {
194
+ // Cierre manual, por 401 o recibido por broadcast: un 401 en vuelo no debe despachar otro.
195
+ markSessionEnded();
94
196
  await setHistoryPush("/logout")(dispatch);
95
197
  };
96
198
  }
@@ -168,7 +270,7 @@ function login(loginData: {
168
270
  return async (dispatch, setState) => {
169
271
  dispatch(setIsLogging(true));
170
272
  const { email, password, rememberMe, petitionId } = loginData;
171
- const loginResponse: AxiosResponse<{ id: number; token: string }> = await global.login({
273
+ const loginResponse: AxiosResponse<{ id: number; token: string; refreshToken?: string }> = await global.login({
172
274
  username: email,
173
275
  password,
174
276
  petitionId,
@@ -177,11 +279,11 @@ function login(loginData: {
177
279
  switch (loginResponse?.status) {
178
280
  case 200: {
179
281
  const {
180
- data: { id, token },
282
+ data: { id, token, refreshToken },
181
283
  } = loginResponse;
182
284
  const langResponse = await languages.getLanguages(token);
183
285
  isReqOk(langResponse.status) && dispatch(setGlobalLanguages(langResponse.data.items));
184
- dispatch(setToken(loginResponse.data.token));
286
+ applySession(token, refreshToken)(dispatch);
185
287
  await usersActions.getUser(id, token, false)(dispatch, setState);
186
288
  dispatch(setSessionStartedAt(new Date()));
187
289
  dispatch(setHasAnimation(true));
@@ -267,12 +369,14 @@ function checkUserSession(): (dispatch: Dispatch, getState: () => IRootState) =>
267
369
  }
268
370
 
269
371
  export {
372
+ applySession,
270
373
  checkUserSession,
271
374
  getGlobalSettings,
272
375
  handleError,
273
376
  login,
274
377
  loginSSO,
275
378
  logout,
379
+ logoutAndEndCentralSession,
276
380
  logoutAndNavigate,
277
381
  resetError,
278
382
  setError,
@@ -284,6 +388,7 @@ export {
284
388
  setIsLogging,
285
389
  setIsSaving,
286
390
  setLanguage,
391
+ setSessionTokens,
287
392
  setToken,
288
393
  setUser,
289
394
  };
@@ -17,12 +17,12 @@ import type { IUser } from "./reducer";
17
17
 
18
18
  export interface ISetTokenAction {
19
19
  type: typeof SET_TOKEN;
20
- payload: { token: string };
20
+ payload: { token: string; refreshToken?: string; sessionUpdatedAt?: number };
21
21
  }
22
22
 
23
23
  export interface ILogoutAction {
24
24
  type: typeof LOGOUT;
25
- payload: { token: string };
25
+ payload: { token: string; refreshToken: string; sessionUpdatedAt: number };
26
26
  }
27
27
 
28
28
  export interface IIsLoggingInAction {