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,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();
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user