mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-26 19:12:50 +00:00
Merge remote-tracking branch 'origin/WorkflowChange' into feature/exam-attempt-domain
# Conflicts: # apps/portal/src/app/features/exams/pages/ExamsPage/columns.tsx # apps/portal/src/app/features/exams/pages/ExamsPage/index.tsx # libs/api/src/lib/features/licensing/licensing.helpers.ts # libs/auth/src/lib/components/AuthBootstrap.tsx
This commit is contained in:
@@ -3,6 +3,7 @@ export type { AuthConfigValue } from "./lib/AuthConfig";
|
||||
export { AuthShell, BrandMark } from "./lib/components/AuthShell";
|
||||
export { ProtectedRoute } from "./lib/components/ProtectedRoute";
|
||||
export { AuthBootstrap } from "./lib/components/AuthBootstrap";
|
||||
export { useIdleTimer } from "./lib/hooks/useIdleTimer";
|
||||
export { LoginPage } from "./lib/pages/LoginPage";
|
||||
export { SignupPage } from "./lib/pages/SignupPage";
|
||||
export { ForgotPasswordPage } from "./lib/pages/ForgotPasswordPage";
|
||||
@@ -25,6 +26,12 @@ export {
|
||||
resetSignup,
|
||||
} from "./lib/store/signup.slice";
|
||||
export { usePermissions } from "./lib/hooks/usePermissions";
|
||||
export { useAuthToken } from "./lib/hooks/useAuthToken";
|
||||
export { useTwoFactor } from "./lib/hooks/useTwoFactor";
|
||||
export { useSessions } from "./lib/hooks/useSessions";
|
||||
export type { MySession } from "./lib/hooks/useSessions";
|
||||
export { ActiveSessions } from "./lib/components/ActiveSessions";
|
||||
export { currentSessionId } from "./lib/utils/jwt";
|
||||
export type { PermissionSet } from "./lib/hooks/usePermissions";
|
||||
export { RequirePermission } from "./lib/components/RequirePermission";
|
||||
export {
|
||||
@@ -36,6 +43,7 @@ export {
|
||||
useGetMyProfileQuery,
|
||||
useUpdateMyProfileMutation,
|
||||
useUpdateMyAddressMutation,
|
||||
useUpdateMyAccountTypeMutation,
|
||||
PROFILE_FIELDS,
|
||||
PROFILE_FIELD_SECTION,
|
||||
} from "./lib/hooks/useCurrentProfile";
|
||||
|
||||
124
libs/auth/src/lib/components/ActiveSessions/columns.tsx
Normal file
124
libs/auth/src/lib/components/ActiveSessions/columns.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import { ActionIcon, Badge, Checkbox, Group, Text, Tooltip } from '@mantine/core';
|
||||
import { IconLogout } from '@tabler/icons-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { AdvancedColumn } from '@ema-platform/ui';
|
||||
import type { MySession } from '../../hooks/useSessions';
|
||||
|
||||
interface Opts {
|
||||
t: TFunction;
|
||||
sessions: MySession[];
|
||||
selected: string[];
|
||||
setSelected: Dispatch<SetStateAction<string[]>>;
|
||||
/** Undefined when the token carries no session claim — then no row is "this device". */
|
||||
currentId?: string;
|
||||
showDate: (value: string) => string;
|
||||
onRevoke: (session: MySession) => void;
|
||||
}
|
||||
|
||||
export function sessionColumns({
|
||||
t,
|
||||
sessions,
|
||||
selected,
|
||||
setSelected,
|
||||
currentId,
|
||||
showDate,
|
||||
onRevoke,
|
||||
}: Opts): AdvancedColumn<MySession>[] {
|
||||
// The current session is never selectable, so "all" means "all the others".
|
||||
const selectable = sessions.filter((s) => s.id !== currentId);
|
||||
const allSelected = selectable.length > 0 && selectable.every((s) => selected.includes(s.id));
|
||||
|
||||
return [
|
||||
{
|
||||
header: (
|
||||
<Checkbox
|
||||
aria-label={t('profile.sessions.selectAll')}
|
||||
checked={allSelected}
|
||||
indeterminate={selected.length > 0 && !allSelected}
|
||||
disabled={selectable.length === 0}
|
||||
onChange={() => setSelected(allSelected ? [] : selectable.map((s) => s.id))}
|
||||
/>
|
||||
),
|
||||
label: t('profile.sessions.select'),
|
||||
size: 40,
|
||||
cell: ({ row }) => {
|
||||
const isCurrent = row.original.id === currentId;
|
||||
return (
|
||||
<Checkbox
|
||||
aria-label={t('profile.sessions.selectRow', { device: row.original.device })}
|
||||
checked={selected.includes(row.original.id)}
|
||||
disabled={isCurrent}
|
||||
onChange={(e) => {
|
||||
const checked = e.currentTarget.checked;
|
||||
setSelected((prev) =>
|
||||
checked
|
||||
? [...prev, row.original.id]
|
||||
: prev.filter((id) => id !== row.original.id),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.device'),
|
||||
cell: ({ row }) => (
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text size="sm" fw={500}>
|
||||
{row.original.device || '—'}
|
||||
</Text>
|
||||
{row.original.id === currentId && (
|
||||
<Badge variant="light" color="emaTeal" size="sm">
|
||||
{t('profile.sessions.thisDevice')}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.signedIn'),
|
||||
cell: ({ row }) => <Text size="sm">{showDate(row.original.createdAt)}</Text>,
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.expires'),
|
||||
cell: ({ row }) => <Text size="sm">{showDate(row.original.expiryTime)}</Text>,
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.status'),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="light" size="sm" color={row.original.status === 'ACTIVE' ? 'green' : 'gray'}>
|
||||
{row.original.status}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.actions'),
|
||||
size: 70,
|
||||
align: 'center',
|
||||
cell: ({ row }) => {
|
||||
const isCurrent = row.original.id === currentId;
|
||||
return (
|
||||
<Tooltip
|
||||
label={
|
||||
isCurrent ? t('profile.sessions.cannotRevokeCurrent') : t('profile.sessions.revoke')
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="red"
|
||||
size="sm"
|
||||
disabled={isCurrent}
|
||||
aria-label={t('profile.sessions.revoke')}
|
||||
onClick={() => onRevoke(row.original)}
|
||||
>
|
||||
<IconLogout size={14} />
|
||||
</ActionIcon>
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
153
libs/auth/src/lib/components/ActiveSessions/index.tsx
Normal file
153
libs/auth/src/lib/components/ActiveSessions/index.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Button, Group, Paper, Stack, Text, Title } from '@mantine/core';
|
||||
import { IconLogout } from '@tabler/icons-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AdvancedTable, ConfirmModal, notify, useErrorHandler, useServerTable } from '@ema-platform/ui';
|
||||
import { useDateDisplayer } from '@ema-platform/shared';
|
||||
import { useSessions, type MySession } from '../../hooks/useSessions';
|
||||
import { useAuthToken } from '../../hooks/useAuthToken';
|
||||
import { currentSessionId } from '../../utils/jwt';
|
||||
import { sessionColumns } from './columns';
|
||||
|
||||
/** What the one confirm dialog is currently asking about. */
|
||||
type Pending =
|
||||
| { kind: 'one'; ids: string[]; device: string }
|
||||
| { kind: 'selected'; ids: string[] }
|
||||
| { kind: 'others' };
|
||||
|
||||
/**
|
||||
* Where the signed-in user is logged in, and how to end those sessions.
|
||||
*
|
||||
* Renders as its own card so it can sit OUTSIDE the change-password <form> on
|
||||
* the Security tab — a bare <button> inside that form would submit it.
|
||||
*/
|
||||
export function ActiveSessions() {
|
||||
const { t } = useTranslation();
|
||||
const { handleError } = useErrorHandler();
|
||||
const showDate = useDateDisplayer();
|
||||
const token = useAuthToken();
|
||||
const currentId = useMemo(() => currentSessionId(token), [token]);
|
||||
|
||||
const { pageIndex, setPageIndex, pageSize, setPageSize, skip, take } = useServerTable({
|
||||
pageSize: 5,
|
||||
});
|
||||
const { sessions, total, isFetching, refetch, revoke, isRevoking, allSessionIds } = useSessions({
|
||||
skip,
|
||||
take,
|
||||
});
|
||||
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [pending, setPending] = useState<Pending | null>(null);
|
||||
|
||||
const columns = useMemo(
|
||||
() =>
|
||||
sessionColumns({
|
||||
t,
|
||||
sessions,
|
||||
selected,
|
||||
setSelected,
|
||||
currentId,
|
||||
showDate,
|
||||
onRevoke: (s: MySession) => setPending({ kind: 'one', ids: [s.id], device: s.device }),
|
||||
}),
|
||||
[t, sessions, selected, currentId, showDate],
|
||||
);
|
||||
|
||||
const confirmMessage = () => {
|
||||
if (!pending) return '';
|
||||
const base =
|
||||
pending.kind === 'one'
|
||||
? t('profile.sessions.confirm.one', { device: pending.device })
|
||||
: pending.kind === 'selected'
|
||||
? t('profile.sessions.confirm.selected', { count: pending.ids.length })
|
||||
: t('profile.sessions.confirm.others');
|
||||
// Without a session claim on the token there is no way to spare this
|
||||
// device, so say so rather than implying the current login survives.
|
||||
return currentId ? base : `${base} ${t('profile.sessions.confirm.unknownDevice')}`;
|
||||
};
|
||||
|
||||
const onConfirm = async () => {
|
||||
if (!pending) return;
|
||||
try {
|
||||
const ids =
|
||||
pending.kind === 'others'
|
||||
? (await allSessionIds()).filter((id) => id !== currentId)
|
||||
: pending.ids;
|
||||
await revoke(ids);
|
||||
notify.success(t('profile.sessions.revoked', { count: ids.length }));
|
||||
setSelected([]);
|
||||
setPending(null);
|
||||
} catch (e) {
|
||||
handleError(e);
|
||||
}
|
||||
};
|
||||
|
||||
// "Sign out everywhere else" is only meaningful once a second session exists.
|
||||
const hasOthers = total > (currentId ? 1 : 0);
|
||||
|
||||
return (
|
||||
<Paper p="xl" shadow="sm" radius="lg" withBorder>
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
||||
<div>
|
||||
<Title order={5}>{t('profile.sessions.title')}</Title>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t('profile.sessions.hint')}
|
||||
</Text>
|
||||
</div>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{selected.length > 0 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
color="red"
|
||||
size="sm"
|
||||
onClick={() => setPending({ kind: 'selected', ids: selected })}
|
||||
>
|
||||
{t('profile.sessions.revokeSelected', { count: selected.length })}
|
||||
</Button>
|
||||
)}
|
||||
{hasOthers && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
color="red"
|
||||
size="sm"
|
||||
leftSection={<IconLogout size={16} />}
|
||||
onClick={() => setPending({ kind: 'others' })}
|
||||
>
|
||||
{t('profile.sessions.signOutOthers')}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<AdvancedTable<MySession>
|
||||
tableName="active-sessions"
|
||||
columns={columns}
|
||||
data={sessions}
|
||||
itemCount={total}
|
||||
pageIndex={pageIndex}
|
||||
onPageChange={setPageIndex}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={setPageSize}
|
||||
pageSizeOptions={[5, 10, 20]}
|
||||
refresh={refetch}
|
||||
isLoading={isFetching}
|
||||
emptyText={t('profile.sessions.empty')}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<ConfirmModal
|
||||
opened={pending !== null}
|
||||
onClose={() => setPending(null)}
|
||||
onConfirm={onConfirm}
|
||||
loading={isRevoking}
|
||||
title={t('profile.sessions.confirm.title')}
|
||||
message={confirmMessage()}
|
||||
confirmLabel={t('profile.sessions.revoke')}
|
||||
cancelLabel={t('common.cancel', 'Cancel')}
|
||||
/>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { authStorage } from "../utils/auth-storage";
|
||||
import { hydrateAuth, logout, setUser } from "../store/auth.slice";
|
||||
import type { AuthUser } from "../types/auth.types";
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { PageLoader } from '@ema-platform/ui';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import { hydrateAuth, logout, setToken, setUser } from '../store/auth.slice';
|
||||
import { refreshAccessToken } from '../utils/refresh-token';
|
||||
import type { AuthUser } from '../types/auth.types';
|
||||
|
||||
const BASE_API_URL =
|
||||
(import.meta as { env?: Record<string, string> }).env?.[
|
||||
"VITE_BASE_API_URL"
|
||||
] ?? "http://localhost:3001/api";
|
||||
(import.meta as { env?: Record<string, string> }).env?.['VITE_BASE_API_URL'] ??
|
||||
'http://localhost:3000/api';
|
||||
|
||||
/**
|
||||
* Restores the signed-in session before the router renders.
|
||||
@@ -38,10 +39,31 @@ export function AuthBootstrap({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BASE_API_URL}/auth/me`, {
|
||||
let response = await fetch(`${BASE_API_URL}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
|
||||
// An expired access token is the normal state after a day away — spend
|
||||
// the refresh token before deciding the session is over. Without this
|
||||
// a lapsed token logs the user out on load even though the credential
|
||||
// to renew it is sitting right next to it in storage.
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
try {
|
||||
const fresh = await refreshAccessToken();
|
||||
dispatch(setToken(fresh));
|
||||
response = await fetch(`${BASE_API_URL}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${fresh}` },
|
||||
});
|
||||
} catch (err) {
|
||||
// Only the server rejecting the refresh token ends the session —
|
||||
// same rule as the API layer's 401 handler. A 502 or a network
|
||||
// blip during refresh keeps the stored session; the screens
|
||||
// surface their own errors.
|
||||
if (!(err as { sessionExpired?: boolean })?.sessionExpired) return;
|
||||
// Rejected — fall through to the logout below.
|
||||
}
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
const user = (await response.json()) as AuthUser;
|
||||
// Keep the persisted session as the source of truth when it is
|
||||
@@ -71,7 +93,7 @@ export function AuthBootstrap({ children }: { children: ReactNode }) {
|
||||
|
||||
// Rendering the router before the session resolves would let the guards
|
||||
// redirect based on a state that is about to change.
|
||||
if (!ready) return null;
|
||||
if (!ready) return <PageLoader label="Authenticating Maritime Session…" height="100vh" />;
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
@@ -7,15 +7,14 @@ import {
|
||||
Stack,
|
||||
Text,
|
||||
Title,
|
||||
UnstyledButton,
|
||||
rem,
|
||||
useComputedColorScheme,
|
||||
useMantineColorScheme,
|
||||
useMantineTheme,
|
||||
type BoxProps,
|
||||
} from '@mantine/core';
|
||||
import { IconCheck, IconMoon, IconSun } from '@tabler/icons-react';
|
||||
import { IconCheck } from '@tabler/icons-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ColorSchemeToggle, LanguageSwitcher } from '@ema-platform/ui';
|
||||
import { useAuthConfig } from '../AuthConfig';
|
||||
|
||||
export function BrandMark({ size = 44, ...boxProps }: BoxProps & { size?: number }) {
|
||||
@@ -33,35 +32,6 @@ export function BrandMark({ size = 44, ...boxProps }: BoxProps & { size?: number
|
||||
);
|
||||
}
|
||||
|
||||
function ThemeToggle() {
|
||||
const { t } = useTranslation();
|
||||
const { setColorScheme } = useMantineColorScheme();
|
||||
const computed = useComputedColorScheme('light');
|
||||
const isDark = computed === 'dark';
|
||||
|
||||
return (
|
||||
<UnstyledButton
|
||||
onClick={() => setColorScheme(isDark ? 'light' : 'dark')}
|
||||
aria-label={t('authShell.toggleTheme', 'Toggle theme')}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: rem(36),
|
||||
height: rem(36),
|
||||
borderRadius: rem(10),
|
||||
border: '1px solid var(--mantine-color-default-border)',
|
||||
background: 'var(--mantine-color-body)',
|
||||
color: 'var(--mantine-color-dimmed)',
|
||||
cursor: 'pointer',
|
||||
transition: 'all 150ms ease',
|
||||
}}
|
||||
>
|
||||
{isDark ? <IconSun size={18} /> : <IconMoon size={18} />}
|
||||
</UnstyledButton>
|
||||
);
|
||||
}
|
||||
|
||||
interface AuthShellProps {
|
||||
children: ReactNode;
|
||||
brandTitle?: string;
|
||||
@@ -98,8 +68,9 @@ export function AuthShell({ children, brandTitle, brandSubtitle }: AuthShellProp
|
||||
}}
|
||||
p="md"
|
||||
>
|
||||
{/* Theme toggle — top-right corner */}
|
||||
<Box
|
||||
{/* Language switcher & Theme toggle — top-right corner */}
|
||||
<Group
|
||||
gap="xs"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: rem(16),
|
||||
@@ -107,8 +78,9 @@ export function AuthShell({ children, brandTitle, brandSubtitle }: AuthShellProp
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
<ThemeToggle />
|
||||
</Box>
|
||||
<LanguageSwitcher supportedLanguages={['en', 'am']} />
|
||||
<ColorSchemeToggle />
|
||||
</Group>
|
||||
|
||||
<Flex
|
||||
mih="100vh"
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import Cookies from 'js-cookie';
|
||||
import { Navigate, Outlet, useLocation } from 'react-router-dom';
|
||||
import type { ReactNode } from 'react';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import { useAuthToken } from '../hooks/useAuthToken';
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children?: ReactNode;
|
||||
loginPath?: string;
|
||||
}
|
||||
|
||||
export function ProtectedRoute({ children, loginPath = '/login' }: ProtectedRouteProps) {
|
||||
export function ProtectedRoute({ children, loginPath = '/' }: ProtectedRouteProps) {
|
||||
const location = useLocation();
|
||||
// `authStorage` is already scoped to this app; the bare key is only the
|
||||
// legacy pre-prefix session. Never read a sibling app's token — that is how
|
||||
// a backoffice tab ends up authenticated as a portal applicant.
|
||||
const token = authStorage.getToken() ?? Cookies.get('auth-token');
|
||||
const token = useAuthToken();
|
||||
|
||||
if (!token) {
|
||||
return <Navigate to={loginPath} state={{ from: location }} replace />;
|
||||
|
||||
22
libs/auth/src/lib/hooks/two-factor-request.spec.ts
Normal file
22
libs/auth/src/lib/hooks/two-factor-request.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { twoFactorRequest } from "./two-factor-request";
|
||||
|
||||
describe("twoFactorRequest", () => {
|
||||
it("creates when the user has no account configuration yet", () => {
|
||||
expect(twoFactorRequest(undefined, true)).toEqual({
|
||||
url: "/account-configurations/set-my-config",
|
||||
method: "POST",
|
||||
body: { isMFARequired: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("updates an existing record instead of creating a second one", () => {
|
||||
const config = { id: "c9fc67c6", isMFARequired: true };
|
||||
|
||||
expect(twoFactorRequest(config, false)).toEqual({
|
||||
url: "/account-configurations/my-config/c9fc67c6",
|
||||
method: "PUT",
|
||||
body: { isMFARequired: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
26
libs/auth/src/lib/hooks/two-factor-request.ts
Normal file
26
libs/auth/src/lib/hooks/two-factor-request.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
type AccountConfig = { id: string; isMFARequired: boolean };
|
||||
|
||||
/**
|
||||
* Picks the request that persists the two-step verification setting.
|
||||
*
|
||||
* `set-my-config` only ever creates, and `iam.account_configurations` is unique
|
||||
* per user — so an existing record has to be updated through PUT. Getting this
|
||||
* backwards works exactly once and then fails on the unique constraint, which
|
||||
* is why the choice lives here, apart from the hook, with a test on it.
|
||||
*/
|
||||
export function twoFactorRequest(
|
||||
config: AccountConfig | undefined,
|
||||
isMFARequired: boolean,
|
||||
) {
|
||||
return config
|
||||
? {
|
||||
url: `/account-configurations/my-config/${config.id}`,
|
||||
method: "PUT" as const,
|
||||
body: { isMFARequired },
|
||||
}
|
||||
: {
|
||||
url: "/account-configurations/set-my-config",
|
||||
method: "POST" as const,
|
||||
body: { isMFARequired },
|
||||
};
|
||||
}
|
||||
15
libs/auth/src/lib/hooks/useAuthToken.ts
Normal file
15
libs/auth/src/lib/hooks/useAuthToken.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { useSelector } from 'react-redux';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import type { AuthState } from '../types/auth.types';
|
||||
|
||||
/**
|
||||
* The current auth token, preferring Redux so components re-render on login
|
||||
* and logout. Falls back to storage for the one case Redux misses: both
|
||||
* `hydrateAuth` and the stores' `preloadedState` only populate `auth.token`
|
||||
* when a token *and* a cached user are present, so a session with a token but
|
||||
* no cached user would otherwise read as signed out.
|
||||
*/
|
||||
export function useAuthToken(): string | undefined {
|
||||
const token = useSelector((state: { auth: AuthState }) => state.auth.token);
|
||||
return token ?? authStorage.getToken();
|
||||
}
|
||||
@@ -119,6 +119,22 @@ const profileApi = baseApi
|
||||
query: ({ id, body }) => ({ url: `/profiles/${id}`, method: 'PUT', body }),
|
||||
invalidatesTags: ['CurrentProfile'],
|
||||
}),
|
||||
/**
|
||||
* The portal role — seafarer, vessel owner or logistics operator.
|
||||
*
|
||||
* Sidebar and route permissions are computed from this server-side
|
||||
* (`profiles.type`), not from the declared modes of operation, so the
|
||||
* Operations tab writes it here too. Invalidates the profile so the
|
||||
* shell repermissions itself without a reload.
|
||||
*/
|
||||
updateMyAccountType: builder.mutation<unknown, { type: string }>({
|
||||
query: (body) => ({
|
||||
url: '/profiles/me/account-type',
|
||||
method: 'PUT',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_result, error) => (error ? [] : ['CurrentProfile']),
|
||||
}),
|
||||
updateMyAddress: builder.mutation<
|
||||
unknown,
|
||||
{ id: string; body: Record<string, unknown> }
|
||||
@@ -134,6 +150,7 @@ export const {
|
||||
useGetMyProfileQuery,
|
||||
useUpdateMyProfileMutation,
|
||||
useUpdateMyAddressMutation,
|
||||
useUpdateMyAccountTypeMutation,
|
||||
} = profileApi;
|
||||
export const currentProfileApi = profileApi;
|
||||
|
||||
|
||||
76
libs/auth/src/lib/hooks/useIdleTimer.ts
Normal file
76
libs/auth/src/lib/hooks/useIdleTimer.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
const ACTIVITY_EVENTS = [
|
||||
'mousedown',
|
||||
'mousemove',
|
||||
'keydown',
|
||||
'scroll',
|
||||
'touchstart',
|
||||
'click',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Fires `onIdle` once no activity event has fired for `timeoutMs` — the
|
||||
* "left the desk" auto-logout for a govt app handling sensitive records.
|
||||
*
|
||||
* `onIdle` is read through a ref rather than a `useEffect` dependency: the
|
||||
* caller typically passes a fresh closure every render (it captures
|
||||
* `dispatch`, `navigate`, current user), and depending on it directly would
|
||||
* tear down and re-add six window listeners — and rearm the timer to a full
|
||||
* 15 minutes — on every unrelated re-render, not just real activity.
|
||||
*/
|
||||
export function useIdleTimer(timeoutMs: number, onIdle: () => void) {
|
||||
const onIdleRef = useRef(onIdle);
|
||||
onIdleRef.current = onIdle;
|
||||
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
let lastReset = 0;
|
||||
|
||||
// localStorage is origin-scoped, so every tab of this app shares it and
|
||||
// the sibling app (other port/domain) does not.
|
||||
const ACTIVITY_KEY = 'ema-last-activity';
|
||||
|
||||
function fire() {
|
||||
// This tab sat idle, but a sibling tab may have been busy the whole
|
||||
// time — logging out here would clear the shared cookies and kill that
|
||||
// tab mid-work. Trust the newest activity stamp any tab wrote.
|
||||
let last = 0;
|
||||
try {
|
||||
last = Number(localStorage.getItem(ACTIVITY_KEY)) || 0;
|
||||
} catch {
|
||||
/* storage blocked — fall back to this tab's own timer */
|
||||
}
|
||||
const remaining = last + timeoutMs - Date.now();
|
||||
if (remaining > 1000) {
|
||||
timer = setTimeout(fire, remaining);
|
||||
} else {
|
||||
onIdleRef.current();
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
// mousemove fires dozens of times a second; only rearm once a second
|
||||
// so it isn't clearing/setting a timeout on every pixel of movement.
|
||||
const now = Date.now();
|
||||
if (now - lastReset < 1000) return;
|
||||
lastReset = now;
|
||||
try {
|
||||
localStorage.setItem(ACTIVITY_KEY, String(now));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(fire, timeoutMs);
|
||||
}
|
||||
|
||||
reset();
|
||||
ACTIVITY_EVENTS.forEach((event) => window.addEventListener(event, reset));
|
||||
return () => {
|
||||
ACTIVITY_EVENTS.forEach((event) =>
|
||||
window.removeEventListener(event, reset),
|
||||
);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [timeoutMs]);
|
||||
}
|
||||
65
libs/auth/src/lib/hooks/useSessions.ts
Normal file
65
libs/auth/src/lib/hooks/useSessions.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { useApiLazyQuery, useApiMutation, useApiQuery } from '@ema-platform/api';
|
||||
|
||||
export interface MySession {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
email: string;
|
||||
/** IP address the session was created from — IAM sends no user agent. */
|
||||
device: string;
|
||||
expiryTime: string;
|
||||
refreshCount: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
/** `/sessions/my-sessions` answers with a tuple, not the usual `{items, count}`. */
|
||||
type SessionsResponse = [MySession[], number];
|
||||
|
||||
const SESSIONS_URL = '/sessions/my-sessions';
|
||||
const ORDER_BY = 'CreatedAt:DESC';
|
||||
|
||||
function unwrapList(data: unknown): SessionsResponse {
|
||||
if (!Array.isArray(data)) return [[], 0];
|
||||
const [items, total] = data as Partial<SessionsResponse>;
|
||||
return [items ?? [], total ?? 0];
|
||||
}
|
||||
|
||||
/**
|
||||
* The signed-in user's login sessions, and the two ways to end them.
|
||||
*
|
||||
* Uses the generic query/mutation endpoints rather than its own slice, so
|
||||
* freshness comes from `refetch()` rather than cache tags — the same shape as
|
||||
* `useTwoFactor`.
|
||||
*/
|
||||
export function useSessions({ skip, take }: { skip: number; take: number }) {
|
||||
const { data, isFetching, refetch } = useApiQuery<SessionsResponse>({
|
||||
url: SESSIONS_URL,
|
||||
params: { skip, take, orderBy: ORDER_BY },
|
||||
});
|
||||
const [fetchAll] = useApiLazyQuery<SessionsResponse>();
|
||||
const [send, { isLoading: isRevoking }] = useApiMutation();
|
||||
|
||||
const [sessions, total] = unwrapList(data);
|
||||
|
||||
/** Every session id the user has, not just the ones on the current page. */
|
||||
const allSessionIds = async (): Promise<string[]> => {
|
||||
// `total` is one page stale at worst; ask for a page big enough to cover it
|
||||
// growing between render and click.
|
||||
const result = await fetchAll({
|
||||
url: SESSIONS_URL,
|
||||
params: { skip: 0, take: Math.max(total, sessions.length) + 20, orderBy: ORDER_BY },
|
||||
}).unwrap();
|
||||
return unwrapList(result)[0].map((s) => s.id);
|
||||
};
|
||||
|
||||
const revoke = async (ids: string[]) => {
|
||||
if (ids.length === 0) return;
|
||||
await send(
|
||||
ids.length === 1
|
||||
? { url: `/sessions/revoke/${ids[0]}`, method: 'DELETE' }
|
||||
: { url: '/sessions/bulk-revoke', method: 'POST', body: { sessionIds: ids } },
|
||||
).unwrap();
|
||||
await refetch();
|
||||
};
|
||||
|
||||
return { sessions, total, isFetching, refetch, revoke, isRevoking, allSessionIds };
|
||||
}
|
||||
21
libs/auth/src/lib/hooks/useTwoFactor.ts
Normal file
21
libs/auth/src/lib/hooks/useTwoFactor.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { useApiMutation, useApiQuery } from "@ema-platform/api";
|
||||
import { twoFactorRequest } from "./two-factor-request";
|
||||
|
||||
type AccountConfig = { id: string; isMFARequired: boolean };
|
||||
|
||||
/** Reads and writes the signed-in user's IAM two-step verification setting. */
|
||||
export function useTwoFactor() {
|
||||
const { data, refetch, isLoading } = useApiQuery<{ items: AccountConfig[] }>({
|
||||
url: "/account-configurations/my-config",
|
||||
});
|
||||
const [save, { isLoading: isSaving }] = useApiMutation();
|
||||
|
||||
const config = data?.items?.[0];
|
||||
|
||||
const setEnabled = async (isMFARequired: boolean) => {
|
||||
await save(twoFactorRequest(config, isMFARequired)).unwrap();
|
||||
await refetch();
|
||||
};
|
||||
|
||||
return { enabled: !!config?.isMFARequired, isLoading, isSaving, setEnabled };
|
||||
}
|
||||
@@ -11,8 +11,10 @@ import {
|
||||
Text,
|
||||
TextInput,
|
||||
Title,
|
||||
UnstyledButton,
|
||||
} from "@mantine/core";
|
||||
import {
|
||||
IconArrowLeft,
|
||||
IconArrowRight,
|
||||
IconDeviceMobile,
|
||||
IconLock,
|
||||
@@ -50,6 +52,14 @@ export function LoginPage() {
|
||||
const [meTrigger] = useApiMutation<AuthUser>();
|
||||
const [profileTrigger] = useApiMutation<{ profile: CurrentProfile | null }>();
|
||||
|
||||
const handleBack = () => {
|
||||
if (window.history.length > 1) {
|
||||
navigate(-1);
|
||||
} else {
|
||||
navigate("/");
|
||||
}
|
||||
};
|
||||
|
||||
// Built inside the component (not module scope) so validation messages
|
||||
// pick up the active language — same pattern as ProfilePage's forms.
|
||||
const schema = z.object({
|
||||
@@ -101,6 +111,17 @@ export function LoginPage() {
|
||||
method: "POST",
|
||||
body: values,
|
||||
}).unwrap();
|
||||
|
||||
// Two-step verification on: the server withheld the tokens and mailed a
|
||||
// one-time code instead. Storing this response would write an undefined
|
||||
// token and 401 the very next request.
|
||||
if (data.mfaRequired) {
|
||||
navigate("/otp-verify", {
|
||||
state: { mode: "mfa", email: values.email },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch(loginSuccess(data));
|
||||
|
||||
const me = await meTrigger({
|
||||
@@ -149,6 +170,32 @@ export function LoginPage() {
|
||||
return (
|
||||
<AuthShell>
|
||||
<Stack gap="lg">
|
||||
<UnstyledButton
|
||||
onClick={handleBack}
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: 6,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
color: "var(--mantine-color-dimmed)",
|
||||
cursor: "pointer",
|
||||
width: "fit-content",
|
||||
transition: "all 150ms ease",
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.color = "var(--mantine-primary-color-filled)";
|
||||
e.currentTarget.style.transform = "translateX(-3px)";
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.color = "var(--mantine-color-dimmed)";
|
||||
e.currentTarget.style.transform = "translateX(0)";
|
||||
}}
|
||||
>
|
||||
<IconArrowLeft size={18} />
|
||||
{t("common.back", "Back")}
|
||||
</UnstyledButton>
|
||||
|
||||
<div>
|
||||
<Title order={2} fz={30}>
|
||||
{t("login.welcome", { appName, defaultValue: "Welcome to {{appName}}" })}
|
||||
|
||||
@@ -17,10 +17,13 @@ import { Controller, useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useApiMutation } from '@ema-platform/api';
|
||||
import { notify, useErrorHandler } from '@ema-platform/ui';
|
||||
import { AuthShell } from '../components/AuthShell';
|
||||
import { useAuthConfig } from '../AuthConfig';
|
||||
import { loginSuccess, setUser } from '../store/auth.slice';
|
||||
import type { AuthUser, LoginPayload } from '../types/auth.types';
|
||||
|
||||
const CODE_LENGTH = 6;
|
||||
const RESEND_SECONDS = 30;
|
||||
@@ -37,14 +40,18 @@ export function OTPVerificationPage() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { loginRedirectPath } = useAuthConfig();
|
||||
const dispatch = useDispatch();
|
||||
const state = location.state as
|
||||
| { email?: string; phoneNumber?: string }
|
||||
| { email?: string; phoneNumber?: string; mode?: 'mfa' }
|
||||
| null;
|
||||
const email = state?.email ?? '';
|
||||
const phoneNumber = state?.phoneNumber ?? '';
|
||||
/** Second factor at sign-in, as opposed to the phone-number verification. */
|
||||
const isMfa = state?.mode === 'mfa';
|
||||
|
||||
const [verifyTrigger, { isLoading: loading }] = useApiMutation();
|
||||
const [verifyTrigger, { isLoading: loading }] = useApiMutation<LoginPayload>();
|
||||
const [resendTrigger, { isLoading: resending }] = useApiMutation();
|
||||
const [meTrigger] = useApiMutation<AuthUser>();
|
||||
const [secondsLeft, setSecondsLeft] = useState(RESEND_SECONDS);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const { handleError } = useErrorHandler();
|
||||
@@ -66,6 +73,21 @@ export function OTPVerificationPage() {
|
||||
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
try {
|
||||
if (isMfa) {
|
||||
const data = await verifyTrigger({
|
||||
url: '/auth/mfa-verify',
|
||||
method: 'POST',
|
||||
body: { email, otp: values.verificationCode },
|
||||
}).unwrap();
|
||||
|
||||
dispatch(loginSuccess(data));
|
||||
const me = await meTrigger({ url: '/auth/me', method: 'GET' }).unwrap();
|
||||
dispatch(setUser(me));
|
||||
|
||||
navigate(loginRedirectPath);
|
||||
return;
|
||||
}
|
||||
|
||||
await verifyTrigger({
|
||||
url: '/auth/verify-phone-number',
|
||||
method: 'PATCH',
|
||||
@@ -164,44 +186,51 @@ export function OTPVerificationPage() {
|
||||
</Stack>
|
||||
</form>
|
||||
|
||||
<Divider
|
||||
label="Having trouble?"
|
||||
labelPosition="center"
|
||||
variant="dashed"
|
||||
/>
|
||||
{/* Sign-in has not happened yet under MFA, so there is nothing to skip
|
||||
to — and the resend endpoint below only regenerates phone-verification
|
||||
codes. A fresh MFA code means logging in again. */}
|
||||
{!isMfa && (
|
||||
<>
|
||||
<Divider
|
||||
label="Having trouble?"
|
||||
labelPosition="center"
|
||||
variant="dashed"
|
||||
/>
|
||||
|
||||
<Button
|
||||
variant="light"
|
||||
fullWidth
|
||||
size="md"
|
||||
onClick={() => navigate(loginRedirectPath)}
|
||||
>
|
||||
Skip verification for now
|
||||
</Button>
|
||||
<Button
|
||||
variant="light"
|
||||
fullWidth
|
||||
size="md"
|
||||
onClick={() => navigate(loginRedirectPath)}
|
||||
>
|
||||
Skip verification for now
|
||||
</Button>
|
||||
|
||||
<Center>
|
||||
<Group justify="center" gap={6}>
|
||||
<Text size="sm" c="dimmed">
|
||||
Didn't receive a code?
|
||||
</Text>
|
||||
{secondsLeft > 0 ? (
|
||||
<Text size="sm" c="dimmed" fw={600}>
|
||||
Resend in {secondsLeft}s
|
||||
</Text>
|
||||
) : (
|
||||
<Anchor
|
||||
size="sm"
|
||||
fw={600}
|
||||
onClick={handleResendOtp}
|
||||
style={
|
||||
resending ? { pointerEvents: 'none', opacity: 0.6 } : undefined
|
||||
}
|
||||
>
|
||||
Resend code
|
||||
</Anchor>
|
||||
)}
|
||||
</Group>
|
||||
</Center>
|
||||
<Center>
|
||||
<Group justify="center" gap={6}>
|
||||
<Text size="sm" c="dimmed">
|
||||
Didn't receive a code?
|
||||
</Text>
|
||||
{secondsLeft > 0 ? (
|
||||
<Text size="sm" c="dimmed" fw={600}>
|
||||
Resend in {secondsLeft}s
|
||||
</Text>
|
||||
) : (
|
||||
<Anchor
|
||||
size="sm"
|
||||
fw={600}
|
||||
onClick={handleResendOtp}
|
||||
style={
|
||||
resending ? { pointerEvents: 'none', opacity: 0.6 } : undefined
|
||||
}
|
||||
>
|
||||
Resend code
|
||||
</Anchor>
|
||||
)}
|
||||
</Group>
|
||||
</Center>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</AuthShell>
|
||||
);
|
||||
|
||||
@@ -11,8 +11,10 @@ import {
|
||||
Text,
|
||||
TextInput,
|
||||
Title,
|
||||
UnstyledButton,
|
||||
} from '@mantine/core';
|
||||
import {
|
||||
IconArrowLeft,
|
||||
IconArrowRight,
|
||||
IconAt,
|
||||
IconDeviceMobile,
|
||||
@@ -61,6 +63,14 @@ export function SignupPage() {
|
||||
}>();
|
||||
const [meTrigger] = useApiMutation<AuthUser>();
|
||||
|
||||
const handleBack = () => {
|
||||
if (window.history.length > 1) {
|
||||
navigate(-1);
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
};
|
||||
|
||||
// Order matches passwordRules' default list: length, lowercase, uppercase,
|
||||
// number, special character. Shared between the zod schema (field error)
|
||||
// and the live checklist below, so both agree on the wording.
|
||||
@@ -80,7 +90,12 @@ export function SignupPage() {
|
||||
username: z.string().min(3, { message: t('signup.usernameMinLength', 'Username must be at least 3 characters') }),
|
||||
phoneNumber: z.string().min(1, { message: t('signup.phoneRequired', 'Phone number is required') }),
|
||||
userType: z.literal('individual'),
|
||||
nameEn: z.string().min(1, { message: t('signup.nameEnRequired', 'Name (English) is required') }),
|
||||
nameEn: z
|
||||
.string()
|
||||
.min(1, { message: t('signup.nameEnRequired', 'Name (English) is required') })
|
||||
.refine((v) => v.trim().split(/\s+/).length >= 3, {
|
||||
message: t('signup.nameEnFullNameRequired', 'Please enter your full name (first, middle, and last)'),
|
||||
}),
|
||||
nameAm: z.string().optional(),
|
||||
password: passwordSchema(8, passwordRuleLabels),
|
||||
confirmPassword: z.string().min(1, { message: t('signup.confirmPasswordRequired', 'Confirm your password') }),
|
||||
@@ -155,6 +170,32 @@ export function SignupPage() {
|
||||
})}
|
||||
>
|
||||
<Stack gap="lg">
|
||||
<UnstyledButton
|
||||
onClick={handleBack}
|
||||
style={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
color: 'var(--mantine-color-dimmed)',
|
||||
cursor: 'pointer',
|
||||
width: 'fit-content',
|
||||
transition: 'all 150ms ease',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.color = 'var(--mantine-primary-color-filled)';
|
||||
e.currentTarget.style.transform = 'translateX(-3px)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.color = 'var(--mantine-color-dimmed)';
|
||||
e.currentTarget.style.transform = 'translateX(0)';
|
||||
}}
|
||||
>
|
||||
<IconArrowLeft size={18} />
|
||||
{t('common.back', 'Back')}
|
||||
</UnstyledButton>
|
||||
|
||||
<div>
|
||||
<Title order={2} fz={30}>
|
||||
{t('signup.title', 'Create account')}
|
||||
@@ -174,7 +215,7 @@ export function SignupPage() {
|
||||
<Stack gap="md">
|
||||
<SimpleGrid cols={{ base: 1, xs: 2 }} spacing="md">
|
||||
<TextInput
|
||||
label={t('signup.nameEnLabel', 'Name (English)')}
|
||||
label={t('signup.nameEnLabel', 'Full name (English)')}
|
||||
placeholder={t('signup.nameEnPlaceholder', 'Abebe Bekele')}
|
||||
leftSection={<IconUser size={18} />}
|
||||
error={errors.nameEn?.message}
|
||||
|
||||
@@ -31,6 +31,8 @@ export const LICENSE_PERMISSIONS = {
|
||||
VIEW_INSPECTIONS: "can:View:inspections",
|
||||
CONFIRM_PAYMENT: "can:confirm:license-payment",
|
||||
VIEW_PAYMENTS: "can:View:license-payments",
|
||||
SCHEDULE_ISSUANCE: "can:schedule:license-issuance",
|
||||
ISSUE_CERTIFICATE: "can:issue:license-certificate",
|
||||
CREATE_LICENSE_TYPE: "can:create:license-type",
|
||||
VIEW_LICENSE_TYPES: "can:View:license-types",
|
||||
UPDATE_LICENSE_TYPE: "can:update:license-type",
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
LoginPayload,
|
||||
} from "../types/auth.types";
|
||||
import { authStorage } from "../utils/auth-storage";
|
||||
import { setSignedOut } from "../utils/refresh-token";
|
||||
|
||||
const initialState: AuthState = {
|
||||
user: null,
|
||||
@@ -19,6 +20,7 @@ const authSlice = createSlice({
|
||||
initialState,
|
||||
reducers: {
|
||||
loginSuccess(state, action: PayloadAction<LoginPayload>) {
|
||||
setSignedOut(false);
|
||||
state.token = action.payload.token;
|
||||
state.isAuthenticated = true;
|
||||
authStorage.setToken(action.payload.token);
|
||||
@@ -37,6 +39,8 @@ const authSlice = createSlice({
|
||||
authStorage.removeProfile();
|
||||
},
|
||||
logout(state) {
|
||||
// Before clearing storage, so an in-flight refresh can't repopulate it.
|
||||
setSignedOut(true);
|
||||
state.user = null;
|
||||
state.token = null;
|
||||
state.isAuthenticated = false;
|
||||
|
||||
18
libs/auth/src/lib/utils/jwt.ts
Normal file
18
libs/auth/src/lib/utils/jwt.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Session id from the access token, when it carries one.
|
||||
*
|
||||
* `/sessions/my-sessions` returns no "this is you" flag, so the only way to
|
||||
* stop the user revoking the session they are sitting in is to read the id off
|
||||
* the token. Undefined is a normal answer — an opaque token just means no
|
||||
* "This device" badge and a confirm dialog that warns instead.
|
||||
*/
|
||||
export function currentSessionId(token?: string): string | undefined {
|
||||
const payload = token?.split('.')[1];
|
||||
if (!payload) return undefined;
|
||||
try {
|
||||
const claims = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
|
||||
return claims.sessionId ?? claims.sid ?? claims.jti;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -10,24 +10,92 @@ interface RefreshResponse {
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
export async function refreshAccessToken(): Promise<string> {
|
||||
/**
|
||||
* Marks the one failure that actually ends a session: the server rejecting the
|
||||
* refresh token. Read structurally by the API layer's 401 handler — a shared
|
||||
* error class would mean `libs/api` importing `libs/auth`, which already
|
||||
* imports `libs/api`.
|
||||
*/
|
||||
const sessionExpired = (message: string) =>
|
||||
Object.assign(new Error(message), { sessionExpired: true });
|
||||
|
||||
let inFlight: Promise<string> | null = null;
|
||||
|
||||
let signedOut = false;
|
||||
|
||||
/**
|
||||
* Set on logout, cleared on login. A refresh that was already in flight when
|
||||
* the user (or the idle timer) signed out must not write its response back
|
||||
* into storage — that would silently re-authenticate an unattended desk.
|
||||
*/
|
||||
export function setSignedOut(v: boolean) {
|
||||
signedOut = v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Concurrent 401s must share one refresh. A page fires several requests at
|
||||
* once; without this each one POSTs the same refresh token, the server rotates
|
||||
* on the first and rejects the rest, and the losers tear down the session the
|
||||
* winner just renewed.
|
||||
*/
|
||||
export function refreshAccessToken(): Promise<string> {
|
||||
inFlight ??= acquireAndRefresh().finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-tab guard on top of the in-tab one: cookies are shared per origin, so
|
||||
* two tabs expiring together would both POST the same rotating refresh token
|
||||
* and the loser would tear down the session the winner just renewed. A Web
|
||||
* Lock makes the second tab wait; if the first tab already refreshed while it
|
||||
* waited, the fresh token is sitting in storage and no request is needed.
|
||||
*/
|
||||
async function acquireAndRefresh(): Promise<string> {
|
||||
if (typeof navigator === "undefined" || !navigator.locks) {
|
||||
// Old Safari / test env — in-tab de-dup still applies.
|
||||
return runRefresh();
|
||||
}
|
||||
const tokenBefore = authStorage.getToken();
|
||||
return navigator.locks.request("ema-token-refresh", async () => {
|
||||
const current = authStorage.getToken();
|
||||
if (current && current !== tokenBefore) return current;
|
||||
return runRefresh();
|
||||
});
|
||||
}
|
||||
|
||||
async function runRefresh(): Promise<string> {
|
||||
if (signedOut) throw new Error("Signed out");
|
||||
const refreshToken = authStorage.getRefreshToken();
|
||||
if (!refreshToken) throw new Error("No refresh token available");
|
||||
if (!refreshToken) throw sessionExpired("No refresh token available");
|
||||
|
||||
// The IAM service exposes this as `refresh-token`; posting to `/auth/refresh`
|
||||
// 404s, which the catch below turns into a silent logout.
|
||||
// 404s, which the caller would turn into a silent logout.
|
||||
const response = await fetch(`${BASE_API_URL}/auth/refresh-token`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
|
||||
if (
|
||||
response.status === 400 ||
|
||||
response.status === 401 ||
|
||||
response.status === 403
|
||||
) {
|
||||
throw sessionExpired("Refresh token rejected");
|
||||
}
|
||||
|
||||
// Anything else is the API having a bad minute — a 502, a proxy timeout. The
|
||||
// session is still valid, so leave it alone and let the screen report it.
|
||||
if (!response.ok) {
|
||||
authStorage.clear();
|
||||
throw new Error("Token refresh failed");
|
||||
throw new Error(`Token refresh failed (${response.status})`);
|
||||
}
|
||||
|
||||
const data: RefreshResponse = await response.json();
|
||||
// Deliberately NOT sessionExpired: the user already signed out, so there is
|
||||
// no session left to end — just refuse to resurrect it.
|
||||
if (signedOut) throw new Error("Signed out during refresh");
|
||||
authStorage.setToken(data.token);
|
||||
if (data.refreshToken) authStorage.setRefreshToken(data.refreshToken);
|
||||
return data.token;
|
||||
|
||||
11
libs/auth/vite.config.mts
Normal file
11
libs/auth/vite.config.mts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
watch: false,
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['src/**/*.spec.ts'],
|
||||
reporters: ['default'],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user