frontend phase 1: auth — phone-OTP login, role routing & session refresh
Replace the username/password stub with Balinyaar's real credential (phone-OTP) and add the role router every authenticated screen sits behind. - services/auth rewritten for OTP over the b2 contract: types/keys/constants, clientApi+mockApi behind a config'd seam, hooks (useRequestOtp/useVerifyOtp/ useMe/useRefresh/useLogout/useSelectRole/useSessionRoleSync). Stub removed. - A1/A2 customer login + B1/B2 nurse switch as one OTP flow at /login (PhoneStep/OtpStep: auto-verify, resend countdown, wrong/expired/lockout states). - Role router: pure resolveRoleDestination + RoleRouter -> family / nurse / admin / select-role, with a splash while /me loads (no wrong-shell flash). - SelectRole first-use screen at /select-role. - Widened AuthState (roles via SessionUser), hydrated from /me by useSessionRoleSync. - Fetch-layer silent token refresh (single-flight + one retry) + shared persistAuthTokens/clearAuthTokens; useRefresh as the on-demand path. - auth i18n namespace in both locales; tests for routing branches, countdown, OtpStep state machine, RoleRouter branches; fixed jest @/ -> src alias. - Docs: client/CLAUDE.md, frontend STATUS/report, for-backend REQ-002..004. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
'use client';
|
||||
import type { ReactNode } from 'react';
|
||||
import { PrivateLayout } from '@/layout';
|
||||
|
||||
import { useSessionRoleSync } from '@/services/auth';
|
||||
|
||||
export default function PrivateRouteLayout({ children }: { children: ReactNode }) {
|
||||
// Hydrate AuthContext roles from /me for a returning (server-seeded) session so the shells
|
||||
// pick the right chrome without a second role store.
|
||||
useSessionRoleSync();
|
||||
return <PrivateLayout>{children}</PrivateLayout>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
'use client';
|
||||
import { Suspense } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { APP_ROLES } from '@/constants';
|
||||
import { SelectRole } from '@/components/auth';
|
||||
|
||||
function SelectRoleContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const initialRole = searchParams.get('role') === APP_ROLES.NURSE ? APP_ROLES.NURSE : APP_ROLES.CUSTOMER;
|
||||
return <SelectRole initialRole={initialRole} />;
|
||||
}
|
||||
|
||||
/** First-use role picker for an authenticated user with no public role yet. */
|
||||
export default function SelectRolePage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<SelectRoleContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
'use client';
|
||||
import { Suspense } from 'react';
|
||||
import { LoginFlow } from '@/components/auth';
|
||||
|
||||
/**
|
||||
* Phone-OTP login (A1/A2 customer, B1/B2 nurse). The Suspense boundary is required because
|
||||
* LoginFlow reads `useSearchParams` (the `?role=nurse` switch).
|
||||
*/
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<LoginFlow />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,15 @@ export function isIranianMobile(value: string): boolean {
|
||||
return /^09\d{9}$/.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Masks a mobile number for a "code sent to …" echo, keeping the first 4 and last 4 digits
|
||||
* (e.g. `09120001234` → `0912•••1234`). Short/partial input is returned unchanged.
|
||||
*/
|
||||
export function maskIranMobile(value: string): string {
|
||||
if (value.length < 8) return value;
|
||||
return `${value.slice(0, 4)}•••${value.slice(-4)}`;
|
||||
}
|
||||
|
||||
export interface PhoneNumberFieldProps extends Omit<TextFieldProps, 'onChange' | 'value' | 'type'> {
|
||||
/** Controlled value — normalized ASCII digits, no formatting. */
|
||||
value: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import PhoneNumberField from './PhoneNumberField';
|
||||
|
||||
export type { PhoneNumberFieldProps } from './PhoneNumberField';
|
||||
export { IRAN_MOBILE_LENGTH, isIranianMobile } from './PhoneNumberField';
|
||||
export { IRAN_MOBILE_LENGTH, isIranianMobile, maskIranMobile } from './PhoneNumberField';
|
||||
export { PhoneNumberField as default, PhoneNumberField };
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
'use client';
|
||||
import { FunctionComponent, PropsWithChildren } from 'react';
|
||||
import { Paper, Stack } from '@mui/material';
|
||||
import { AUTH_CARD_MAX_WIDTH } from './constants';
|
||||
import BrandMark from './BrandMark';
|
||||
|
||||
/**
|
||||
* Centered branded card that hosts each auth step (phone, OTP, role selection). Presentational
|
||||
* shell only — the step content is passed as children.
|
||||
* @component AuthCard
|
||||
*/
|
||||
const AuthCard: FunctionComponent<PropsWithChildren> = ({ children }) => (
|
||||
<Stack sx={{ alignItems: 'center', justifyContent: 'center', minHeight: '70vh', px: 2, py: 4 }}>
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
width: '100%',
|
||||
maxWidth: AUTH_CARD_MAX_WIDTH,
|
||||
p: { xs: 3, sm: 4 },
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
borderRadius: 3,
|
||||
}}
|
||||
>
|
||||
<Stack sx={{ gap: 3 }}>
|
||||
<BrandMark withTagline />
|
||||
{children}
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
export default AuthCard;
|
||||
@@ -0,0 +1,29 @@
|
||||
'use client';
|
||||
import { FunctionComponent } from 'react';
|
||||
import { Stack, Typography } from '@mui/material';
|
||||
import { AppLoading } from '@/components';
|
||||
import BrandMark from './BrandMark';
|
||||
|
||||
interface AuthSplashProps {
|
||||
/** Already-translated status line (e.g. "Signing you in…"). */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-height branded loading splash shown while the role router resolves `/me` — prevents the
|
||||
* wrong actor shell from flashing before the destination is known.
|
||||
* @component AuthSplash
|
||||
*/
|
||||
const AuthSplash: FunctionComponent<AuthSplashProps> = ({ message }) => (
|
||||
<Stack sx={{ alignItems: 'center', justifyContent: 'center', minHeight: '70vh', gap: 2 }}>
|
||||
<BrandMark />
|
||||
<AppLoading />
|
||||
{message && (
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
{message}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
|
||||
export default AuthSplash;
|
||||
@@ -0,0 +1,34 @@
|
||||
'use client';
|
||||
import { FunctionComponent } from 'react';
|
||||
import { Stack, Typography } from '@mui/material';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import AppIcon from '../common/AppIcon';
|
||||
|
||||
interface BrandMarkProps {
|
||||
/** Show the brand tagline under the wordmark. */
|
||||
withTagline?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Balinyaar brand lockup for the auth screens: logo mark + wordmark (+ optional tagline).
|
||||
* Colours come from the palette so it tracks the color scheme.
|
||||
* @component BrandMark
|
||||
*/
|
||||
const BrandMark: FunctionComponent<BrandMarkProps> = ({ withTagline }) => {
|
||||
const t = useTranslations('common');
|
||||
return (
|
||||
<Stack sx={{ alignItems: 'center', gap: 1 }}>
|
||||
<AppIcon icon="logo" size={56} color="var(--bal-primary)" />
|
||||
<Typography variant="h5" component="p" sx={{ fontWeight: 700, color: 'primary.main' }}>
|
||||
{t('brand')}
|
||||
</Typography>
|
||||
{withTagline && (
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary', textAlign: 'center' }}>
|
||||
{t('brand_tagline')}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default BrandMark;
|
||||
@@ -0,0 +1,62 @@
|
||||
'use client';
|
||||
import { FunctionComponent, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
import { APP_ROLES, type AppRole } from '@/constants';
|
||||
import { OTP_RESEND_FALLBACK_SECONDS } from '@/services/auth/constants';
|
||||
import AuthCard from './AuthCard';
|
||||
import PhoneStep from './PhoneStep';
|
||||
import OtpStep from './OtpStep';
|
||||
import RoleRouter from './RoleRouter';
|
||||
|
||||
type Step = 'phone' | 'otp' | 'routing';
|
||||
|
||||
/**
|
||||
* The single login stack for both actors (A1/A2 customer, B1/B2 nurse). One OTP mechanism,
|
||||
* parameterised by `intendedRole` (seeded from `?role=nurse`) — no forked login trees. After a
|
||||
* successful verify it hands off to the role router.
|
||||
* @component LoginFlow
|
||||
*/
|
||||
const LoginFlow: FunctionComponent = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const [intendedRole, setIntendedRole] = useState<AppRole>(
|
||||
searchParams.get('role') === APP_ROLES.NURSE ? APP_ROLES.NURSE : APP_ROLES.CUSTOMER,
|
||||
);
|
||||
const [step, setStep] = useState<Step>('phone');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [resendSeconds, setResendSeconds] = useState(OTP_RESEND_FALLBACK_SECONDS);
|
||||
|
||||
if (step === 'routing') {
|
||||
return <RoleRouter intendedRole={intendedRole} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthCard>
|
||||
{step === 'phone' ? (
|
||||
<PhoneStep
|
||||
intendedRole={intendedRole}
|
||||
onSwitchRole={() =>
|
||||
setIntendedRole((role) =>
|
||||
role === APP_ROLES.NURSE ? APP_ROLES.CUSTOMER : APP_ROLES.NURSE,
|
||||
)
|
||||
}
|
||||
onSent={(nextPhone, result) => {
|
||||
setPhone(nextPhone);
|
||||
setResendSeconds(result.resendAvailableInSeconds);
|
||||
setStep('otp');
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<OtpStep
|
||||
phone={phone}
|
||||
intendedRole={intendedRole}
|
||||
resendSeconds={resendSeconds}
|
||||
onVerified={() => setStep('routing')}
|
||||
onChangeNumber={() => setStep('phone')}
|
||||
/>
|
||||
)}
|
||||
</AuthCard>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginFlow;
|
||||
@@ -0,0 +1,79 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { ThemeProvider } from '../../theme';
|
||||
|
||||
const mockVerifyMutate = jest.fn();
|
||||
const mockVerifyReset = jest.fn();
|
||||
const mockRequestMutate = jest.fn();
|
||||
|
||||
jest.mock('next-intl', () => ({ useTranslations: () => (key: string) => key }));
|
||||
jest.mock('@/services/auth', () => ({
|
||||
useVerifyOtp: () => ({ isPending: false, isError: false, mutate: mockVerifyMutate, reset: mockVerifyReset }),
|
||||
useRequestOtp: () => ({ isPending: false, mutate: mockRequestMutate }),
|
||||
}));
|
||||
|
||||
import OtpStep from './OtpStep';
|
||||
|
||||
const PHONE = '09120001234';
|
||||
|
||||
function renderStep() {
|
||||
const onVerified = jest.fn();
|
||||
const onChangeNumber = jest.fn();
|
||||
render(
|
||||
<ThemeProvider>
|
||||
<OtpStep
|
||||
phone={PHONE}
|
||||
intendedRole="customer"
|
||||
resendSeconds={120}
|
||||
onVerified={onVerified}
|
||||
onChangeNumber={onChangeNumber}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
return { onVerified, onChangeNumber };
|
||||
}
|
||||
|
||||
async function fillCode(code: string) {
|
||||
const user = userEvent.setup();
|
||||
const boxes = screen.getAllByRole('textbox') as HTMLInputElement[];
|
||||
for (let i = 0; i < code.length; i += 1) {
|
||||
await user.type(boxes[i], code[i]);
|
||||
}
|
||||
}
|
||||
|
||||
describe('<OtpStep/> state machine', () => {
|
||||
beforeEach(() => {
|
||||
mockVerifyMutate.mockReset();
|
||||
mockVerifyReset.mockReset();
|
||||
mockRequestMutate.mockReset();
|
||||
});
|
||||
|
||||
it('renders one box per code digit (6)', () => {
|
||||
renderStep();
|
||||
expect(screen.getAllByRole('textbox')).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('auto-verifies once the last box is filled', async () => {
|
||||
renderStep();
|
||||
await fillCode('123456');
|
||||
expect(mockVerifyMutate).toHaveBeenCalledWith(
|
||||
{ phone: PHONE, code: '123456' },
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
|
||||
it('calls onVerified on a successful verify', async () => {
|
||||
mockVerifyMutate.mockImplementation((_vars, opts) => opts.onSuccess?.());
|
||||
const { onVerified } = renderStep();
|
||||
await fillCode('123456');
|
||||
expect(onVerified).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('clears the boxes on a wrong code so the user can retry', async () => {
|
||||
mockVerifyMutate.mockImplementation((_vars, opts) => opts.onError?.(new Error('bad code')));
|
||||
renderStep();
|
||||
await fillCode('000000');
|
||||
const boxes = screen.getAllByRole('textbox') as HTMLInputElement[];
|
||||
expect(boxes.every((box) => box.value === '')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
'use client';
|
||||
import { FormEvent, FunctionComponent, useEffect, useState } from 'react';
|
||||
import { CircularProgress, Link as MuiLink, Stack, Typography } from '@mui/material';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
import OtpInput from '@/components/OtpInput';
|
||||
import { maskIranMobile } from '@/components/PhoneNumberField';
|
||||
import { AppButton } from '@/components';
|
||||
import { APP_ROLES, type AppRole } from '@/constants';
|
||||
import { useRequestOtp, useVerifyOtp } from '@/services/auth';
|
||||
import { OTP_CODE_LENGTH, OTP_LOCKED_CODE } from '@/services/auth/constants';
|
||||
import type { ApiError } from '@/lib/api/errors';
|
||||
import { useCountdown } from './useCountdown';
|
||||
|
||||
interface OtpStepProps {
|
||||
phone: string;
|
||||
intendedRole: AppRole;
|
||||
/** Server's resend cooldown from the request step; drives the initial countdown. */
|
||||
resendSeconds: number;
|
||||
onVerified: () => void;
|
||||
onChangeNumber: () => void;
|
||||
}
|
||||
|
||||
function formatMmSs(totalSeconds: number): string {
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A2 (customer) / B2 (nurse) — the OTP code step. Auto-verifies once the last box is filled,
|
||||
* runs a single resend countdown (cleaned up on unmount), and renders explicit wrong-code,
|
||||
* expired-code and max-attempts-lockout states. Same mechanism for both actors; the CTA copy
|
||||
* differs.
|
||||
* @component OtpStep
|
||||
*/
|
||||
const OtpStep: FunctionComponent<OtpStepProps> = ({
|
||||
phone,
|
||||
intendedRole,
|
||||
resendSeconds,
|
||||
onVerified,
|
||||
onChangeNumber,
|
||||
}) => {
|
||||
const t = useTranslations('auth');
|
||||
const [code, setCode] = useState('');
|
||||
const [locked, setLocked] = useState(false);
|
||||
const countdown = useCountdown();
|
||||
const verifyOtp = useVerifyOtp();
|
||||
const resendOtp = useRequestOtp();
|
||||
|
||||
const { start } = countdown;
|
||||
useEffect(() => start(resendSeconds), [start, resendSeconds]);
|
||||
|
||||
const isNurse = intendedRole === APP_ROLES.NURSE;
|
||||
const hasError = verifyOtp.isError;
|
||||
|
||||
const verify = (value: string) => {
|
||||
if (value.length !== OTP_CODE_LENGTH || verifyOtp.isPending || locked) return;
|
||||
verifyOtp.mutate(
|
||||
{ phone, code: value },
|
||||
{
|
||||
onSuccess: onVerified,
|
||||
onError: (error) => {
|
||||
if ((error as ApiError).code === OTP_LOCKED_CODE) setLocked(true);
|
||||
setCode(''); // clear the boxes so the user can retry a fresh code
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const submit = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
verify(code);
|
||||
};
|
||||
|
||||
const resend = () => {
|
||||
resendOtp.mutate(
|
||||
{ phone },
|
||||
{
|
||||
onSuccess: (result) => {
|
||||
setLocked(false);
|
||||
setCode('');
|
||||
verifyOtp.reset();
|
||||
start(result.resendAvailableInSeconds);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
// While locked, requesting a new code is the way out — allow resend regardless of the timer.
|
||||
const resendDisabled = resendOtp.isPending || (countdown.isActive && !locked);
|
||||
|
||||
return (
|
||||
<Stack component="form" onSubmit={submit} sx={{ gap: 2 }}>
|
||||
<Stack sx={{ gap: 0.5, textAlign: 'center' }}>
|
||||
<Typography variant="h6" component="h1">
|
||||
{t('otp_title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
{t('otp_sent_to', { phone: maskIranMobile(phone) })}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
<OtpInput
|
||||
length={OTP_CODE_LENGTH}
|
||||
value={code}
|
||||
onChange={setCode}
|
||||
onComplete={verify}
|
||||
disabled={locked || verifyOtp.isPending}
|
||||
error={hasError}
|
||||
autoFocus
|
||||
aria-label={t('otp_title')}
|
||||
/>
|
||||
|
||||
{locked ? (
|
||||
<Typography variant="body2" sx={{ color: 'var(--bal-error)', textAlign: 'center' }}>
|
||||
{t('otp_locked')}
|
||||
</Typography>
|
||||
) : hasError ? (
|
||||
<Typography variant="body2" sx={{ color: 'var(--bal-error)', textAlign: 'center' }}>
|
||||
{t('otp_invalid')}
|
||||
</Typography>
|
||||
) : null}
|
||||
|
||||
<AppButton
|
||||
type="submit"
|
||||
color="primary"
|
||||
variant="contained"
|
||||
fullWidth
|
||||
disabled={code.length !== OTP_CODE_LENGTH || verifyOtp.isPending || locked}
|
||||
startIcon={verifyOtp.isPending ? <CircularProgress size={18} color="inherit" /> : undefined}
|
||||
sx={{ m: 0 }}
|
||||
>
|
||||
{isNurse ? t('otp_verify_nurse') : t('otp_verify_customer')}
|
||||
</AppButton>
|
||||
|
||||
<Stack sx={{ alignItems: 'center', gap: 1 }}>
|
||||
{resendDisabled && countdown.isActive && !locked ? (
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
{t('resend_in', { time: formatMmSs(countdown.seconds) })}
|
||||
</Typography>
|
||||
) : (
|
||||
<MuiLink
|
||||
component="button"
|
||||
type="button"
|
||||
onClick={resend}
|
||||
disabled={resendDisabled}
|
||||
underline="hover"
|
||||
sx={{ color: 'primary.main' }}
|
||||
>
|
||||
{t('resend')}
|
||||
</MuiLink>
|
||||
)}
|
||||
<MuiLink
|
||||
component="button"
|
||||
type="button"
|
||||
onClick={onChangeNumber}
|
||||
underline="hover"
|
||||
sx={{ color: 'text.secondary' }}
|
||||
>
|
||||
{t('change_number')}
|
||||
</MuiLink>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default OtpStep;
|
||||
@@ -0,0 +1,106 @@
|
||||
'use client';
|
||||
import { FormEvent, FunctionComponent, useState } from 'react';
|
||||
import { CircularProgress, Link as MuiLink, Stack, Typography } from '@mui/material';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
import PhoneNumberField, { isIranianMobile } from '@/components/PhoneNumberField';
|
||||
import { AppButton } from '@/components';
|
||||
import { APP_ROLES, type AppRole } from '@/constants';
|
||||
import { useRequestOtp } from '@/services/auth';
|
||||
import type { ApiError } from '@/lib/api/errors';
|
||||
import type { RequestOtpResult } from '@/services/auth/types';
|
||||
|
||||
interface PhoneStepProps {
|
||||
intendedRole: AppRole;
|
||||
onSwitchRole: () => void;
|
||||
onSent: (phone: string, result: RequestOtpResult) => void;
|
||||
}
|
||||
|
||||
const RATE_LIMIT_STATUS = 429;
|
||||
|
||||
/**
|
||||
* A1 (customer) / B1 (nurse) — the phone entry step. Same mechanism for both actors; only the
|
||||
* copy and the role-switch link differ. Requests an OTP and advances to the code step; domain
|
||||
* 4xx (invalid number, rate-limit) render inline.
|
||||
* @component PhoneStep
|
||||
*/
|
||||
const PhoneStep: FunctionComponent<PhoneStepProps> = ({ intendedRole, onSwitchRole, onSent }) => {
|
||||
const t = useTranslations('auth');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [invalid, setInvalid] = useState(false);
|
||||
const [rateLimited, setRateLimited] = useState(false);
|
||||
const requestOtp = useRequestOtp();
|
||||
|
||||
const isNurse = intendedRole === APP_ROLES.NURSE;
|
||||
|
||||
const submit = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
setRateLimited(false);
|
||||
if (!isIranianMobile(phone)) {
|
||||
setInvalid(true);
|
||||
return;
|
||||
}
|
||||
setInvalid(false);
|
||||
requestOtp.mutate(
|
||||
{ phone },
|
||||
{
|
||||
onSuccess: (result) => onSent(phone, result),
|
||||
onError: (error) => {
|
||||
if ((error as ApiError).status === RATE_LIMIT_STATUS) setRateLimited(true);
|
||||
else setInvalid(true);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack component="form" onSubmit={submit} sx={{ gap: 2 }}>
|
||||
<Stack sx={{ gap: 0.5, textAlign: 'center' }}>
|
||||
<Typography variant="h6" component="h1">
|
||||
{isNurse ? t('nurse_title') : t('customer_title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
{isNurse ? t('nurse_subtitle') : t('customer_subtitle')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
<PhoneNumberField
|
||||
value={phone}
|
||||
onChange={(next) => {
|
||||
setPhone(next);
|
||||
if (invalid) setInvalid(false);
|
||||
}}
|
||||
label={t('phone_label')}
|
||||
placeholder="0912 000 0000"
|
||||
error={invalid}
|
||||
helperText={invalid ? t('phone_invalid') : rateLimited ? t('rate_limited') : ' '}
|
||||
fullWidth
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<AppButton
|
||||
type="submit"
|
||||
color="primary"
|
||||
variant="contained"
|
||||
fullWidth
|
||||
disabled={requestOtp.isPending}
|
||||
startIcon={requestOtp.isPending ? <CircularProgress size={18} color="inherit" /> : undefined}
|
||||
sx={{ m: 0 }}
|
||||
>
|
||||
{t('request_code')}
|
||||
</AppButton>
|
||||
|
||||
<MuiLink
|
||||
component="button"
|
||||
type="button"
|
||||
onClick={onSwitchRole}
|
||||
underline="hover"
|
||||
sx={{ color: 'text.secondary', textAlign: 'center' }}
|
||||
>
|
||||
{isNurse ? t('customer_switch') : t('nurse_switch')}
|
||||
</MuiLink>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default PhoneStep;
|
||||
@@ -0,0 +1,58 @@
|
||||
import { render, waitFor } from '@testing-library/react';
|
||||
import { ThemeProvider } from '../../theme';
|
||||
import type { Me } from '@/services/auth/types';
|
||||
|
||||
const mockReplace = jest.fn();
|
||||
|
||||
jest.mock('next/navigation', () => ({
|
||||
...jest.requireActual('next/navigation'),
|
||||
useRouter: () => ({ replace: mockReplace }),
|
||||
}));
|
||||
jest.mock('next-intl', () => ({ useLocale: () => 'fa', useTranslations: () => (key: string) => key }));
|
||||
|
||||
let meResult: { data?: Partial<Me>; isError: boolean };
|
||||
jest.mock('@/services/auth', () => ({ useMe: () => meResult }));
|
||||
|
||||
import RoleRouter from './RoleRouter';
|
||||
|
||||
function renderRouter(intendedRole?: 'customer' | 'nurse') {
|
||||
render(
|
||||
<ThemeProvider>
|
||||
<RoleRouter intendedRole={intendedRole} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('<RoleRouter/>', () => {
|
||||
beforeEach(() => mockReplace.mockReset());
|
||||
|
||||
it('does not navigate while /me is loading', () => {
|
||||
meResult = { data: undefined, isError: false };
|
||||
renderRouter();
|
||||
expect(mockReplace).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('routes a customer to the family app', async () => {
|
||||
meResult = { data: { roles: ['customer'] }, isError: false };
|
||||
renderRouter();
|
||||
await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/'));
|
||||
});
|
||||
|
||||
it('routes a nurse to the nurse app', async () => {
|
||||
meResult = { data: { roles: ['nurse'] }, isError: false };
|
||||
renderRouter();
|
||||
await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/nurse'));
|
||||
});
|
||||
|
||||
it('routes a role-less user to select-role, carrying nurse intent', async () => {
|
||||
meResult = { data: { roles: [] }, isError: false };
|
||||
renderRouter('nurse');
|
||||
await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/select-role?role=nurse'));
|
||||
});
|
||||
|
||||
it('falls back to login when /me errors', async () => {
|
||||
meResult = { data: undefined, isError: true };
|
||||
renderRouter();
|
||||
await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/fa/login'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
import { FunctionComponent, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
|
||||
import { APP_ROLES, ROUTES, type AppRole } from '@/constants';
|
||||
import { useMe } from '@/services/auth';
|
||||
import { resolveRoleDestination } from '@/services/auth/routing';
|
||||
import AuthSplash from './AuthSplash';
|
||||
|
||||
interface RoleRouterProps {
|
||||
/** The role the user logged in as (A1 vs B1); disambiguates a multi-role user and pre-selects on SelectRole. */
|
||||
intendedRole?: AppRole;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs after authentication (never re-implements the auth gate — the middleware owns that) and
|
||||
* sends the user to the right app: customer → family, nurse → nurse app, no role → SelectRole,
|
||||
* admin → admin console. Shows the branded splash while `/me` is in flight so the wrong shell
|
||||
* never flashes.
|
||||
* @component RoleRouter
|
||||
*/
|
||||
const RoleRouter: FunctionComponent<RoleRouterProps> = ({ intendedRole }) => {
|
||||
const router = useRouter();
|
||||
const locale = useLocale();
|
||||
const t = useTranslations('auth');
|
||||
const { data: me, isError } = useMe();
|
||||
|
||||
useEffect(() => {
|
||||
if (isError) {
|
||||
router.replace(`/${locale}${ROUTES.LOGIN}`);
|
||||
return;
|
||||
}
|
||||
if (!me) return;
|
||||
|
||||
let destination = resolveRoleDestination(me, intendedRole);
|
||||
// Carry the login intent into role selection so it can pre-select the right role.
|
||||
if (destination === ROUTES.SELECT_ROLE && intendedRole === APP_ROLES.NURSE) {
|
||||
destination = `${destination}?role=${APP_ROLES.NURSE}`;
|
||||
}
|
||||
router.replace(`/${locale}${destination}`);
|
||||
}, [me, isError, intendedRole, router, locale]);
|
||||
|
||||
return <AuthSplash message={t('routing_title')} />;
|
||||
};
|
||||
|
||||
export default RoleRouter;
|
||||
@@ -0,0 +1,115 @@
|
||||
'use client';
|
||||
import { FunctionComponent, useState } from 'react';
|
||||
import { CircularProgress, Paper, Stack, Typography } from '@mui/material';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
|
||||
import AppIcon from '@/components/common/AppIcon';
|
||||
import { AppButton } from '@/components';
|
||||
import { APP_ROLES, type AppRole } from '@/constants';
|
||||
import { useSelectRole } from '@/services/auth';
|
||||
import { resolveRoleDestination } from '@/services/auth/routing';
|
||||
import type { PublicRole } from '@/services/auth/types';
|
||||
import { AUTH_CARD_MAX_WIDTH } from './constants';
|
||||
import BrandMark from './BrandMark';
|
||||
|
||||
interface SelectRoleProps {
|
||||
/** Login intent carried from A1/B1 — pre-selects the matching option. Admin is never offered. */
|
||||
initialRole?: AppRole;
|
||||
}
|
||||
|
||||
const ROLE_OPTIONS: ReadonlyArray<{ role: PublicRole; icon: string }> = [
|
||||
{ role: 'customer', icon: 'account' },
|
||||
{ role: 'nurse', icon: 'home' },
|
||||
];
|
||||
|
||||
/**
|
||||
* First-use role picker for a brand-new user whose `/me` has no public role. Selecting one calls
|
||||
* `me/select_role` (which rotates the token so the new claim lands), then routes into that app.
|
||||
* Admin roles are internal-only and never selectable here.
|
||||
* @component SelectRole
|
||||
*/
|
||||
const SelectRole: FunctionComponent<SelectRoleProps> = ({ initialRole }) => {
|
||||
const t = useTranslations('auth');
|
||||
const router = useRouter();
|
||||
const locale = useLocale();
|
||||
const selectRole = useSelectRole();
|
||||
|
||||
const preset: PublicRole = initialRole === APP_ROLES.NURSE ? 'nurse' : 'customer';
|
||||
const [selected, setSelected] = useState<PublicRole>(preset);
|
||||
|
||||
const confirm = () => {
|
||||
selectRole.mutate(selected, {
|
||||
onSuccess: (me) => router.replace(`/${locale}${resolveRoleDestination(me, selected)}`),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack sx={{ alignItems: 'center', justifyContent: 'center', minHeight: '70vh', px: 2, py: 4 }}>
|
||||
<Stack sx={{ width: '100%', maxWidth: AUTH_CARD_MAX_WIDTH, gap: 3 }}>
|
||||
<BrandMark />
|
||||
<Stack sx={{ gap: 0.5, textAlign: 'center' }}>
|
||||
<Typography variant="h6" component="h1">
|
||||
{t('select_role_title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
{t('select_role_subtitle')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
<Stack sx={{ gap: 2 }}>
|
||||
{ROLE_OPTIONS.map(({ role, icon }) => {
|
||||
const isSelected = selected === role;
|
||||
return (
|
||||
<Paper
|
||||
key={role}
|
||||
role="radio"
|
||||
aria-checked={isSelected}
|
||||
tabIndex={0}
|
||||
onClick={() => setSelected(role)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') setSelected(role);
|
||||
}}
|
||||
elevation={0}
|
||||
sx={{
|
||||
p: 2,
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 2,
|
||||
border: '2px solid',
|
||||
borderColor: isSelected ? 'primary.main' : 'divider',
|
||||
borderRadius: 2,
|
||||
}}
|
||||
>
|
||||
<AppIcon icon={icon} size={28} color="var(--bal-primary)" />
|
||||
<Stack sx={{ gap: 0.25 }}>
|
||||
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
|
||||
{t(`role_${role}`)}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
{t(`role_${role}_desc`)}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
|
||||
<AppButton
|
||||
color="primary"
|
||||
variant="contained"
|
||||
fullWidth
|
||||
onClick={confirm}
|
||||
disabled={selectRole.isPending}
|
||||
startIcon={selectRole.isPending ? <CircularProgress size={18} color="inherit" /> : undefined}
|
||||
sx={{ m: 0 }}
|
||||
>
|
||||
{t('continue')}
|
||||
</AppButton>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default SelectRole;
|
||||
@@ -0,0 +1,2 @@
|
||||
/** Reading width for the branded auth screens (login, OTP, role selection). */
|
||||
export const AUTH_CARD_MAX_WIDTH = 420;
|
||||
@@ -0,0 +1,4 @@
|
||||
export { default as LoginFlow } from './LoginFlow';
|
||||
export { default as RoleRouter } from './RoleRouter';
|
||||
export { default as SelectRole } from './SelectRole';
|
||||
export { default as AuthSplash } from './AuthSplash';
|
||||
@@ -0,0 +1,48 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useCountdown } from './useCountdown';
|
||||
|
||||
describe('useCountdown', () => {
|
||||
beforeEach(() => jest.useFakeTimers());
|
||||
afterEach(() => jest.useRealTimers());
|
||||
|
||||
it('starts at zero and inactive', () => {
|
||||
const { result } = renderHook(() => useCountdown());
|
||||
expect(result.current.seconds).toBe(0);
|
||||
expect(result.current.isActive).toBe(false);
|
||||
});
|
||||
|
||||
it('counts down one second at a time and stops at zero', () => {
|
||||
const { result } = renderHook(() => useCountdown());
|
||||
act(() => result.current.start(3));
|
||||
expect(result.current.seconds).toBe(3);
|
||||
expect(result.current.isActive).toBe(true);
|
||||
|
||||
act(() => jest.advanceTimersByTime(1000));
|
||||
expect(result.current.seconds).toBe(2);
|
||||
|
||||
act(() => jest.advanceTimersByTime(2000));
|
||||
expect(result.current.seconds).toBe(0);
|
||||
expect(result.current.isActive).toBe(false);
|
||||
|
||||
// No leaked interval keeps decrementing past zero.
|
||||
act(() => jest.advanceTimersByTime(3000));
|
||||
expect(result.current.seconds).toBe(0);
|
||||
});
|
||||
|
||||
it('restarting resets the remaining seconds', () => {
|
||||
const { result } = renderHook(() => useCountdown());
|
||||
act(() => result.current.start(2));
|
||||
act(() => jest.advanceTimersByTime(1000));
|
||||
expect(result.current.seconds).toBe(1);
|
||||
act(() => result.current.start(5));
|
||||
expect(result.current.seconds).toBe(5);
|
||||
});
|
||||
|
||||
it('stop() halts the countdown', () => {
|
||||
const { result } = renderHook(() => useCountdown());
|
||||
act(() => result.current.start(5));
|
||||
act(() => result.current.stop());
|
||||
act(() => jest.advanceTimersByTime(3000));
|
||||
expect(result.current.seconds).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
'use client';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
/**
|
||||
* A one-shot seconds countdown for the OTP resend timer. Exactly one interval runs at a time —
|
||||
* `start(n)` restarts it, it stops itself at zero, and it is cleared on unmount, so no interval
|
||||
* leaks (which would cause re-render storms). State is kept local to the OTP component.
|
||||
*/
|
||||
export function useCountdown() {
|
||||
const [seconds, setSeconds] = useState(0);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
intervalRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const start = useCallback(
|
||||
(from: number) => {
|
||||
stop();
|
||||
const initial = Math.max(0, Math.floor(from));
|
||||
setSeconds(initial);
|
||||
if (initial === 0) return;
|
||||
intervalRef.current = setInterval(() => {
|
||||
setSeconds((prev) => {
|
||||
if (prev <= 1) {
|
||||
stop();
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
},
|
||||
[stop],
|
||||
);
|
||||
|
||||
useEffect(() => stop, [stop]);
|
||||
|
||||
return { seconds, isActive: seconds > 0, start, stop };
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
export const ROUTES = {
|
||||
LOGIN: '/login',
|
||||
// Post-login role picker for a brand-new user whose /me has no public role yet.
|
||||
SELECT_ROLE: '/select-role',
|
||||
|
||||
// Customer (family) app — mobile-first, bottom-tab nav
|
||||
HOME: '/',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export { AuthProvider, useAuth } from './AuthContext';
|
||||
export type { AuthContextValue } from './AuthContext';
|
||||
export { INITIAL_AUTH_STATE } from './types';
|
||||
export type { AuthAction, AuthState } from './types';
|
||||
export type { AuthAction, AuthState, SessionUser } from './types';
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
import type { User } from '@/services/auth/types';
|
||||
import type { AppRole } from '@/constants';
|
||||
|
||||
/**
|
||||
* The session identity the shells need for chrome. `roles` are the coarse actor roles
|
||||
* (customer/nurse/admin) derived from the server's fine-grained role codes via
|
||||
* `toAppRoles`; `id` is optional because verify_otp returns roles but not the id — `/me`
|
||||
* (via useSessionRoleSync) fills it once loaded.
|
||||
*/
|
||||
export interface SessionUser {
|
||||
id?: number;
|
||||
phone: string;
|
||||
roles: AppRole[];
|
||||
}
|
||||
|
||||
export interface AuthState {
|
||||
isAuthenticated: boolean;
|
||||
currentUser?: User;
|
||||
currentUser?: SessionUser;
|
||||
}
|
||||
|
||||
export type AuthAction = { type: 'LOG_IN'; user?: User } | { type: 'LOG_OUT' };
|
||||
export type AuthAction = { type: 'LOG_IN'; user?: SessionUser } | { type: 'LOG_OUT' };
|
||||
|
||||
export const INITIAL_AUTH_STATE: AuthState = {
|
||||
isAuthenticated: false,
|
||||
|
||||
@@ -17,6 +17,11 @@ import { deleteClientCookie, getClientCookie } from '@/lib/cookies/client';
|
||||
import { dispatchToast } from '@/lib/toast/dispatchToast';
|
||||
import { ROUTES } from '@/constants';
|
||||
import { ApiError } from './errors';
|
||||
import { attemptTokenRefresh } from './refresh';
|
||||
|
||||
// Routes that must never trigger the silent-refresh-on-401 retry: the refresh call itself
|
||||
// (a 401 there is terminal reuse/expiry) and the unauthenticated OTP endpoints.
|
||||
const NO_REFRESH_PATHS = ['/auth/refresh', '/auth/request_otp', '/auth/verify_otp'];
|
||||
|
||||
async function parseBody(response: Response): Promise<{ message?: string; code?: string }> {
|
||||
try {
|
||||
@@ -26,7 +31,7 @@ async function parseBody(response: Response): Promise<{ message?: string; code?:
|
||||
}
|
||||
}
|
||||
|
||||
export async function clientFetch<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
export async function clientFetch<T>(path: string, options?: RequestInit, isRetry = false): Promise<T> {
|
||||
const token = getClientCookie(COOKIE_NAMES.ACCESS_TOKEN);
|
||||
const locale = window.location.pathname.split('/')[1] || 'fa';
|
||||
|
||||
@@ -59,6 +64,13 @@ export async function clientFetch<T>(path: string, options?: RequestInit): Promi
|
||||
const { code } = body;
|
||||
|
||||
if (response.status === 401) {
|
||||
// Try one silent refresh + retry before giving up — an expired access token is rotated
|
||||
// transparently so the user keeps their session. Skip for the refresh/OTP endpoints and
|
||||
// never loop (single retry).
|
||||
const refreshEligible = !isRetry && !NO_REFRESH_PATHS.some((p) => path.includes(p));
|
||||
if (refreshEligible && (await attemptTokenRefresh())) {
|
||||
return clientFetch<T>(path, options, true);
|
||||
}
|
||||
deleteClientCookie(COOKIE_NAMES.ACCESS_TOKEN);
|
||||
deleteClientCookie(COOKIE_NAMES.REFRESH_TOKEN);
|
||||
dispatchToast('Session expired. Please log in again.', 'error');
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Silent access-token refresh for the client fetch layer. On a 401, `clientFetch` calls this
|
||||
* once to rotate the token pair (the server does rotation + reuse-detection) and, on success,
|
||||
* retries the original request. A module-level single-flight promise coalesces concurrent 401s
|
||||
* into one refresh so a burst of parallel requests rotates the session exactly once.
|
||||
*
|
||||
* This is deliberately a bare `fetch` (not `clientFetch`, not the `services/auth` client) to
|
||||
* avoid an import cycle — it only shares the token-cookie writers in `@/lib/auth/session`.
|
||||
*/
|
||||
import { API_URL } from '@/config';
|
||||
import { COOKIE_NAMES } from '@/lib/cookies';
|
||||
import { getClientCookie } from '@/lib/cookies/client';
|
||||
import { clearAuthTokens, persistAuthTokens } from '@/lib/auth/session';
|
||||
|
||||
const REFRESH_PATH = '/api/v1/auth/refresh';
|
||||
|
||||
let inFlight: Promise<boolean> | null = null;
|
||||
|
||||
async function doRefresh(): Promise<boolean> {
|
||||
const refreshToken = getClientCookie(COOKIE_NAMES.REFRESH_TOKEN);
|
||||
if (!refreshToken) return false;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}${REFRESH_PATH}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
// 401 here means an unknown/expired/reused (stolen) token — the session is gone.
|
||||
clearAuthTokens();
|
||||
return false;
|
||||
}
|
||||
const envelope = await response.json();
|
||||
const tokens = envelope?.data;
|
||||
if (!tokens?.accessToken || !tokens?.refreshToken) {
|
||||
clearAuthTokens();
|
||||
return false;
|
||||
}
|
||||
persistAuthTokens(tokens);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function attemptTokenRefresh(): Promise<boolean> {
|
||||
if (!inFlight) {
|
||||
inFlight = doRefresh().finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
}
|
||||
return inFlight;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Client-only session token persistence. The single place that writes/clears the auth
|
||||
* cookies via the cookie manager — shared by the `services/auth` hooks and the fetch
|
||||
* layer's silent-refresh path so token storage never diverges.
|
||||
*
|
||||
* Import from client components / hooks / the client fetch layer only (uses the client
|
||||
* cookie manager, which needs `window`). Never from an RSC.
|
||||
*/
|
||||
import { AUTH_ACCESS_COOKIE_OPTIONS, AUTH_REFRESH_COOKIE_OPTIONS, COOKIE_NAMES } from '@/lib/cookies';
|
||||
import { deleteClientCookie, setClientCookie } from '@/lib/cookies/client';
|
||||
|
||||
interface TokenPair {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
export function persistAuthTokens(tokens: TokenPair): void {
|
||||
setClientCookie(COOKIE_NAMES.ACCESS_TOKEN, tokens.accessToken, AUTH_ACCESS_COOKIE_OPTIONS);
|
||||
setClientCookie(COOKIE_NAMES.REFRESH_TOKEN, tokens.refreshToken, AUTH_REFRESH_COOKIE_OPTIONS);
|
||||
}
|
||||
|
||||
export function clearAuthTokens(): void {
|
||||
deleteClientCookie(COOKIE_NAMES.ACCESS_TOKEN);
|
||||
deleteClientCookie(COOKIE_NAMES.REFRESH_TOKEN);
|
||||
}
|
||||
@@ -1,16 +1,63 @@
|
||||
import { clientFetch } from '@/lib/api/client';
|
||||
import type { AuthTokens, LoginDto, User } from '../types';
|
||||
import { unwrap, type ApiEnvelope } from '@/lib/api/types';
|
||||
import { AUTH_API_BASE } from '../constants';
|
||||
import type {
|
||||
AuthApi,
|
||||
AuthTokens,
|
||||
LogoutRequest,
|
||||
Me,
|
||||
OtpRequest,
|
||||
OtpVerify,
|
||||
RefreshRequest,
|
||||
RequestOtpResult,
|
||||
SelectRoleDto,
|
||||
} from '../types';
|
||||
|
||||
export const AuthClientApi = {
|
||||
login: (dto: LoginDto) =>
|
||||
clientFetch<AuthTokens>('/auth/login', {
|
||||
/**
|
||||
* Real HTTP implementation of the AuthApi seam. `clientFetch` returns the raw server
|
||||
* envelope, so each call reads its payload via `unwrap`. Routes are the exact snake_case
|
||||
* paths from the published swagger (`[controller]/[action]` transform).
|
||||
*/
|
||||
export const authClientApi: AuthApi = {
|
||||
requestOtp: async (body: OtpRequest) =>
|
||||
unwrap(
|
||||
await clientFetch<ApiEnvelope<RequestOtpResult>>(`${AUTH_API_BASE}/auth/request_otp`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
),
|
||||
|
||||
verifyOtp: async (body: OtpVerify) =>
|
||||
unwrap(
|
||||
await clientFetch<ApiEnvelope<AuthTokens>>(`${AUTH_API_BASE}/auth/verify_otp`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
),
|
||||
|
||||
refresh: async (body: RefreshRequest) =>
|
||||
unwrap(
|
||||
await clientFetch<ApiEnvelope<AuthTokens>>(`${AUTH_API_BASE}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
),
|
||||
|
||||
// Success is an empty envelope (no `data`) — don't unwrap, just await the revocation.
|
||||
logout: async (body?: LogoutRequest) => {
|
||||
await clientFetch<ApiEnvelope<void>>(`${AUTH_API_BASE}/auth/logout`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(dto),
|
||||
}),
|
||||
body: JSON.stringify(body ?? {}),
|
||||
});
|
||||
},
|
||||
|
||||
logout: () =>
|
||||
clientFetch<void>('/auth/logout', { method: 'POST' }),
|
||||
getMe: async () => unwrap(await clientFetch<ApiEnvelope<Me>>(`${AUTH_API_BASE}/me`)),
|
||||
|
||||
getCurrentUser: () =>
|
||||
clientFetch<User>('/auth/me'),
|
||||
selectRole: async (body: SelectRoleDto) =>
|
||||
unwrap(
|
||||
await clientFetch<ApiEnvelope<Me>>(`${AUTH_API_BASE}/me/select_role`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { USE_AUTH_MOCK } from '../constants';
|
||||
import type { AuthApi } from '../types';
|
||||
import { authClientApi } from './clientApi';
|
||||
import { authMockApi } from './mockApi';
|
||||
|
||||
/**
|
||||
* The selected AuthApi implementation — the single seam every auth hook imports. Selection is
|
||||
* by config (USE_AUTH_MOCK), never by scattered `if (mock)` checks.
|
||||
*/
|
||||
export const authApi: AuthApi = USE_AUTH_MOCK ? authMockApi : authClientApi;
|
||||
@@ -0,0 +1,104 @@
|
||||
import { sleep } from '@/utils';
|
||||
import { ApiError } from '@/lib/api/errors';
|
||||
import { OTP_LOCKED_CODE } from '../constants';
|
||||
import type { AuthApi, AuthTokens, Me, RoleCode } from '../types';
|
||||
|
||||
const MOCK_LATENCY_MS = 400;
|
||||
const DEV_OTP_CODE = '123456';
|
||||
const MAX_WRONG_ATTEMPTS = 3;
|
||||
|
||||
/**
|
||||
* Which `Me` the mock returns, so a developer can exercise all three role-router branches
|
||||
* without a backend. Flip this to `nurse_unverified` or `no_role` while USE_AUTH_MOCK is true.
|
||||
*/
|
||||
type MockScenario = 'customer' | 'nurse_unverified' | 'no_role';
|
||||
const MOCK_SCENARIO: MockScenario = 'customer';
|
||||
|
||||
const SCENARIO_ROLES: Record<MockScenario, RoleCode[]> = {
|
||||
customer: ['customer'],
|
||||
nurse_unverified: ['nurse'],
|
||||
no_role: [],
|
||||
};
|
||||
|
||||
// Mutable so `selectRole` can grant a role to the fresh (`no_role`) user mid-session.
|
||||
let grantedRoles: RoleCode[] = [...SCENARIO_ROLES[MOCK_SCENARIO]];
|
||||
let wrongAttempts = 0;
|
||||
|
||||
function fakeTokens(): AuthTokens {
|
||||
return {
|
||||
// A structurally-valid unsigned JWT with a far-future `exp` so `isTokenAlive`
|
||||
// (middleware / server-seed) accepts it. Payload: { exp: 4102444800 }.
|
||||
accessToken:
|
||||
'eyJhbGciOiJub25lIn0.eyJleHAiOjQxMDI0NDQ4MDB9.',
|
||||
refreshToken: 'mock-refresh-token',
|
||||
accessExpiresAt: '2100-01-01T00:00:00Z',
|
||||
refreshExpiresAt: '2100-01-01T00:00:00Z',
|
||||
isNewUser: grantedRoles.length === 0,
|
||||
roles: grantedRoles,
|
||||
};
|
||||
}
|
||||
|
||||
function currentMe(): Me {
|
||||
return {
|
||||
id: 1,
|
||||
phone: '0912*****00',
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
gender: null,
|
||||
isActive: true,
|
||||
roles: grantedRoles,
|
||||
hasCustomerProfile: false,
|
||||
hasNurseProfile: false,
|
||||
nurseVerificationStatus: 'not_started',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory mock behind the AuthApi seam — the offline fallback for the login flow.
|
||||
* `verifyOtp` accepts the fixed dev code `123456` and locks after MAX_WRONG_ATTEMPTS wrong
|
||||
* tries (reset by requesting a new code), mirroring the real domain 4xx states.
|
||||
*/
|
||||
export const authMockApi: AuthApi = {
|
||||
requestOtp: async () => {
|
||||
await sleep(MOCK_LATENCY_MS);
|
||||
wrongAttempts = 0;
|
||||
return { otpSent: true, resendAvailableInSeconds: 120 };
|
||||
},
|
||||
|
||||
verifyOtp: async ({ code }) => {
|
||||
await sleep(MOCK_LATENCY_MS);
|
||||
if (wrongAttempts >= MAX_WRONG_ATTEMPTS) {
|
||||
throw new ApiError(400, 'Too many attempts. Request a new code.', OTP_LOCKED_CODE);
|
||||
}
|
||||
if (code !== DEV_OTP_CODE) {
|
||||
wrongAttempts += 1;
|
||||
if (wrongAttempts >= MAX_WRONG_ATTEMPTS) {
|
||||
throw new ApiError(400, 'Too many attempts. Request a new code.', OTP_LOCKED_CODE);
|
||||
}
|
||||
throw new ApiError(400, 'The code is incorrect or has expired.');
|
||||
}
|
||||
wrongAttempts = 0;
|
||||
return fakeTokens();
|
||||
},
|
||||
|
||||
refresh: async () => {
|
||||
await sleep(MOCK_LATENCY_MS);
|
||||
return fakeTokens();
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
await sleep(MOCK_LATENCY_MS);
|
||||
grantedRoles = [...SCENARIO_ROLES[MOCK_SCENARIO]];
|
||||
},
|
||||
|
||||
getMe: async () => {
|
||||
await sleep(MOCK_LATENCY_MS);
|
||||
return currentMe();
|
||||
},
|
||||
|
||||
selectRole: async ({ role }) => {
|
||||
await sleep(MOCK_LATENCY_MS);
|
||||
if (!grantedRoles.includes(role)) grantedRoles = [...grantedRoles, role];
|
||||
return currentMe();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Auth domain configuration. The b2 endpoints are live (swagger snapshot published), so
|
||||
* the real client is selected by default; flip USE_AUTH_MOCK to develop the login flow
|
||||
* offline behind the AuthApi seam (see dev/shared-working-context/reports/mocks-registry.md).
|
||||
*/
|
||||
export const USE_AUTH_MOCK = false;
|
||||
|
||||
/** Versioned API base — every auth route is `api/v1/...` per the published swagger. */
|
||||
export const AUTH_API_BASE = '/api/v1';
|
||||
|
||||
/** `/me` is stable within a session; revisiting a screen shouldn't refetch it. */
|
||||
export const AUTH_ME_STALE_TIME = 60_000;
|
||||
|
||||
/**
|
||||
* OTP length. The contract's RequestOtpResult exposes no `code_length`, and the live verify
|
||||
* example uses a 6-digit code, so we default to 6 (a request to surface the length is filed in
|
||||
* frontend/requests/for-backend.md). The wireframe's 4 boxes predate the real 6-digit code.
|
||||
*/
|
||||
export const OTP_CODE_LENGTH = 6;
|
||||
|
||||
/** Fallback resend cooldown (seconds) when a request hasn't yet returned the server value. */
|
||||
export const OTP_RESEND_FALLBACK_SECONDS = 120;
|
||||
|
||||
/**
|
||||
* `ApiError.code` the mock returns after too many wrong codes so the OTP screen can show the
|
||||
* lockout state. The live server sends a 400 with a safe message but no machine-readable code
|
||||
* yet (also filed in for-backend.md) — the screen degrades to the generic invalid-code state.
|
||||
*/
|
||||
export const OTP_LOCKED_CODE = 'otp_locked';
|
||||
@@ -1,11 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { AuthClientApi } from '../apis/clientApi';
|
||||
import { authKeys } from '../keys';
|
||||
|
||||
export function useCurrentUser() {
|
||||
return useQuery({
|
||||
queryKey: authKeys.currentUser(),
|
||||
queryFn: () => AuthClientApi.getCurrentUser(),
|
||||
});
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { AUTH_ACCESS_COOKIE_OPTIONS, AUTH_REFRESH_COOKIE_OPTIONS, COOKIE_NAMES } from '@/lib/cookies';
|
||||
import { setClientCookie } from '@/lib/cookies/client';
|
||||
import { dispatchToast } from '@/lib/toast/dispatchToast';
|
||||
import type { ApiError } from '@/lib/api/errors';
|
||||
import { useAuth } from '@/context/auth';
|
||||
|
||||
import { AuthClientApi } from '../apis/clientApi';
|
||||
import type { LoginDto } from '../types';
|
||||
|
||||
export function useLogin() {
|
||||
const [, dispatch] = useAuth();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (dto: LoginDto) => AuthClientApi.login(dto),
|
||||
onSuccess: (data) => {
|
||||
setClientCookie(COOKIE_NAMES.ACCESS_TOKEN, data.accessToken, AUTH_ACCESS_COOKIE_OPTIONS);
|
||||
setClientCookie(COOKIE_NAMES.REFRESH_TOKEN, data.refreshToken, AUTH_REFRESH_COOKIE_OPTIONS);
|
||||
// Sync AuthContext after a client-side login so the UI reflects the new
|
||||
// session immediately, without waiting for the next full server render.
|
||||
dispatch({ type: 'LOG_IN' });
|
||||
},
|
||||
onError: (error: ApiError) => {
|
||||
dispatchToast(error.message, 'error');
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,25 +1,30 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useLocale } from 'next-intl';
|
||||
|
||||
import { COOKIE_NAMES } from '@/lib/cookies';
|
||||
import { deleteClientCookie } from '@/lib/cookies/client';
|
||||
import { clearAuthTokens } from '@/lib/auth/session';
|
||||
import { ROUTES } from '@/constants';
|
||||
import { useAuth } from '@/context/auth';
|
||||
|
||||
import { AuthClientApi } from '../apis/clientApi';
|
||||
import { authApi } from '../apis';
|
||||
import { authKeys } from '../keys';
|
||||
|
||||
/**
|
||||
* The single logout path: revoke the server session, then (regardless of the call's outcome) clear
|
||||
* both token cookies, reset AuthContext, drop the cached `/me`, and return to login.
|
||||
*/
|
||||
export function useLogout() {
|
||||
const [, dispatch] = useAuth();
|
||||
const router = useRouter();
|
||||
const locale = useLocale();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => AuthClientApi.logout(),
|
||||
mutationFn: () => authApi.logout({}),
|
||||
onSettled: () => {
|
||||
deleteClientCookie(COOKIE_NAMES.ACCESS_TOKEN);
|
||||
deleteClientCookie(COOKIE_NAMES.REFRESH_TOKEN);
|
||||
clearAuthTokens();
|
||||
dispatch({ type: 'LOG_OUT' });
|
||||
queryClient.removeQueries({ queryKey: authKeys.all });
|
||||
router.replace(`/${locale}${ROUTES.LOGIN}`);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useIsAuthenticated } from '@/hooks';
|
||||
|
||||
import { authApi } from '../apis';
|
||||
import { AUTH_ME_STALE_TIME } from '../constants';
|
||||
import { authKeys } from '../keys';
|
||||
|
||||
/**
|
||||
* The signed-in user's identity, roles, and onboarding state — the role router's data source and
|
||||
* the shells' role source. Only runs once authenticated (no `/me` call for a logged-out visitor).
|
||||
*/
|
||||
export function useMe() {
|
||||
const isAuthenticated = useIsAuthenticated();
|
||||
return useQuery({
|
||||
queryKey: authKeys.me(),
|
||||
queryFn: () => authApi.getMe(),
|
||||
enabled: isAuthenticated,
|
||||
staleTime: AUTH_ME_STALE_TIME,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { persistAuthTokens } from '@/lib/auth/session';
|
||||
|
||||
import { authApi } from '../apis';
|
||||
|
||||
/**
|
||||
* Explicitly rotate the token pair (e.g. after selecting a role, whose claim lives inside the
|
||||
* access token). The **automatic** silent refresh on an expired access token is owned by the
|
||||
* fetch layer (`@/lib/api/refresh`); this hook is the on-demand path and shares the same
|
||||
* `persistAuthTokens` writer so token storage never diverges.
|
||||
*/
|
||||
export function useRefresh() {
|
||||
return useMutation({
|
||||
mutationFn: (refreshToken: string) => authApi.refresh({ refreshToken }),
|
||||
onSuccess: (tokens) => persistAuthTokens(tokens),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { authApi } from '../apis';
|
||||
import type { OtpRequest } from '../types';
|
||||
|
||||
/**
|
||||
* Request an OTP for a phone (A1/B1 → A2/B2). Domain 4xx (400 invalid phone, 429 rate-limit)
|
||||
* surface via `mutation.error` for the caller to render inline — 401/403/5xx are already
|
||||
* toasted by the fetch layer, so this hook does not toast.
|
||||
*/
|
||||
export function useRequestOtp() {
|
||||
return useMutation({
|
||||
mutationFn: (body: OtpRequest) => authApi.requestOtp(body),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { COOKIE_NAMES } from '@/lib/cookies';
|
||||
import { getClientCookie } from '@/lib/cookies/client';
|
||||
import { persistAuthTokens } from '@/lib/auth/session';
|
||||
import { useAuth } from '@/context/auth';
|
||||
|
||||
import { authApi } from '../apis';
|
||||
import { authKeys } from '../keys';
|
||||
import { toAppRoles } from '../routing';
|
||||
import type { PublicRole } from '../types';
|
||||
|
||||
/**
|
||||
* Self-assign a public actor role for a brand-new user. Because role claims live inside the access
|
||||
* token, we rotate the token pair after selecting so subsequent role-gated calls carry the new
|
||||
* claim (contract note). AuthContext and the cached `/me` are then updated so the router re-runs
|
||||
* against the new role.
|
||||
*/
|
||||
export function useSelectRole() {
|
||||
const queryClient = useQueryClient();
|
||||
const [, dispatch] = useAuth();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (role: PublicRole) => authApi.selectRole({ role }),
|
||||
onSuccess: async (me) => {
|
||||
const refreshToken = getClientCookie(COOKIE_NAMES.REFRESH_TOKEN);
|
||||
if (refreshToken) {
|
||||
try {
|
||||
persistAuthTokens(await authApi.refresh({ refreshToken }));
|
||||
} catch {
|
||||
// A failed rotation surfaces on the next `/me`/gated call via the fetch layer; the
|
||||
// role is already persisted server-side, so don't block the flow on it.
|
||||
}
|
||||
}
|
||||
dispatch({ type: 'LOG_IN', user: { id: me.id, phone: me.phone, roles: toAppRoles(me.roles) } });
|
||||
queryClient.setQueryData(authKeys.me(), me);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { useAuth } from '@/context/auth';
|
||||
|
||||
import { useMe } from './useMe';
|
||||
import { toAppRoles } from '../routing';
|
||||
|
||||
/**
|
||||
* Hydrate AuthContext with the real roles from `/me` for an already-authenticated session (a
|
||||
* returning user whose server-seeded state only knows `isAuthenticated`). Runs once per `/me`
|
||||
* result — the shells read `currentUser.roles` to pick chrome, so this keeps that single source
|
||||
* of truth fresh without a second role store. Mount it once, high in the authenticated tree.
|
||||
*/
|
||||
export function useSessionRoleSync(): void {
|
||||
const [, dispatch] = useAuth();
|
||||
const { data: me } = useMe();
|
||||
|
||||
useEffect(() => {
|
||||
if (!me) return;
|
||||
dispatch({ type: 'LOG_IN', user: { id: me.id, phone: me.phone, roles: toAppRoles(me.roles) } });
|
||||
}, [me, dispatch]);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { persistAuthTokens } from '@/lib/auth/session';
|
||||
import { useAuth } from '@/context/auth';
|
||||
|
||||
import { authApi } from '../apis';
|
||||
import { authKeys } from '../keys';
|
||||
import { toAppRoles } from '../routing';
|
||||
import type { OtpVerify } from '../types';
|
||||
|
||||
/**
|
||||
* Verify the OTP, then establish the session: persist the token pair, sync AuthContext with the
|
||||
* roles the server returned (so the shells pick chrome immediately), and invalidate `/me` — the
|
||||
* role router's input. The router (rendered on success) then routes to the right app.
|
||||
*
|
||||
* Wrong/expired/lockout codes come back as domain 400s via `mutation.error`; the OTP screen maps
|
||||
* them to inline states. The fetch layer owns 401/403/5xx toasts.
|
||||
*/
|
||||
export function useVerifyOtp() {
|
||||
const [, dispatch] = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (body: OtpVerify) => authApi.verifyOtp(body),
|
||||
onSuccess: (tokens, variables) => {
|
||||
persistAuthTokens(tokens);
|
||||
dispatch({
|
||||
type: 'LOG_IN',
|
||||
user: { phone: variables.phone, roles: toAppRoles(tokens.roles) },
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: authKeys.me() });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
export { useLogin } from './hooks/useLogin';
|
||||
export { useRequestOtp } from './hooks/useRequestOtp';
|
||||
export { useVerifyOtp } from './hooks/useVerifyOtp';
|
||||
export { useMe } from './hooks/useMe';
|
||||
export { useRefresh } from './hooks/useRefresh';
|
||||
export { useLogout } from './hooks/useLogout';
|
||||
export { useCurrentUser } from './hooks/useCurrentUser';
|
||||
export { useSelectRole } from './hooks/useSelectRole';
|
||||
export { useSessionRoleSync } from './hooks/useSessionRoleSync';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const authKeys = {
|
||||
all: ['auth'] as const,
|
||||
currentUser: () => [...authKeys.all, 'me'] as const,
|
||||
me: () => [...authKeys.all, 'me'] as const,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ROUTES } from '@/constants';
|
||||
import { isAdminRole, resolveRoleDestination, toAppRoles } from './routing';
|
||||
import type { RoleCode } from './types';
|
||||
|
||||
describe('toAppRoles', () => {
|
||||
it('collapses all admin sub-roles to the single admin actor', () => {
|
||||
expect(toAppRoles(['support'])).toEqual(['admin']);
|
||||
expect(toAppRoles(['super_admin', 'finance'])).toEqual(['admin']);
|
||||
});
|
||||
|
||||
it('keeps customer and nurse and de-duplicates', () => {
|
||||
expect(toAppRoles(['customer', 'nurse'])).toEqual(['customer', 'nurse']);
|
||||
expect(toAppRoles(['nurse', 'nurse'])).toEqual(['nurse']);
|
||||
});
|
||||
|
||||
it('drops unknown/empty codes', () => {
|
||||
expect(toAppRoles([])).toEqual([]);
|
||||
expect(toAppRoles(['unknown' as RoleCode])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isAdminRole', () => {
|
||||
it('flags every internal admin sub-role', () => {
|
||||
(['admin', 'support', 'finance', 'moderation', 'super_admin'] as RoleCode[]).forEach((role) =>
|
||||
expect(isAdminRole(role)).toBe(true),
|
||||
);
|
||||
});
|
||||
it('does not flag public roles', () => {
|
||||
expect(isAdminRole('customer')).toBe(false);
|
||||
expect(isAdminRole('nurse')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRoleDestination (role-router branches)', () => {
|
||||
it('sends a customer to the family app home', () => {
|
||||
expect(resolveRoleDestination({ roles: ['customer'] })).toBe(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('sends a nurse to the nurse app', () => {
|
||||
expect(resolveRoleDestination({ roles: ['nurse'] })).toBe(ROUTES.NURSE);
|
||||
});
|
||||
|
||||
it('sends a role-less (brand-new) user to role selection', () => {
|
||||
expect(resolveRoleDestination({ roles: [] })).toBe(ROUTES.SELECT_ROLE);
|
||||
});
|
||||
|
||||
it('sends any admin-family role to the admin console', () => {
|
||||
expect(resolveRoleDestination({ roles: ['support'] })).toBe(ROUTES.ADMIN);
|
||||
expect(resolveRoleDestination({ roles: ['customer', 'super_admin'] })).toBe(ROUTES.ADMIN);
|
||||
});
|
||||
|
||||
it('uses the login intent to disambiguate a dual customer+nurse user', () => {
|
||||
expect(resolveRoleDestination({ roles: ['customer', 'nurse'] }, 'nurse')).toBe(ROUTES.NURSE);
|
||||
expect(resolveRoleDestination({ roles: ['customer', 'nurse'] }, 'customer')).toBe(ROUTES.HOME);
|
||||
// Defaults to the family app when no intent is carried.
|
||||
expect(resolveRoleDestination({ roles: ['customer', 'nurse'] })).toBe(ROUTES.HOME);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { APP_ROLES, ROUTES, type AppRole } from '@/constants';
|
||||
import type { Me, RoleCode } from './types';
|
||||
|
||||
const ADMIN_ROLES: RoleCode[] = ['admin', 'support', 'finance', 'moderation', 'super_admin'];
|
||||
|
||||
export function isAdminRole(role: RoleCode): boolean {
|
||||
return ADMIN_ROLES.includes(role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapse the server's fine-grained role codes to the three actor experiences the shells
|
||||
* render. Admin sub-roles all map to the single ADMIN shell; unknown/non-public codes drop out.
|
||||
*/
|
||||
export function toAppRoles(roles: RoleCode[]): AppRole[] {
|
||||
const actors = new Set<AppRole>();
|
||||
for (const role of roles) {
|
||||
if (role === 'customer') actors.add(APP_ROLES.CUSTOMER);
|
||||
else if (role === 'nurse') actors.add(APP_ROLES.NURSE);
|
||||
else if (isAdminRole(role)) actors.add(APP_ROLES.ADMIN);
|
||||
}
|
||||
return [...actors];
|
||||
}
|
||||
|
||||
/**
|
||||
* The locale-less path a signed-in user should land on after auth — the pure core of the role
|
||||
* router (the component just navigates to it). `intendedRole` is the role carried from the login
|
||||
* switch (A1 vs B1); it only disambiguates a user who holds **both** customer and nurse.
|
||||
*
|
||||
* A nurse always routes to the nurse app here; the B3 "verification in progress" landing for an
|
||||
* unverified nurse is f5's job (this only routes correctly, it doesn't render the banner).
|
||||
*/
|
||||
export function resolveRoleDestination(me: Pick<Me, 'roles'>, intendedRole?: AppRole): string {
|
||||
if (me.roles.length === 0) return ROUTES.SELECT_ROLE;
|
||||
if (me.roles.some(isAdminRole)) return ROUTES.ADMIN;
|
||||
|
||||
const hasNurse = me.roles.includes('nurse');
|
||||
const hasCustomer = me.roles.includes('customer');
|
||||
|
||||
let target: AppRole;
|
||||
if (hasNurse && hasCustomer) {
|
||||
target = intendedRole === APP_ROLES.NURSE ? APP_ROLES.NURSE : APP_ROLES.CUSTOMER;
|
||||
} else {
|
||||
target = hasNurse ? APP_ROLES.NURSE : APP_ROLES.CUSTOMER;
|
||||
}
|
||||
|
||||
return target === APP_ROLES.NURSE ? ROUTES.NURSE : ROUTES.HOME;
|
||||
}
|
||||
@@ -1,19 +1,104 @@
|
||||
export interface LoginDto {
|
||||
username: string;
|
||||
password: string;
|
||||
/**
|
||||
* Auth domain — phone-OTP login, revocable refresh-token sessions, `/me`, and public
|
||||
* role selection. Shapes mirror the b2 contract
|
||||
* (`dev/contracts/domains/identity-auth.md` + `dev/contracts/openapi/swagger.v1.json`)
|
||||
* exactly, including the **camelCase** wire casing confirmed against the live envelope.
|
||||
*
|
||||
* Enums cross the wire as stable string codes (money-and-types.md) and are mirrored here
|
||||
* as string-literal unions — never hardcode a display label off a code (labels are i18n keys).
|
||||
*/
|
||||
|
||||
/** Publicly self-selectable roles (customer and nurse may coexist). */
|
||||
export type PublicRole = 'customer' | 'nurse';
|
||||
|
||||
/** Internal-only admin sub-roles — never self-assignable (`me/select_role` → 403). */
|
||||
export type AdminRole = 'admin' | 'support' | 'finance' | 'moderation' | 'super_admin';
|
||||
|
||||
/** Any role code the server may report on a session. */
|
||||
export type RoleCode = PublicRole | AdminRole;
|
||||
|
||||
/** Load-bearing for same-gender matching; null until the profile flow (b3) sets it. */
|
||||
export type Gender = 'male' | 'female';
|
||||
|
||||
/** Nurse verification stage. `not_started` until the b6 pipeline exists. */
|
||||
export type NurseVerificationStatus =
|
||||
| 'not_started'
|
||||
| 'in_progress'
|
||||
| 'pending_review'
|
||||
| 'verified'
|
||||
| 'rejected';
|
||||
|
||||
/** `POST auth/request_otp` body. The server accepts +98/0098/Persian digits and normalizes. */
|
||||
export interface OtpRequest {
|
||||
phone: string;
|
||||
}
|
||||
|
||||
/** `POST auth/request_otp` payload. Inside the resend window `otpSent` is false with the remaining seconds. */
|
||||
export interface RequestOtpResult {
|
||||
otpSent: boolean;
|
||||
resendAvailableInSeconds: number;
|
||||
}
|
||||
|
||||
/** `POST auth/verify_otp` body. */
|
||||
export interface OtpVerify {
|
||||
phone: string;
|
||||
code: string;
|
||||
deviceInfo?: string;
|
||||
}
|
||||
|
||||
/** `POST auth/refresh` body — the refresh token is itself the credential. */
|
||||
export interface RefreshRequest {
|
||||
refreshToken: string;
|
||||
deviceInfo?: string;
|
||||
}
|
||||
|
||||
/** `POST auth/logout` body. Omitting `refreshToken` (or `everywhere: true`) revokes every session. */
|
||||
export interface LogoutRequest {
|
||||
refreshToken?: string;
|
||||
everywhere?: boolean;
|
||||
}
|
||||
|
||||
/** `AuthTokensResult` — returned by verify_otp and refresh. */
|
||||
export interface AuthTokens {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
accessExpiresAt: string;
|
||||
refreshExpiresAt: string;
|
||||
/** `true` only on the first successful verify for a phone ⇒ send to role selection. */
|
||||
isNewUser: boolean;
|
||||
/** Active roles; empty ⇒ route the user to role selection. */
|
||||
roles: RoleCode[];
|
||||
}
|
||||
|
||||
import type { AppRole } from '@/constants';
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
// Populated by the server in f1-b2. Optional until then; the shell defaults to
|
||||
// the customer experience when roles are absent (see useActorRole).
|
||||
roles?: AppRole[];
|
||||
/** `POST me/select_role` body. Only public roles are accepted. */
|
||||
export interface SelectRoleDto {
|
||||
role: PublicRole;
|
||||
}
|
||||
|
||||
/** `MeResult` — the role router's input and the shell's role source. */
|
||||
export interface Me {
|
||||
id: number;
|
||||
/** Always masked by the server (`0912*****33`); the full number is never returned. */
|
||||
phone: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
gender: Gender | null;
|
||||
isActive: boolean;
|
||||
roles: RoleCode[];
|
||||
hasCustomerProfile: boolean;
|
||||
hasNurseProfile: boolean;
|
||||
nurseVerificationStatus: NurseVerificationStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* The auth domain's API seam. The real HTTP client and the in-memory mock both implement
|
||||
* this interface; selection is by config (`USE_AUTH_MOCK`), never scattered `if (mock)` checks.
|
||||
*/
|
||||
export interface AuthApi {
|
||||
requestOtp(body: OtpRequest): Promise<RequestOtpResult>;
|
||||
verifyOtp(body: OtpVerify): Promise<AuthTokens>;
|
||||
refresh(body: RefreshRequest): Promise<AuthTokens>;
|
||||
logout(body?: LogoutRequest): Promise<void>;
|
||||
getMe(): Promise<Me>;
|
||||
selectRole(body: SelectRoleDto): Promise<Me>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user