feat(market): login and registration flow
- auth-flow store: the number, code timing, misses, block, registration token and step-4 draft, in memory only (never URL, cookie or storage). - Auth repository maps the gateway's English error text to codes and Persian copy (AUTH_ERROR_CODES, AUTH_ERROR_COPY, blockEndOf). - Actions: sendCode, verifyRegistrationCode; login turns a suspended account away and closes its session; register actions reset the flow and creator registration reports upload progress and can be cancelled. - Models: shared code step (wrong/expired codes, 3-miss block, resend), login, login verify (landing per role and unfinished creator profile), registration type, phone, verify and details (token warning and halt, investor and creator parts). - Screens under (auth): support entry, code step, login, login verify with the suspended notice, registration progress and steps 1-4. - Navigation: auth routes, withReturnPath and useAuthRoutes; GuestGuard keeps the page through its own sign-in. - Shared: valibot auth schemas (phone, code, names, username, national ID, ID card image), showActionError, applyServerErrors, translateMessage, mobile helpers, and the `auth` locale namespace. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
025c68dd0d
commit
d43e74237f
|
|
@ -1,27 +1,33 @@
|
|||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { useViewerStatus } from '../../../stores/auth';
|
||||
import { safeReturnPath } from '../../navigation';
|
||||
import type { GuestGuardProps } from './types';
|
||||
|
||||
/**
|
||||
* Wraps login and registration. A signed-in visitor goes on to `?redirect=` (a path on this site
|
||||
* only) or home; a guest sees the page. The skeleton covers the moment before the viewer is known.
|
||||
* Wraps login and registration, which render only in the browser. A visitor who arrives signed in
|
||||
* goes on to `?redirect=` (a path on this site only) or home; a guest sees the page. The skeleton
|
||||
* covers the moment before the viewer is known. A guest who signs in on the page keeps it: the
|
||||
* page shows its progress and sends them on itself.
|
||||
*/
|
||||
export function GuestGuard({ fallback, children }: GuestGuardProps) {
|
||||
const status = useViewerStatus();
|
||||
const router = useRouter();
|
||||
const [wasGuest, setWasGuest] = useState(false);
|
||||
// Remembered during render, so the render that turns member already knows.
|
||||
if (status === 'guest' && !wasGuest) setWasGuest(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (status !== 'member') return;
|
||||
if (status !== 'member' || wasGuest) return;
|
||||
const redirect = new URLSearchParams(window.location.search).get(
|
||||
'redirect',
|
||||
);
|
||||
router.replace(safeReturnPath(redirect));
|
||||
}, [status, router]);
|
||||
}, [status, wasGuest, router]);
|
||||
|
||||
return status === 'guest' ? children : fallback;
|
||||
const showsPage = status === 'guest' || (status === 'member' && wasGuest);
|
||||
return showsPage ? children : fallback;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
import { useSearchParams } from 'next/navigation';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import type { SignedInViewer } from '../../../features/auth';
|
||||
import { ROUTES, withReturnPath } from '../navigation';
|
||||
import { safeReturnPath } from '../return-path';
|
||||
import type { AuthRoutes } from '../types';
|
||||
|
||||
/**
|
||||
* Every login and registration step's path, each keeping `?redirect=`, and where a person lands
|
||||
* once signed in. Browser only: the auth pages render their steps in the browser.
|
||||
*/
|
||||
export function useAuthRoutes(): AuthRoutes {
|
||||
const redirect = useSearchParams().get('redirect');
|
||||
|
||||
return useMemo(() => {
|
||||
const step = (path: string) => withReturnPath(path, redirect);
|
||||
return {
|
||||
login: step(ROUTES.login),
|
||||
loginVerify: step(ROUTES.loginVerify),
|
||||
register: {
|
||||
type: step(ROUTES.register.type),
|
||||
phone: step(ROUTES.register.phone),
|
||||
verify: step(ROUTES.register.verify),
|
||||
details: step(ROUTES.register.details),
|
||||
},
|
||||
profile: {
|
||||
investor: step(ROUTES.onboarding.investorProfile),
|
||||
creator: step(ROUTES.onboarding.creatorProfile),
|
||||
},
|
||||
landing: ({ role, username, needsProfile }: SignedInViewer) => {
|
||||
if (needsProfile) return step(ROUTES.onboarding.creatorProfile);
|
||||
if (redirect) return safeReturnPath(redirect);
|
||||
return role === 'creator' ? ROUTES.channel(username) : ROUTES.home;
|
||||
},
|
||||
};
|
||||
}, [redirect]);
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
export { CHANNEL_PREFIX } from './constants';
|
||||
export { loginRoute, ROUTES } from './navigation';
|
||||
export { useAuthRoutes } from './hooks/use-auth-routes';
|
||||
export { loginRoute, ROUTES, withReturnPath } from './navigation';
|
||||
export { safeReturnPath } from './return-path';
|
||||
export type { AuthRoutes } from './types';
|
||||
|
|
|
|||
|
|
@ -7,6 +7,13 @@ const channel = (username: string) =>
|
|||
export const ROUTES = {
|
||||
home: '/',
|
||||
login: '/auth/login',
|
||||
loginVerify: '/auth/login/verify',
|
||||
register: {
|
||||
type: '/auth/register',
|
||||
phone: '/auth/register/phone',
|
||||
verify: '/auth/register/verify',
|
||||
details: '/auth/register/details',
|
||||
},
|
||||
account: '/account',
|
||||
channel,
|
||||
post: (username: string, id: string) =>
|
||||
|
|
@ -34,7 +41,16 @@ export const ROUTES = {
|
|||
|
||||
/** `/auth/login?redirect=…`: auth returns to the page that asked for it. */
|
||||
export function loginRoute(returnTo?: string): string {
|
||||
return returnTo
|
||||
? `${ROUTES.login}?redirect=${encodeURIComponent(returnTo)}`
|
||||
: ROUTES.login;
|
||||
return withReturnPath(ROUTES.login, returnTo);
|
||||
}
|
||||
|
||||
/**
|
||||
* An auth step's path that keeps `?redirect=`, so every step of login and registration returns
|
||||
* to the page that asked for it.
|
||||
*/
|
||||
export function withReturnPath(
|
||||
path: string,
|
||||
returnTo: string | null | undefined,
|
||||
): string {
|
||||
return returnTo ? `${path}?redirect=${encodeURIComponent(returnTo)}` : path;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,16 @@
|
|||
import type { SignedInViewer } from '../../features/auth';
|
||||
|
||||
/** The auth steps' paths with `?redirect=` kept, and where a signed-in person lands. */
|
||||
export type AuthRoutes = {
|
||||
login: string;
|
||||
loginVerify: string;
|
||||
register: {
|
||||
type: string;
|
||||
phone: string;
|
||||
verify: string;
|
||||
details: string;
|
||||
};
|
||||
/** Registration step 5, per account type. */
|
||||
profile: { investor: string; creator: string };
|
||||
landing: (viewer: SignedInViewer) => string;
|
||||
};
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Link } from '@lumina/island/atoms/link';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import type { FormEvent } from 'react';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useLoginPage } from '../../../../../../../features/auth';
|
||||
import { translateMessage } from '../../../../../../../shared/utils';
|
||||
import { useAuthRoutes } from '../../../../../../navigation';
|
||||
import { SupportEntry } from '../../../../organisms/support-entry';
|
||||
import type { LoginStepProps } from './types';
|
||||
|
||||
/**
|
||||
* Login step 1: the mobile number and «دریافت کد» right under it, the way to registration, and
|
||||
* support. A number with no account gets the way to register with it under the field.
|
||||
*/
|
||||
export function LoginStep({ size, supportPlacement }: LoginStepProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const routes = useAuthRoutes();
|
||||
const {
|
||||
form,
|
||||
submit,
|
||||
isSubmitting,
|
||||
formError,
|
||||
isUnknownPhone,
|
||||
registerHref,
|
||||
carryPhone,
|
||||
} = useLoginPage({
|
||||
codeHref: routes.loginVerify,
|
||||
registerHref: routes.register.type,
|
||||
});
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
|
||||
{formError && (
|
||||
<Banner tone="danger" title={t('phone.send-failed-banner')}>
|
||||
{formError}
|
||||
</Banner>
|
||||
)}
|
||||
<FlexBox direction="flex-col" className="gap-1.5">
|
||||
<Typography tag="h1" variant="heading-md">
|
||||
{t('login.title')}
|
||||
</Typography>
|
||||
<Typography color="secondary">{t('login.description')}</Typography>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
direction="flex-col"
|
||||
gap="gap-5"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-1">
|
||||
<Controller
|
||||
name="phone"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
inputMode="numeric"
|
||||
autoComplete="tel"
|
||||
label={t('phone.label')}
|
||||
placeholder={t('phone.placeholder')}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
className="w-full"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{isUnknownPhone && (
|
||||
<Link
|
||||
href={registerHref}
|
||||
onClick={carryPhone}
|
||||
icon="arrow-left"
|
||||
standalone
|
||||
>
|
||||
{t('login.register-with-phone')}
|
||||
</Link>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size={size}
|
||||
block
|
||||
isLoading={isSubmitting}
|
||||
>
|
||||
{t('login.submit')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-center"
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Typography tag="span" variant="body-sm" color="secondary">
|
||||
{t('login.no-account')}
|
||||
</Typography>
|
||||
<Link href={registerHref} onClick={carryPhone}>
|
||||
{t('login.register')}
|
||||
</Link>
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-center" className="mt-auto">
|
||||
<SupportEntry trigger="link" placement={supportPlacement} />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { LoginStep } from './LoginStep';
|
||||
export type { LoginStepProps } from './types';
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { SupportEntryProps } from '../../../../organisms/support-entry';
|
||||
|
||||
export type LoginStepProps = {
|
||||
/** `lg` on mobile, `md` on desktop. */
|
||||
size: 'md' | 'lg';
|
||||
supportPlacement: SupportEntryProps['placement'];
|
||||
};
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
'use client';
|
||||
|
||||
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useLoginVerifyPage } from '../../../../../../../../features/auth';
|
||||
import { useAuthRoutes } from '../../../../../../../navigation';
|
||||
import { CodeStep } from '../../../../organisms/code-step';
|
||||
import { SuspendedNotice } from './components/SuspendedNotice';
|
||||
import type { LoginVerifyStepProps } from './types';
|
||||
|
||||
/**
|
||||
* Login step 2: the code, then the person lands where they were going. A suspended account sees
|
||||
* the suspended screen here instead. Without a number (after a reload) it waits in its skeleton
|
||||
* while the model sends the person back to the number step.
|
||||
*/
|
||||
export function LoginVerifyStep({
|
||||
size,
|
||||
supportPlacement,
|
||||
}: LoginVerifyStepProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const routes = useAuthRoutes();
|
||||
const model = useLoginVerifyPage({
|
||||
phoneHref: routes.login,
|
||||
landing: routes.landing,
|
||||
});
|
||||
|
||||
if (model.view === 'suspended') {
|
||||
return <SuspendedNotice size={size} supportPlacement={supportPlacement} />;
|
||||
}
|
||||
if (!model.phone) {
|
||||
return <SkeletonPreset preset="form" label={t('loading')} />;
|
||||
}
|
||||
return (
|
||||
<CodeStep
|
||||
model={model}
|
||||
submitLabel={t('login.verify-submit')}
|
||||
editHref={routes.login}
|
||||
size={size}
|
||||
supportPlacement={supportPlacement}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
'use client';
|
||||
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { StateArt } from '@lumina/island/atoms/state-art';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { SupportEntry } from '../../../../../../organisms/support-entry';
|
||||
import type { SuspendedNoticeProps } from '../types';
|
||||
|
||||
/**
|
||||
* A valid code for a suspended account: no session, nothing else reachable, one way out to
|
||||
* support. Amber, because a suspension is a state, not an error. It replaces the code step, so
|
||||
* focus moves to its heading. The API gives no reason yet.
|
||||
*/
|
||||
export function SuspendedNotice({
|
||||
size,
|
||||
supportPlacement,
|
||||
}: SuspendedNoticeProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
|
||||
useEffect(() => headingRef.current?.focus(), []);
|
||||
|
||||
return (
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
alignItems="items-center"
|
||||
gap="gap-4"
|
||||
className="pt-6 text-center"
|
||||
>
|
||||
<StateArt icon="ban" tone="warning" />
|
||||
<FlexBox direction="flex-col" alignItems="items-center" gap="gap-2">
|
||||
<Typography
|
||||
ref={headingRef}
|
||||
tabIndex={-1}
|
||||
tag="h1"
|
||||
variant="heading-md"
|
||||
className="outline-none"
|
||||
>
|
||||
{t('suspended.title')}
|
||||
</Typography>
|
||||
<Typography color="secondary">{t('suspended.description')}</Typography>
|
||||
</FlexBox>
|
||||
<FlexBox direction="flex-col" className="mt-2 w-full">
|
||||
<SupportEntry
|
||||
trigger="button"
|
||||
placement={supportPlacement}
|
||||
size={size}
|
||||
/>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { LoginVerifyStep } from './LoginVerifyStep';
|
||||
export type { LoginVerifyStepProps } from './types';
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import type { SupportEntryProps } from '../../../../../organisms/support-entry';
|
||||
|
||||
export type LoginVerifyStepProps = {
|
||||
/** `lg` on mobile, `md` on desktop. */
|
||||
size: 'md' | 'lg';
|
||||
supportPlacement: SupportEntryProps['placement'];
|
||||
};
|
||||
|
||||
export type SuspendedNoticeProps = LoginVerifyStepProps;
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Link } from '@lumina/island/atoms/link';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import { OtpInput } from '@lumina/island/molecules/otp-input';
|
||||
import { ResendCode } from '@lumina/island/molecules/resend-code';
|
||||
import type { FormEvent } from 'react';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { formatMobile, translateMessage } from '../../../../../../shared/utils';
|
||||
import { SupportEntry } from '../../../organisms/support-entry';
|
||||
import type { CodeStepProps } from './types';
|
||||
|
||||
/**
|
||||
* The 6-digit code step of login and registration: the number it went to, the cells, the resend
|
||||
* wait and the submit button under them. Blocked, the cells and the button rest and the wait
|
||||
* counts to the moment a new code may be asked for; «ویرایش شماره» stays live.
|
||||
*/
|
||||
export function CodeStep({
|
||||
model,
|
||||
submitLabel,
|
||||
editHref,
|
||||
size,
|
||||
supportPlacement,
|
||||
progress,
|
||||
}: CodeStepProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const { form, status, attempt, submit, complete, resend } = model;
|
||||
const isBlocked = status === 'blocked';
|
||||
const formError = form.formState.errors.root?.server?.message;
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
|
||||
{isBlocked && (
|
||||
<Banner tone="warning" title={t('code.blocked-title')}>
|
||||
{t('code.blocked-description')}
|
||||
</Banner>
|
||||
)}
|
||||
{formError && !isBlocked && <Banner tone="danger">{formError}</Banner>}
|
||||
{progress}
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
alignItems="items-start"
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Typography tag="h1" variant="heading-md">
|
||||
{t('code.title')}
|
||||
</Typography>
|
||||
<Typography color="secondary">
|
||||
{t('code.description', {
|
||||
// Isolated left to right inside the sentence.
|
||||
phone: `${formatMobile(model.phone ?? '')}`,
|
||||
})}
|
||||
</Typography>
|
||||
<Link href={editHref} iconStart="edit" standalone>
|
||||
{t('code.edit-phone')}
|
||||
</Link>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
direction="flex-col"
|
||||
gap="gap-5"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<Controller
|
||||
name="code"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<OtpInput
|
||||
// A new key empties the cells' own state and focuses the first cell again.
|
||||
key={attempt}
|
||||
name={field.name}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onComplete={complete}
|
||||
label={t('code.label')}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
status={status === 'verifying' ? 'verifying' : 'idle'}
|
||||
disabled={isBlocked || status === 'verifying'}
|
||||
// The step exists to type the code, so focus starts in the cells.
|
||||
// oxlint-disable-next-line jsx-a11y/no-autofocus
|
||||
autoFocus
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<FlexBox justifyContent="justify-center">
|
||||
<ResendCode
|
||||
// A new code (or block) starts a new wait, and its announcement plays again.
|
||||
key={resend.endsAt}
|
||||
endsAt={resend.endsAt}
|
||||
status={
|
||||
resend.phase === 'auto'
|
||||
? isBlocked
|
||||
? 'limited'
|
||||
: 'auto'
|
||||
: resend.phase
|
||||
}
|
||||
onResend={resend.onResend}
|
||||
labels={{
|
||||
counting: t('code.resend.counting'),
|
||||
ready: t('code.resend.ready'),
|
||||
sending: t('code.resend.sending'),
|
||||
sent: t('code.resend.sent'),
|
||||
limited: t('code.resend.limited'),
|
||||
hint: t('code.resend.hint'),
|
||||
readyAnnouncement: t('code.resend.ready-announcement'),
|
||||
}}
|
||||
/>
|
||||
</FlexBox>
|
||||
{!isBlocked && (
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size={size}
|
||||
block
|
||||
isLoading={status === 'verifying'}
|
||||
>
|
||||
{submitLabel}
|
||||
</Button>
|
||||
)}
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-center" className="mt-auto">
|
||||
<SupportEntry trigger="link" placement={supportPlacement} />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { CodeStep } from './CodeStep';
|
||||
export type { CodeStepProps } from './types';
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import type { ReactNode } from 'react';
|
||||
|
||||
import type { CodeStepModel } from '../../../../../../features/auth';
|
||||
import type { SupportEntryProps } from '../../../organisms/support-entry';
|
||||
|
||||
export type CodeStepProps = {
|
||||
/** The page model's code step (`useCodeStep`). */
|
||||
model: CodeStepModel;
|
||||
/** «ورود» for login, «تأیید و ادامه» for registration. */
|
||||
submitLabel: string;
|
||||
/** «ویرایش شماره»: back to the number step, which keeps the number. */
|
||||
editHref: string;
|
||||
/** `lg` on mobile, `md` on desktop. */
|
||||
size: 'md' | 'lg';
|
||||
supportPlacement: SupportEntryProps['placement'];
|
||||
/** Registration's step bar, above the heading. */
|
||||
progress?: ReactNode;
|
||||
};
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
'use client';
|
||||
|
||||
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useRegisterDetailsPage } from '../../../../../../../../features/auth';
|
||||
import { useAuthRoutes } from '../../../../../../../navigation';
|
||||
import { CreatorIdentityForm } from './components/CreatorIdentityForm';
|
||||
import { InvestorDetailsForm } from './components/InvestorDetailsForm';
|
||||
import type { RegisterDetailsStepProps } from './types';
|
||||
|
||||
/**
|
||||
* Registration step 4, on the 15-minute token: account details for an investor, identity for a
|
||||
* creator. There is no back: the code is used. Without a token (after a reload) it waits in its
|
||||
* skeleton while the page sends the person back to the number.
|
||||
*/
|
||||
export function RegisterDetailsStep(props: RegisterDetailsStepProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const routes = useAuthRoutes();
|
||||
const page = useRegisterDetailsPage({
|
||||
phoneHref: routes.register.phone,
|
||||
codeHref: routes.register.verify,
|
||||
});
|
||||
|
||||
if (!page.role || page.expiresAt === null) {
|
||||
return <SkeletonPreset preset="form" count={3} label={t('loading')} />;
|
||||
}
|
||||
const partOptions = {
|
||||
profileHref: routes.profile[page.role],
|
||||
onExpired: page.expire,
|
||||
};
|
||||
return page.role === 'creator' ? (
|
||||
<CreatorIdentityForm {...props} page={page} partOptions={partOptions} />
|
||||
) : (
|
||||
<InvestorDetailsForm {...props} page={page} partOptions={partOptions} />
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,195 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { FileField } from '@lumina/island/molecules/file-field';
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { number } from '@lumina/tools/format';
|
||||
import { useId } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useCreatorIdentityPart } from '../../../../../../../../../features/auth';
|
||||
import type { IdCardSide } from '../../../../../../../../../features/auth';
|
||||
import { translateMessage } from '../../../../../../../../../shared/utils';
|
||||
import { ID_CARD_IMAGE } from '../../../../../../../../../shared/validations';
|
||||
import type { DetailsFormProps } from '../types';
|
||||
import { DetailsFrame } from './DetailsFrame';
|
||||
import { NameFields } from './NameFields';
|
||||
import { TermsLine } from './TermsLine';
|
||||
import { UsernameField } from './UsernameField';
|
||||
|
||||
const ID_CARD_SIDES = [
|
||||
{ side: 'idCardFront', label: 'id-card-front' },
|
||||
{ side: 'idCardBack', label: 'id-card-back' },
|
||||
] as const satisfies readonly { side: IdCardSide; label: string }[];
|
||||
|
||||
const BYTES_PER_MB = 1024 * 1024;
|
||||
|
||||
/** A labelled group with its privacy line: what investors see, and what only the review sees. */
|
||||
function Group({
|
||||
title,
|
||||
note,
|
||||
noteIcon,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
note: string;
|
||||
noteIcon?: 'lock';
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const titleId = useId();
|
||||
return (
|
||||
<FlexBox
|
||||
tag="section"
|
||||
aria-labelledby={titleId}
|
||||
direction="flex-col"
|
||||
gap="gap-4"
|
||||
>
|
||||
<FlexBox direction="flex-col" gap="gap-1">
|
||||
<Typography tag="h2" variant="heading-sm" id={titleId}>
|
||||
{title}
|
||||
</Typography>
|
||||
<FlexBox alignItems="items-center" gap="gap-1">
|
||||
{noteIcon && (
|
||||
<Icon
|
||||
name={noteIcon}
|
||||
size={16}
|
||||
className="flex-none text-text-secondary"
|
||||
/>
|
||||
)}
|
||||
<Typography tag="span" variant="body-sm" color="secondary">
|
||||
{note}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
{children}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 4 for a creator: the public username, then the private identity (names, national code,
|
||||
* both sides of the ID card) for the admin review. The images upload with a bar and can be
|
||||
* cancelled; a failure keeps every value and image.
|
||||
*/
|
||||
export function CreatorIdentityForm(props: DetailsFormProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const {
|
||||
form,
|
||||
submit,
|
||||
isSubmitting,
|
||||
formError,
|
||||
pickImage,
|
||||
progress,
|
||||
cancelUpload,
|
||||
draft,
|
||||
} = useCreatorIdentityPart(props.partOptions);
|
||||
|
||||
return (
|
||||
<DetailsFrame
|
||||
{...props}
|
||||
title={t('register.identity.title')}
|
||||
description={t('register.identity.description')}
|
||||
formError={formError}
|
||||
draft={draft}
|
||||
onSubmit={() => void submit()}
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size={props.size}
|
||||
block
|
||||
isLoading={isSubmitting}
|
||||
>
|
||||
{t('register.identity.submit')}
|
||||
</Button>
|
||||
{progress !== undefined && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={props.size}
|
||||
block
|
||||
onClick={cancelUpload}
|
||||
>
|
||||
{t('register.identity.cancel')}
|
||||
</Button>
|
||||
)}
|
||||
<TermsLine before={t('register.identity.terms-before')} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Group
|
||||
title={t('register.identity.public-title')}
|
||||
note={t('register.identity.public-description')}
|
||||
>
|
||||
<UsernameField
|
||||
control={form.control}
|
||||
name="username"
|
||||
placeholder="ali_trader"
|
||||
hint={t('register.identity.username-note')}
|
||||
/>
|
||||
</Group>
|
||||
<Group
|
||||
title={t('register.identity.private-title')}
|
||||
note={t('register.identity.private-description')}
|
||||
noteIcon="lock"
|
||||
>
|
||||
<NameFields control={form.control} isPaired={props.size === 'md'} />
|
||||
<Controller
|
||||
name="nationalId"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
dir="ltr"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
maxLength={10}
|
||||
label={t('register.fields.national-id')}
|
||||
placeholder={t('register.fields.national-id-placeholder')}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{ID_CARD_SIDES.map(({ side, label }) => (
|
||||
<Controller
|
||||
key={side}
|
||||
name={side}
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<FileField
|
||||
name={field.name}
|
||||
file={field.value}
|
||||
onChange={(file) => pickImage(side, file)}
|
||||
onBlur={field.onBlur}
|
||||
accept={ID_CARD_IMAGE.types.join(',')}
|
||||
label={t(`register.fields.${label}`)}
|
||||
hint={t('register.fields.id-card-hint')}
|
||||
size={
|
||||
field.value &&
|
||||
t('register.fields.file-size', {
|
||||
size: number(field.value.size / BYTES_PER_MB, 1),
|
||||
})
|
||||
}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
progress={progress}
|
||||
disabled={isSubmitting}
|
||||
labels={{
|
||||
pick: t('register.fields.id-card-pick'),
|
||||
rules: t('register.fields.id-card-rules'),
|
||||
remove: t('register.fields.id-card-remove'),
|
||||
uploading: (percent) =>
|
||||
t('register.fields.id-card-uploading', { percent }),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</Group>
|
||||
</DetailsFrame>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
'use client';
|
||||
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import type { FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { SupportEntry } from '../../../../../../organisms/support-entry';
|
||||
import { RegisterProgress } from '../../../../organisms/register-progress';
|
||||
import type { DetailsFrameProps } from '../types';
|
||||
import { ExpiryHalt } from './ExpiryHalt';
|
||||
import { ExpiryWarning } from './ExpiryWarning';
|
||||
|
||||
/**
|
||||
* What both account types' step 4 share: the token's warning and halt, the server-failure banner,
|
||||
* the step bar and heading, the form with its submit under the fields, and support.
|
||||
*/
|
||||
export function DetailsFrame({
|
||||
page,
|
||||
title,
|
||||
description,
|
||||
formError,
|
||||
footer,
|
||||
draft,
|
||||
onSubmit,
|
||||
supportPlacement,
|
||||
haltPlacement,
|
||||
children,
|
||||
}: DetailsFrameProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
|
||||
{page.phase === 'warning' && page.expiresAt !== null && (
|
||||
<ExpiryWarning expiresAt={page.expiresAt} />
|
||||
)}
|
||||
{formError && (
|
||||
<Banner tone="danger" title={t('register.details.network-title')}>
|
||||
{formError}
|
||||
</Banner>
|
||||
)}
|
||||
<RegisterProgress current={3} role={page.role} />
|
||||
<FlexBox direction="flex-col" className="gap-1.5">
|
||||
<Typography tag="h1" variant="heading-md">
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography color="secondary">{description}</Typography>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
direction="flex-col"
|
||||
gap="gap-6"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
onSubmit();
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
{footer}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-center" className="mt-auto">
|
||||
<SupportEntry trigger="link" placement={supportPlacement} />
|
||||
</FlexBox>
|
||||
{page.phase === 'expired' && (
|
||||
<ExpiryHalt
|
||||
placement={haltPlacement}
|
||||
isSending={page.isReverifying}
|
||||
onConfirm={() => page.reverify(draft())}
|
||||
/>
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { Modal } from '@lumina/island/molecules/modal';
|
||||
import { Sheet } from '@lumina/island/molecules/sheet';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { ExpiryHaltProps } from '../types';
|
||||
|
||||
/**
|
||||
* The registration token ran out: a blocking halt with no ✕ and no cancel. The one way on is a
|
||||
* new code to the same number; after it, step 4 comes back with everything typed.
|
||||
*/
|
||||
export function ExpiryHalt({
|
||||
placement,
|
||||
isSending,
|
||||
onConfirm,
|
||||
}: ExpiryHaltProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const title = t('register.expiry.title');
|
||||
const description = t('register.expiry.description');
|
||||
const button = (
|
||||
<Button
|
||||
variant="primary"
|
||||
size={placement === 'sheet' ? 'lg' : 'md'}
|
||||
block
|
||||
isLoading={isSending}
|
||||
onClick={onConfirm}
|
||||
>
|
||||
{t('register.expiry.submit')}
|
||||
</Button>
|
||||
);
|
||||
|
||||
return placement === 'sheet' ? (
|
||||
<Sheet open title={title} dismissible={false} alert footer={button}>
|
||||
{description}
|
||||
</Sheet>
|
||||
) : (
|
||||
<Modal open title={title} dismissible={false} alert actions={button}>
|
||||
{description}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
'use client';
|
||||
|
||||
import { Countdown } from '@lumina/island/atoms/countdown';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { ExpiryWarningProps } from '../types';
|
||||
|
||||
/**
|
||||
* Two minutes before the registration token runs out. Announced once (the banner's status
|
||||
* role), never every second: the clock inside is not a live region.
|
||||
*/
|
||||
export function ExpiryWarning({ expiresAt }: ExpiryWarningProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
|
||||
return (
|
||||
<Banner
|
||||
tone="warning"
|
||||
icon="clock"
|
||||
title={t('register.expiry.warning-title')}
|
||||
>
|
||||
{t('register.expiry.warning-before')}{' '}
|
||||
<Countdown kind="otp" endsAt={expiresAt} />{' '}
|
||||
{t('register.expiry.warning-after')}
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useInvestorDetailsPart } from '../../../../../../../../../features/auth';
|
||||
import type { DetailsFormProps } from '../types';
|
||||
import { DetailsFrame } from './DetailsFrame';
|
||||
import { NameFields } from './NameFields';
|
||||
import { TermsLine } from './TermsLine';
|
||||
import { UsernameField } from './UsernameField';
|
||||
|
||||
/** Step 4 for an investor: name, last name and username, then «ساخت حساب». */
|
||||
export function InvestorDetailsForm(props: DetailsFormProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const { form, submit, isSubmitting, formError, draft } =
|
||||
useInvestorDetailsPart(props.partOptions);
|
||||
|
||||
return (
|
||||
<DetailsFrame
|
||||
{...props}
|
||||
title={t('register.details.title')}
|
||||
description={t('register.details.description')}
|
||||
formError={formError}
|
||||
draft={draft}
|
||||
onSubmit={() => void submit()}
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size={props.size}
|
||||
block
|
||||
isLoading={isSubmitting}
|
||||
>
|
||||
{t('register.details.submit')}
|
||||
</Button>
|
||||
<TermsLine before={t('register.details.terms-before')} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<NameFields control={form.control} isPaired={props.size === 'md'} />
|
||||
<UsernameField
|
||||
control={form.control}
|
||||
name="username"
|
||||
placeholder={t('register.fields.username-placeholder')}
|
||||
hint={t('register.fields.username-hint')}
|
||||
/>
|
||||
</DetailsFrame>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
'use client';
|
||||
|
||||
import { GridBox } from '@lumina/island/atoms/grid-box';
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import type { FieldValues, Path } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { translateMessage } from '../../../../../../../../../shared/utils';
|
||||
import type { NameFieldsProps } from '../types';
|
||||
|
||||
const NAME_FIELDS = [
|
||||
{ name: 'firstName', label: 'first-name', autoComplete: 'given-name' },
|
||||
{ name: 'lastName', label: 'last-name', autoComplete: 'family-name' },
|
||||
] as const;
|
||||
|
||||
/** First and last name in Persian: stacked on mobile, side by side on desktop. Private. */
|
||||
export function NameFields<T extends FieldValues>({
|
||||
control,
|
||||
isPaired,
|
||||
}: NameFieldsProps<T>) {
|
||||
const { t } = useTranslation('auth');
|
||||
|
||||
return (
|
||||
<GridBox cols={isPaired ? 'grid-cols-2' : 'grid-cols-1'} gap="gap-5">
|
||||
{NAME_FIELDS.map(({ name, label, autoComplete }) => (
|
||||
<Controller
|
||||
key={name}
|
||||
name={name as Path<T>}
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
value={field.value as string}
|
||||
autoComplete={autoComplete}
|
||||
label={t(`register.fields.${label}`)}
|
||||
placeholder={t(`register.fields.${label}-placeholder`)}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</GridBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { TermsLineProps } from '../types';
|
||||
|
||||
/**
|
||||
* Accepting the rules by submitting, with no checkbox. The rules page isn't designed yet, so the
|
||||
* line names it without a link.
|
||||
*/
|
||||
export function TermsLine({ before }: TermsLineProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
|
||||
return (
|
||||
<Typography variant="body-sm" color="secondary" className="text-center">
|
||||
{before}
|
||||
{t('register.terms-link')}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
'use client';
|
||||
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import type { FieldValues } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { translateMessage } from '../../../../../../../../../shared/utils';
|
||||
import { USERNAME_LENGTH } from '../../../../../../../../../shared/validations';
|
||||
import type { UsernameFieldProps } from '../types';
|
||||
|
||||
/** The public username: left to right after a fixed «@», lower-case, 3 to 30 characters. */
|
||||
export function UsernameField<T extends FieldValues>({
|
||||
control,
|
||||
name,
|
||||
placeholder,
|
||||
hint,
|
||||
}: UsernameFieldProps<T>) {
|
||||
const { t } = useTranslation('auth');
|
||||
|
||||
return (
|
||||
<Controller
|
||||
name={name}
|
||||
control={control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
value={field.value as string}
|
||||
dir="ltr"
|
||||
prefix="@"
|
||||
autoComplete="username"
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
maxLength={USERNAME_LENGTH.max}
|
||||
label={t('register.fields.username')}
|
||||
placeholder={placeholder}
|
||||
hint={hint}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { RegisterDetailsStep } from './RegisterDetailsStep';
|
||||
export type { RegisterDetailsStepProps } from './types';
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import type { ReactNode } from 'react';
|
||||
import type { Control, FieldValues, Path } from 'react-hook-form';
|
||||
|
||||
import type {
|
||||
RegisterDetailsPageModel,
|
||||
UseDetailsPartOptions,
|
||||
} from '../../../../../../../../features/auth';
|
||||
import type { SupportEntryProps } from '../../../../../organisms/support-entry';
|
||||
|
||||
export type RegisterDetailsStepProps = {
|
||||
/** `lg` on mobile, `md` on desktop. */
|
||||
size: 'md' | 'lg';
|
||||
supportPlacement: SupportEntryProps['placement'];
|
||||
/** The halt when the token runs out: a bottom sheet on mobile, a modal on desktop. */
|
||||
haltPlacement: 'sheet' | 'modal';
|
||||
};
|
||||
|
||||
/** What each account type's form gets from the step. */
|
||||
export type DetailsFormProps = RegisterDetailsStepProps & {
|
||||
page: RegisterDetailsPageModel;
|
||||
partOptions: UseDetailsPartOptions;
|
||||
};
|
||||
|
||||
export type DetailsFrameProps = DetailsFormProps & {
|
||||
/** Step 4's name in the bar and the heading. */
|
||||
title: string;
|
||||
description: string;
|
||||
formError: string | undefined;
|
||||
/** The submit button and what sits under it. */
|
||||
footer: ReactNode;
|
||||
/** The values to keep for the halt's new code. */
|
||||
draft: () => Parameters<RegisterDetailsPageModel['reverify']>[0];
|
||||
onSubmit: () => void;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export type ExpiryWarningProps = {
|
||||
expiresAt: number;
|
||||
};
|
||||
|
||||
export type ExpiryHaltProps = {
|
||||
placement: RegisterDetailsStepProps['haltPlacement'];
|
||||
isSending: boolean;
|
||||
onConfirm: () => void;
|
||||
};
|
||||
|
||||
export type TermsLineProps = {
|
||||
/** «با ساخت حساب، » or «با ثبت اطلاعات، ». */
|
||||
before: string;
|
||||
};
|
||||
|
||||
export type UsernameFieldProps<T extends FieldValues> = {
|
||||
control: Control<T>;
|
||||
name: Path<T>;
|
||||
placeholder: string;
|
||||
/** A rule shown before typing, replaced by an error. */
|
||||
hint?: string;
|
||||
};
|
||||
|
||||
export type NameFieldsProps<T extends FieldValues> = {
|
||||
control: Control<T>;
|
||||
/** Side by side on desktop. */
|
||||
isPaired: boolean;
|
||||
};
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
'use client';
|
||||
|
||||
import { StepProgress } from '@lumina/island/molecules/step-progress';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { RegisterProgressProps } from './types';
|
||||
|
||||
/** «مرحله n از ۵» over every registration step; step 4's name follows the account type. */
|
||||
export function RegisterProgress({ current, role }: RegisterProgressProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const steps = [
|
||||
t('register.steps.type'),
|
||||
t('register.steps.phone'),
|
||||
t('register.steps.code'),
|
||||
role === 'creator'
|
||||
? t('register.steps.identity')
|
||||
: t('register.steps.details'),
|
||||
t('register.steps.profile'),
|
||||
];
|
||||
|
||||
return (
|
||||
<StepProgress
|
||||
steps={steps}
|
||||
current={current}
|
||||
label={t('register.steps-label')}
|
||||
countLabel={(step, total) => t('register.step-count', { step, total })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { RegisterProgress } from './RegisterProgress';
|
||||
export type { RegisterProgressProps } from './types';
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import type { UserRole } from '../../../../../../../features/auth';
|
||||
|
||||
export type RegisterProgressProps = {
|
||||
/** 0-based: account type, number, code, details or identity, profile. */
|
||||
current: number;
|
||||
/** Names step 4: «احراز هویت» for a creator, «اطلاعات حساب» otherwise. */
|
||||
role: UserRole | null;
|
||||
};
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Link } from '@lumina/island/atoms/link';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { ChoiceCard } from '@lumina/island/molecules/choice-card';
|
||||
import type { FormEvent } from 'react';
|
||||
import { Controller, useWatch } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useRegisterTypePage } from '../../../../../../../features/auth';
|
||||
import type { UserRole } from '../../../../../../../features/auth';
|
||||
import { translateMessage } from '../../../../../../../shared/utils';
|
||||
import { useAuthRoutes } from '../../../../../../navigation';
|
||||
import { SupportEntry } from '../../../../organisms/support-entry';
|
||||
import { RegisterProgress } from '../register-progress';
|
||||
import type { RegisterTypeStepProps } from './types';
|
||||
|
||||
const ACCOUNT_TYPES = [
|
||||
{ value: 'investor', icon: 'investor' },
|
||||
{ value: 'creator', icon: 'analyst' },
|
||||
] as const satisfies readonly { value: UserRole; icon: string }[];
|
||||
|
||||
/**
|
||||
* Registration step 1: two cards, one line each on what the account is for, nothing
|
||||
* pre-selected. The account type can't change later, so the note says so before the choice.
|
||||
*/
|
||||
export function RegisterTypeStep({
|
||||
size,
|
||||
supportPlacement,
|
||||
}: RegisterTypeStepProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const routes = useAuthRoutes();
|
||||
const { form, submit } = useRegisterTypePage({
|
||||
phoneHref: routes.register.phone,
|
||||
});
|
||||
const role = useWatch({ control: form.control, name: 'role' });
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
|
||||
<RegisterProgress
|
||||
current={0}
|
||||
role={role === 'creator' || role === 'investor' ? role : null}
|
||||
/>
|
||||
<FlexBox direction="flex-col" className="gap-1.5">
|
||||
<Typography tag="h1" variant="heading-md">
|
||||
{t('register.type.title')}
|
||||
</Typography>
|
||||
<Typography color="secondary">
|
||||
{t('register.type.description')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
direction="flex-col"
|
||||
gap="gap-5"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<Controller
|
||||
name="role"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => {
|
||||
const error = translateMessage(t, fieldState.error?.message);
|
||||
return (
|
||||
<FlexBox
|
||||
tag="fieldset"
|
||||
direction="flex-col"
|
||||
gap="gap-3"
|
||||
className="m-0 min-w-0 border-0 p-0"
|
||||
>
|
||||
<Typography tag="legend" className="sr-only">
|
||||
{t('register.type.label')}
|
||||
</Typography>
|
||||
{ACCOUNT_TYPES.map(({ value, icon }) => (
|
||||
<ChoiceCard
|
||||
key={value}
|
||||
name={field.name}
|
||||
value={value}
|
||||
icon={icon}
|
||||
checked={field.value === value}
|
||||
onChange={() => field.onChange(value)}
|
||||
title={t(`register.type.${value}`)}
|
||||
description={t(`register.type.${value}-description`)}
|
||||
invalid={error !== undefined}
|
||||
/>
|
||||
))}
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
gap="gap-1"
|
||||
role={error ? 'alert' : undefined}
|
||||
>
|
||||
<Icon
|
||||
name={error ? 'alert' : 'info'}
|
||||
size={16}
|
||||
className={error ? 'text-danger' : 'text-text-secondary'}
|
||||
/>
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="caption"
|
||||
color={error ? 'danger' : 'secondary'}
|
||||
>
|
||||
{error ?? t('register.type.note')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Button type="submit" variant="primary" size={size} block>
|
||||
{t('register.type.submit')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-center"
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Typography tag="span" variant="body-sm" color="secondary">
|
||||
{t('register.has-account')}
|
||||
</Typography>
|
||||
<Link href={routes.login}>{t('register.login')}</Link>
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-center" className="mt-auto">
|
||||
<SupportEntry trigger="link" placement={supportPlacement} />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { RegisterTypeStep } from './RegisterTypeStep';
|
||||
export type { RegisterTypeStepProps } from './types';
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { SupportEntryProps } from '../../../../organisms/support-entry';
|
||||
|
||||
export type RegisterTypeStepProps = {
|
||||
/** `lg` on mobile, `md` on desktop. */
|
||||
size: 'md' | 'lg';
|
||||
supportPlacement: SupportEntryProps['placement'];
|
||||
};
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Link } from '@lumina/island/atoms/link';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
|
||||
import type { FormEvent } from 'react';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useRegisterPhonePage } from '../../../../../../../../features/auth';
|
||||
import { translateMessage } from '../../../../../../../../shared/utils';
|
||||
import { useAuthRoutes } from '../../../../../../../navigation';
|
||||
import { SupportEntry } from '../../../../../organisms/support-entry';
|
||||
import { RegisterProgress } from '../../../organisms/register-progress';
|
||||
import type { RegisterPhoneStepProps } from './types';
|
||||
|
||||
/**
|
||||
* Registration step 2: the number, with the chosen account type still in view and «تغییر» back
|
||||
* to step 1. A number that already has an account offers to sign in with it.
|
||||
*/
|
||||
export function RegisterPhoneStep({
|
||||
size,
|
||||
supportPlacement,
|
||||
}: RegisterPhoneStepProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const routes = useAuthRoutes();
|
||||
const {
|
||||
role,
|
||||
form,
|
||||
submit,
|
||||
isSubmitting,
|
||||
formError,
|
||||
isTakenPhone,
|
||||
loginWithPhone,
|
||||
isLoggingIn,
|
||||
carryPhone,
|
||||
} = useRegisterPhonePage({
|
||||
typeHref: routes.register.type,
|
||||
codeHref: routes.register.verify,
|
||||
loginCodeHref: routes.loginVerify,
|
||||
});
|
||||
|
||||
if (!role) return <SkeletonPreset preset="form" label={t('loading')} />;
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
|
||||
{formError && (
|
||||
<Banner tone="danger" title={t('phone.send-failed-banner')}>
|
||||
{formError}
|
||||
</Banner>
|
||||
)}
|
||||
<RegisterProgress current={1} role={role} />
|
||||
<FlexBox direction="flex-col" className="gap-1.5">
|
||||
<Typography tag="h1" variant="heading-md">
|
||||
{t('register.phone.title')}
|
||||
</Typography>
|
||||
<Typography color="secondary">
|
||||
{t('register.phone.description')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
gap="gap-2"
|
||||
className="rounded-md bg-surface-sunken ps-3 pe-1"
|
||||
>
|
||||
<Icon
|
||||
name={role === 'creator' ? 'analyst' : 'investor'}
|
||||
className="flex-none text-text-secondary"
|
||||
/>
|
||||
<Typography tag="span" variant="body-sm" className="flex-1">
|
||||
{role === 'creator'
|
||||
? t('register.phone.as-creator')
|
||||
: t('register.phone.as-investor')}
|
||||
</Typography>
|
||||
<Link href={routes.register.type} standalone className="px-2">
|
||||
{t('register.phone.change')}
|
||||
</Link>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
direction="flex-col"
|
||||
gap="gap-5"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-1">
|
||||
<Controller
|
||||
name="phone"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
inputMode="numeric"
|
||||
autoComplete="tel"
|
||||
label={t('phone.label')}
|
||||
placeholder={t('phone.placeholder')}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
className="w-full"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{isTakenPhone && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
iconEnd="arrow-left"
|
||||
isLoading={isLoggingIn}
|
||||
onClick={loginWithPhone}
|
||||
className="-ms-3"
|
||||
>
|
||||
{t('register.login-with-phone')}
|
||||
</Button>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size={size}
|
||||
block
|
||||
isLoading={isSubmitting}
|
||||
>
|
||||
{t('register.phone.submit')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-center"
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Typography tag="span" variant="body-sm" color="secondary">
|
||||
{t('register.has-account')}
|
||||
</Typography>
|
||||
<Link href={routes.login} onClick={carryPhone}>
|
||||
{t('register.login')}
|
||||
</Link>
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-center" className="mt-auto">
|
||||
<SupportEntry trigger="link" placement={supportPlacement} />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { RegisterPhoneStep } from './RegisterPhoneStep';
|
||||
export type { RegisterPhoneStepProps } from './types';
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { SupportEntryProps } from '../../../../../organisms/support-entry';
|
||||
|
||||
export type RegisterPhoneStepProps = {
|
||||
/** `lg` on mobile, `md` on desktop. */
|
||||
size: 'md' | 'lg';
|
||||
supportPlacement: SupportEntryProps['placement'];
|
||||
};
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
'use client';
|
||||
|
||||
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useRegisterVerifyPage } from '../../../../../../../../features/auth';
|
||||
import { useAuthRoutes } from '../../../../../../../navigation';
|
||||
import { CodeStep } from '../../../../organisms/code-step';
|
||||
import { RegisterProgress } from '../../../organisms/register-progress';
|
||||
import type { RegisterVerifyStepProps } from './types';
|
||||
|
||||
/**
|
||||
* Registration step 3: login's code step with the step bar and «تأیید و ادامه». A verified code
|
||||
* opens step 4 on the 15-minute registration token.
|
||||
*/
|
||||
export function RegisterVerifyStep({
|
||||
size,
|
||||
supportPlacement,
|
||||
}: RegisterVerifyStepProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const routes = useAuthRoutes();
|
||||
const model = useRegisterVerifyPage({
|
||||
phoneHref: routes.register.phone,
|
||||
detailsHref: routes.register.details,
|
||||
});
|
||||
|
||||
if (!model.phone) {
|
||||
return <SkeletonPreset preset="form" label={t('loading')} />;
|
||||
}
|
||||
return (
|
||||
<CodeStep
|
||||
model={model}
|
||||
progress={<RegisterProgress current={2} role={model.role} />}
|
||||
submitLabel={t('register.verify.submit')}
|
||||
editHref={routes.register.phone}
|
||||
size={size}
|
||||
supportPlacement={supportPlacement}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { RegisterVerifyStep } from './RegisterVerifyStep';
|
||||
export type { RegisterVerifyStepProps } from './types';
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { SupportEntryProps } from '../../../../../organisms/support-entry';
|
||||
|
||||
export type RegisterVerifyStepProps = {
|
||||
/** `lg` on mobile, `md` on desktop. */
|
||||
size: 'md' | 'lg';
|
||||
supportPlacement: SupportEntryProps['placement'];
|
||||
};
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { SupportLink } from '@lumina/island/atoms/support-link';
|
||||
import { SupportSheet } from '@lumina/island/organisms/support-sheet';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { getEnv } from '../../../../../env';
|
||||
import { ROUTES } from '../../../../navigation';
|
||||
import { SUPPORT_CHAT_URLS } from './constants';
|
||||
import type { SupportEntryProps } from './types';
|
||||
|
||||
/**
|
||||
* One way into support: its trigger and the support sheet it opens (a bottom sheet on mobile, a
|
||||
* popover under the trigger on desktop). The chats and hours come from config.
|
||||
*/
|
||||
export function SupportEntry({
|
||||
trigger,
|
||||
placement,
|
||||
size = 'lg',
|
||||
}: SupportEntryProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const { baleHandle, telegramHandle, supportHours } = getEnv();
|
||||
const toggle = () => setIsOpen((open) => !open);
|
||||
const dialogProps = {
|
||||
'aria-haspopup': 'dialog',
|
||||
'aria-expanded': isOpen,
|
||||
onClick: toggle,
|
||||
} as const;
|
||||
|
||||
const button =
|
||||
trigger === 'icon' ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon="headset"
|
||||
label={t('header.support')}
|
||||
{...dialogProps}
|
||||
/>
|
||||
) : trigger === 'link' ? (
|
||||
<SupportLink standalone {...dialogProps}>
|
||||
{t('support.link')}
|
||||
</SupportLink>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon="headset"
|
||||
size={size}
|
||||
block
|
||||
{...dialogProps}
|
||||
>
|
||||
{t('support.link')}
|
||||
</Button>
|
||||
);
|
||||
|
||||
const sheet = (
|
||||
<SupportSheet
|
||||
placement={placement}
|
||||
open={isOpen}
|
||||
onClose={() => setIsOpen(false)}
|
||||
baleHref={SUPPORT_CHAT_URLS.bale(baleHandle)}
|
||||
telegramHref={SUPPORT_CHAT_URLS.telegram(telegramHandle)}
|
||||
termsHref={ROUTES.terms}
|
||||
labels={{
|
||||
title: t('support.title'),
|
||||
bale: t('support.bale'),
|
||||
telegram: t('support.telegram'),
|
||||
hours: t('support.hours', { hours: supportHours }),
|
||||
terms: t('support.terms'),
|
||||
close: t('support.close'),
|
||||
opensNewTab: t('support.opens-new-tab'),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
// A popover hangs from a positioned parent that also holds its trigger.
|
||||
return placement === 'popover' ? (
|
||||
<FlexBox
|
||||
display={trigger === 'button' ? 'flex' : 'inline-flex'}
|
||||
className="relative"
|
||||
>
|
||||
{button}
|
||||
{sheet}
|
||||
</FlexBox>
|
||||
) : (
|
||||
<>
|
||||
{button}
|
||||
{sheet}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
/** The support chats' addresses; only the handles come from config. */
|
||||
export const SUPPORT_CHAT_URLS = {
|
||||
bale: (handle: string) => `https://ble.ir/${handle}`,
|
||||
telegram: (handle: string) => `https://t.me/${handle}`,
|
||||
} as const;
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { SupportEntry } from './SupportEntry';
|
||||
export type { SupportEntryProps } from './types';
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import type { SupportPlacement } from '@lumina/island/organisms/support-sheet';
|
||||
|
||||
export type SupportEntryProps = {
|
||||
/**
|
||||
* icon: the headset in a header. link: «تماس با پشتیبانی» on its own line under a form.
|
||||
* button: the primary action of a screen that leaves nothing else to do (suspended).
|
||||
*/
|
||||
trigger: 'icon' | 'link' | 'button';
|
||||
/** bottom: the mobile sheet. popover: desktop, hanging under its trigger. */
|
||||
placement: Extract<SupportPlacement, 'bottom' | 'popover'>;
|
||||
/** The button trigger's size: `lg` on mobile, `md` on desktop. */
|
||||
size?: 'md' | 'lg';
|
||||
};
|
||||
|
|
@ -1,25 +1,35 @@
|
|||
import { eventEmitter } from '@lumina/libs/event-emitter';
|
||||
|
||||
import { useAuthStore } from '../../../../stores/auth';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { AUTH_EVENTS } from '../../constants';
|
||||
import { authRepository } from '../../repositories/auth';
|
||||
import type { SessionPayload, VerifyOtpArgs } from '../../repositories/auth';
|
||||
import type { VerifyOtpArgs } from '../../repositories/auth';
|
||||
import type { LoginOutcome } from './types';
|
||||
|
||||
/**
|
||||
* Verifies the login code; the gateway sets the session cookies and the auth store learns the
|
||||
* account, so every auth-dependent part renders its member variant. Emits `auth.login`.
|
||||
* account, so every auth-dependent part renders its member variant. A suspended account gets no
|
||||
* session: the gateway still opens one, so it is closed again at once. Emits `auth.login` when
|
||||
* the person is signed in.
|
||||
*/
|
||||
export async function login(
|
||||
args: VerifyOtpArgs,
|
||||
{ emit = true }: { emit?: boolean } = {},
|
||||
): Promise<SessionPayload> {
|
||||
const session = await authRepository.verifyLoginOtp(args);
|
||||
useAuthStore.getState().setSession({ account: session.account });
|
||||
): Promise<LoginOutcome> {
|
||||
const { account } = await authRepository.verifyLoginOtp(args);
|
||||
if (account.status === 'suspended') {
|
||||
await authRepository.logout();
|
||||
useAuthFlowStore.getState().reset();
|
||||
return { status: 'suspended' };
|
||||
}
|
||||
useAuthFlowStore.getState().reset();
|
||||
useAuthStore.getState().setSession({ account });
|
||||
if (emit) {
|
||||
eventEmitter.emit(AUTH_EVENTS.login, {
|
||||
userId: session.account.id,
|
||||
role: session.account.role,
|
||||
userId: account.id,
|
||||
role: account.role,
|
||||
});
|
||||
}
|
||||
return session;
|
||||
return { status: 'signed-in', account };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1,2 @@
|
|||
export { login } from './actions';
|
||||
export type { LoginOutcome } from './types';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,6 @@
|
|||
import type { AccountPayload } from '../../repositories/account';
|
||||
|
||||
/** Signed in, or turned away because the account is suspended (no session). */
|
||||
export type LoginOutcome =
|
||||
| { status: 'signed-in'; account: AccountPayload }
|
||||
| { status: 'suspended' };
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import { eventEmitter } from '@lumina/libs/event-emitter';
|
||||
import type { UploadProgress } from '@lumina/libs/http';
|
||||
|
||||
import { useAuthStore } from '../../../../stores/auth';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { AUTH_EVENTS } from '../../constants';
|
||||
import { authRepository } from '../../repositories/auth';
|
||||
import type {
|
||||
|
|
@ -8,12 +10,28 @@ import type {
|
|||
RegisterCreatorArgs,
|
||||
} from '../../repositories/auth';
|
||||
|
||||
/** Creates a creator account with lite KYC and signs it in (cookies and auth store). Emits `auth.register`. */
|
||||
/**
|
||||
* Creates a creator account with lite KYC (the ID images upload with progress and can be
|
||||
* cancelled) and signs it in (cookies and auth store); the flow's number and token are dropped.
|
||||
* Emits `auth.register`.
|
||||
*/
|
||||
export async function registerCreator(
|
||||
args: RegisterCreatorArgs,
|
||||
{ emit = true }: { emit?: boolean } = {},
|
||||
{
|
||||
emit = true,
|
||||
signal,
|
||||
onProgress,
|
||||
}: {
|
||||
emit?: boolean;
|
||||
signal?: AbortSignal;
|
||||
onProgress?: (progress: UploadProgress) => void;
|
||||
} = {},
|
||||
): Promise<CreatorRegisteredPayload> {
|
||||
const registration = await authRepository.registerCreator(args);
|
||||
const registration = await authRepository.registerCreator(args, {
|
||||
signal,
|
||||
onProgress,
|
||||
});
|
||||
useAuthFlowStore.getState().reset();
|
||||
useAuthStore.getState().setSession({ account: registration.account });
|
||||
if (emit) {
|
||||
eventEmitter.emit(AUTH_EVENTS.register, {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { eventEmitter } from '@lumina/libs/event-emitter';
|
||||
|
||||
import { useAuthStore } from '../../../../stores/auth';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { AUTH_EVENTS } from '../../constants';
|
||||
import { authRepository } from '../../repositories/auth';
|
||||
import type {
|
||||
|
|
@ -8,12 +9,13 @@ import type {
|
|||
SessionPayload,
|
||||
} from '../../repositories/auth';
|
||||
|
||||
/** Creates an investor account and signs it in (cookies and auth store). Emits `auth.register`. */
|
||||
/** Creates an investor account and signs it in (cookies and auth store); the flow's number and token are dropped. Emits `auth.register`. */
|
||||
export async function registerInvestor(
|
||||
args: RegisterInvestorArgs,
|
||||
{ emit = true }: { emit?: boolean } = {},
|
||||
): Promise<SessionPayload> {
|
||||
const session = await authRepository.registerInvestor(args);
|
||||
useAuthFlowStore.getState().reset();
|
||||
useAuthStore.getState().setSession({ account: session.account });
|
||||
if (emit) {
|
||||
eventEmitter.emit(AUTH_EVENTS.register, {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,37 @@
|
|||
import { eventEmitter } from '@lumina/libs/event-emitter';
|
||||
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { AUTH_EVENTS } from '../../constants';
|
||||
import {
|
||||
AUTH_ERROR_CODES,
|
||||
authErrorCode,
|
||||
authRepository,
|
||||
} from '../../repositories/auth';
|
||||
import type { SendCodeArgs } from './types';
|
||||
|
||||
/**
|
||||
* Sends a sign-in or registration code to the number and starts the resend wait. Also the resend:
|
||||
* a new code replaces the previous one. Asked again for the same number inside the server's
|
||||
* cooldown, the code already sent still works, so that counts as sent. Emits `auth.code-sent`.
|
||||
*/
|
||||
export async function sendCode(
|
||||
{ purpose, phone }: SendCodeArgs,
|
||||
{ emit = true }: { emit?: boolean } = {},
|
||||
): Promise<'ok'> {
|
||||
try {
|
||||
if (purpose === 'login') await authRepository.requestLoginOtp({ phone });
|
||||
else await authRepository.sendRegistrationOtp({ phone });
|
||||
} catch (error) {
|
||||
const flow = useAuthFlowStore.getState();
|
||||
const isSameCode =
|
||||
authErrorCode(error) === AUTH_ERROR_CODES.cooldown &&
|
||||
flow.purpose === purpose &&
|
||||
flow.phone === phone &&
|
||||
flow.codeSentAt !== null;
|
||||
if (!isSameCode) throw error;
|
||||
return 'ok';
|
||||
}
|
||||
useAuthFlowStore.getState().codeSent(purpose, phone, Date.now());
|
||||
if (emit) eventEmitter.emit(AUTH_EVENTS.codeSent, { purpose });
|
||||
return 'ok';
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { sendCode } from './actions';
|
||||
export type { SendCodeArgs } from './types';
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { AuthPurpose } from '../../types';
|
||||
|
||||
export type SendCodeArgs = {
|
||||
purpose: AuthPurpose;
|
||||
/** 09XXXXXXXXX; the repository sends E.164. */
|
||||
phone: string;
|
||||
};
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import { eventEmitter } from '@lumina/libs/event-emitter';
|
||||
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { AUTH_EVENTS } from '../../constants';
|
||||
import { authRepository } from '../../repositories/auth';
|
||||
import type { VerifyOtpArgs } from '../../repositories/auth';
|
||||
|
||||
/**
|
||||
* Proves the number for a new account. The registration token it returns lives in memory only
|
||||
* (the flow store), for step 4, and is never stored. Emits `auth.phone-verified`.
|
||||
*/
|
||||
export async function verifyRegistrationCode(
|
||||
args: VerifyOtpArgs,
|
||||
{ emit = true }: { emit?: boolean } = {},
|
||||
): Promise<'ok'> {
|
||||
const { registrationToken, expiresInSeconds } =
|
||||
await authRepository.verifyRegistrationOtp(args);
|
||||
useAuthFlowStore.getState().phoneVerified({
|
||||
token: registrationToken,
|
||||
expiresAt: Date.now() + expiresInSeconds * 1000,
|
||||
});
|
||||
if (emit) {
|
||||
eventEmitter.emit(AUTH_EVENTS.phoneVerified, { purpose: 'register' });
|
||||
}
|
||||
return 'ok';
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { verifyRegistrationCode } from './actions';
|
||||
|
|
@ -1,7 +1,27 @@
|
|||
/** Events auth actions emit when they succeed; the AppShell reacts to them. */
|
||||
export const AUTH_EVENTS = {
|
||||
restore: 'auth.restore',
|
||||
codeSent: 'auth.code-sent',
|
||||
phoneVerified: 'auth.phone-verified',
|
||||
login: 'auth.login',
|
||||
register: 'auth.register',
|
||||
logout: 'auth.logout',
|
||||
} as const;
|
||||
|
||||
/** Why a code is sent: to sign in to an account, or to prove the number for a new one. */
|
||||
export const AUTH_PURPOSES = ['login', 'register'] as const;
|
||||
|
||||
/**
|
||||
* The code rules the pages show. The server owns them (a code lives 10 minutes, the third wrong
|
||||
* code blocks the number for 10 minutes); the 2-minute resend wait is the product's, longer than
|
||||
* the server's 60-second cooldown.
|
||||
*/
|
||||
export const CODE_RULES = {
|
||||
length: 6,
|
||||
resendWaitSeconds: 120,
|
||||
maxMisses: 3,
|
||||
blockSeconds: 600,
|
||||
} as const;
|
||||
|
||||
/** Step 4 warns this long before the registration token runs out. */
|
||||
export const REGISTRATION_WARNING_SECONDS = 120;
|
||||
|
|
|
|||
|
|
@ -1,16 +1,78 @@
|
|||
import './types';
|
||||
|
||||
export { login } from './actions/login';
|
||||
export type { LoginOutcome } from './actions/login';
|
||||
export { logout } from './actions/logout';
|
||||
export { registerCreator } from './actions/register-creator';
|
||||
export { registerInvestor } from './actions/register-investor';
|
||||
export { restoreSession } from './actions/restore-session';
|
||||
export { AUTH_EVENTS } from './constants';
|
||||
export { sendCode } from './actions/send-code';
|
||||
export type { SendCodeArgs } from './actions/send-code';
|
||||
export { verifyRegistrationCode } from './actions/verify-registration-code';
|
||||
export {
|
||||
AUTH_EVENTS,
|
||||
AUTH_PURPOSES,
|
||||
CODE_RULES,
|
||||
REGISTRATION_WARNING_SECONDS,
|
||||
} from './constants';
|
||||
export type { UserRole, UserStatus } from './entities/user';
|
||||
export { useCodeStep } from './models/code-step';
|
||||
export type {
|
||||
CodeStepModel,
|
||||
CodeStepStatus,
|
||||
CodeVerifiedOutcome,
|
||||
ResendPhase,
|
||||
UseCodeStepOptions,
|
||||
} from './models/code-step';
|
||||
export { useLoginPage } from './models/login';
|
||||
export type { LoginPageModel, UseLoginPageOptions } from './models/login';
|
||||
export { useLoginVerifyPage } from './models/login-verify';
|
||||
export type {
|
||||
LoginVerifyPageModel,
|
||||
LoginVerifyView,
|
||||
SignedInViewer,
|
||||
UseLoginVerifyPageOptions,
|
||||
} from './models/login-verify';
|
||||
export {
|
||||
useCreatorIdentityPart,
|
||||
useInvestorDetailsPart,
|
||||
useRegisterDetailsPage,
|
||||
} from './models/register-details';
|
||||
export type {
|
||||
CreatorIdentityPartModel,
|
||||
IdCardSide,
|
||||
InvestorDetailsPartModel,
|
||||
RegisterDetailsPageModel,
|
||||
RegistrationTimePhase,
|
||||
UseDetailsPartOptions,
|
||||
UseRegisterDetailsPageOptions,
|
||||
} from './models/register-details';
|
||||
export { useRegisterPhonePage } from './models/register-phone';
|
||||
export type {
|
||||
RegisterPhonePageModel,
|
||||
UseRegisterPhonePageOptions,
|
||||
} from './models/register-phone';
|
||||
export { useRegisterTypePage } from './models/register-type';
|
||||
export type {
|
||||
RegisterTypePageModel,
|
||||
UseRegisterTypePageOptions,
|
||||
} from './models/register-type';
|
||||
export { useRegisterVerifyPage } from './models/register-verify';
|
||||
export type {
|
||||
RegisterVerifyPageModel,
|
||||
UseRegisterVerifyPageOptions,
|
||||
} from './models/register-verify';
|
||||
export { accountKeys, accountRepository } from './repositories/account';
|
||||
export type { AccountPayload, UpdateAccountArgs } from './repositories/account';
|
||||
export { AUTH_ENDPOINTS, authRepository } from './repositories/auth';
|
||||
export {
|
||||
AUTH_ENDPOINTS,
|
||||
AUTH_ERROR_CODES,
|
||||
AUTH_ERROR_COPY,
|
||||
authErrorCode,
|
||||
authRepository,
|
||||
} from './repositories/auth';
|
||||
export type {
|
||||
AuthErrorCode,
|
||||
CreatorRegisteredPayload,
|
||||
OtpSentPayload,
|
||||
RegisterCreatorArgs,
|
||||
|
|
@ -21,4 +83,4 @@ export type {
|
|||
SessionStatePayload,
|
||||
VerifyOtpArgs,
|
||||
} from './repositories/auth';
|
||||
export type { LogoutReason } from './types';
|
||||
export type { AuthPurpose, LogoutReason } from './types';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
/** How long «کد جدید ارسال شد.» stays before the wait counts again. */
|
||||
export const SENT_NOTICE_MS = 2000;
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
export { useCodeStep } from './use-code-step';
|
||||
export type {
|
||||
CodeStepModel,
|
||||
CodeStepStatus,
|
||||
CodeVerifiedOutcome,
|
||||
ResendPhase,
|
||||
UseCodeStepOptions,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import type { UseFormReturn } from 'react-hook-form';
|
||||
|
||||
import type { CodeFormValues } from '../../../../shared/validations';
|
||||
import type { VerifyOtpArgs } from '../../repositories/auth';
|
||||
import type { AuthPurpose } from '../../types';
|
||||
|
||||
/** stay: the code step stays (a suspended account). leave: the page is moving on. */
|
||||
export type CodeVerifiedOutcome = 'stay' | 'leave';
|
||||
|
||||
export type UseCodeStepOptions = {
|
||||
purpose: AuthPurpose;
|
||||
/** The number step, where a missing number (after a reload) sends the person back. */
|
||||
phoneHref: string;
|
||||
/** What failed, for the toast: «ورود انجام نشد». */
|
||||
failedMessage: string;
|
||||
/** The purpose's action; resolves once the page knows where to go. */
|
||||
verify: (args: VerifyOtpArgs) => Promise<CodeVerifiedOutcome>;
|
||||
};
|
||||
|
||||
/** idle: typing. verifying: a code is checked, or the page is moving on. blocked: too many wrong codes. */
|
||||
export type CodeStepStatus = 'idle' | 'verifying' | 'blocked';
|
||||
|
||||
/** The resend control's own phase: the wait (or the button), a send in flight, its confirmation. */
|
||||
export type ResendPhase = 'auto' | 'sending' | 'sent';
|
||||
|
||||
export type CodeStepModel = {
|
||||
/** `null` until the number is known; the page then redirects. */
|
||||
phone: string | null;
|
||||
form: UseFormReturn<CodeFormValues>;
|
||||
status: CodeStepStatus;
|
||||
/** Remounts the cells after a wrong code or a new one, so focus is back on the first cell. */
|
||||
attempt: number;
|
||||
submit: () => Promise<void>;
|
||||
/** The 6th digit submits on its own. */
|
||||
complete: (code: string) => void;
|
||||
resend: {
|
||||
/** When the wait (or the block) ends, ms since epoch. */
|
||||
endsAt: number | undefined;
|
||||
phase: ResendPhase;
|
||||
onResend: () => void;
|
||||
};
|
||||
blockedUntil: number | null;
|
||||
};
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { applyServerErrors, showActionError } from '../../../../shared/utils';
|
||||
import { codeSchema } from '../../../../shared/validations';
|
||||
import type { CodeFormValues } from '../../../../shared/validations';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { sendCode } from '../../actions/send-code';
|
||||
import { CODE_RULES } from '../../constants';
|
||||
import {
|
||||
AUTH_ERROR_CODES,
|
||||
authErrorCode,
|
||||
blockEndOf,
|
||||
} from '../../repositories/auth';
|
||||
import { SENT_NOTICE_MS } from './constants';
|
||||
import type { CodeStepModel, ResendPhase, UseCodeStepOptions } from './types';
|
||||
|
||||
/** A wrong code counts; the third one blocks the number until the returned time. Event handlers only. */
|
||||
function countMiss(): number | null {
|
||||
useAuthFlowStore.getState().codeMissed();
|
||||
return useAuthFlowStore.getState().misses >= CODE_RULES.maxMisses
|
||||
? Date.now() + CODE_RULES.blockSeconds * 1000
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The code step that login and registration share: the 6-digit field, the resend wait, wrong and
|
||||
* expired codes, and the 10-minute block. The server never says how many tries are left, so the
|
||||
* misses are counted here; the third one blocks the number, as the server does.
|
||||
*/
|
||||
export function useCodeStep({
|
||||
purpose,
|
||||
phoneHref,
|
||||
failedMessage,
|
||||
verify,
|
||||
}: UseCodeStepOptions): CodeStepModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
// Read once: a successful sign-in clears the flow while this page is still on screen.
|
||||
const [phone] = useState(() => useAuthFlowStore.getState().phone);
|
||||
const codeSentAt = useAuthFlowStore((state) => state.codeSentAt);
|
||||
const blockedUntil = useAuthFlowStore((state) => state.blockedUntil);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [phase, setPhase] = useState<ResendPhase>('auto');
|
||||
const [isLeaving, setIsLeaving] = useState(false);
|
||||
const form = useForm<CodeFormValues>({
|
||||
resolver: valibotResolver(codeSchema),
|
||||
defaultValues: { code: '' },
|
||||
});
|
||||
|
||||
// A reload forgets the number (it is never in the URL), so the flow starts again at its number.
|
||||
useEffect(() => {
|
||||
if (!phone) router.replace(phoneHref);
|
||||
}, [phone, phoneHref, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (blockedUntil === null) return undefined;
|
||||
const timer = setTimeout(
|
||||
() => useAuthFlowStore.getState().block(null),
|
||||
Math.max(0, blockedUntil - Date.now()),
|
||||
);
|
||||
return () => clearTimeout(timer);
|
||||
}, [blockedUntil]);
|
||||
|
||||
useEffect(() => {
|
||||
if (phase !== 'sent') return undefined;
|
||||
const timer = setTimeout(() => setPhase('auto'), SENT_NOTICE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [phase]);
|
||||
|
||||
/** Empty cells and focus on the first one. Clears errors too, so set them after. */
|
||||
const restart = () => {
|
||||
form.reset({ code: '' });
|
||||
setAttempt((count) => count + 1);
|
||||
};
|
||||
|
||||
const fail = (error: unknown) => {
|
||||
const options = { t, failedMessage };
|
||||
const code = authErrorCode(error);
|
||||
const isWrong = code === AUTH_ERROR_CODES.codeWrong;
|
||||
const blockEnd = isWrong ? countMiss() : blockEndOf(error);
|
||||
if (isWrong || blockEnd !== null || code === AUTH_ERROR_CODES.codeExpired) {
|
||||
restart();
|
||||
}
|
||||
if (blockEnd !== null) {
|
||||
useAuthFlowStore.getState().block(blockEnd);
|
||||
showActionError(error, options);
|
||||
return;
|
||||
}
|
||||
if (isWrong) {
|
||||
const isLastTry =
|
||||
useAuthFlowStore.getState().misses === CODE_RULES.maxMisses - 1;
|
||||
form.setError('code', {
|
||||
type: 'server',
|
||||
message: isLastTry ? 'auth:code.wrong-last' : 'auth:code.wrong',
|
||||
});
|
||||
showActionError(error, options);
|
||||
return;
|
||||
}
|
||||
applyServerErrors(form, error, options);
|
||||
};
|
||||
|
||||
const submit = form.handleSubmit(async ({ code }) => {
|
||||
if (!phone) return;
|
||||
try {
|
||||
if ((await verify({ phone, code })) === 'leave') setIsLeaving(true);
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
}
|
||||
});
|
||||
|
||||
const onResend = () => {
|
||||
if (!phone || phase === 'sending') return;
|
||||
setPhase('sending');
|
||||
sendCode({ purpose, phone })
|
||||
.then(() => {
|
||||
restart();
|
||||
setPhase('sent');
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
setPhase('auto');
|
||||
const blockEnd = blockEndOf(error);
|
||||
if (blockEnd !== null) useAuthFlowStore.getState().block(blockEnd);
|
||||
showActionError(error, {
|
||||
t,
|
||||
failedMessage: t('code.resend-failed'),
|
||||
retry: onResend,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
phone,
|
||||
form,
|
||||
status:
|
||||
blockedUntil !== null
|
||||
? 'blocked'
|
||||
: form.formState.isSubmitting || isLeaving
|
||||
? 'verifying'
|
||||
: 'idle',
|
||||
attempt,
|
||||
submit: () => submit(),
|
||||
complete: (code) => {
|
||||
form.setValue('code', code);
|
||||
void submit();
|
||||
},
|
||||
resend: {
|
||||
endsAt:
|
||||
blockedUntil ??
|
||||
(codeSentAt === null
|
||||
? undefined
|
||||
: codeSentAt + CODE_RULES.resendWaitSeconds * 1000),
|
||||
phase,
|
||||
onResend,
|
||||
},
|
||||
blockedUntil,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export { useLoginVerifyPage } from './use-login-verify-page';
|
||||
export type {
|
||||
LoginVerifyPageModel,
|
||||
LoginVerifyView,
|
||||
SignedInViewer,
|
||||
UseLoginVerifyPageOptions,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import type { UserRole } from '../../entities/user';
|
||||
import type { CodeStepModel } from '../code-step';
|
||||
|
||||
/** Who just signed in, for picking where they land. */
|
||||
export type SignedInViewer = {
|
||||
role: UserRole;
|
||||
username: string;
|
||||
/** A creator who left registration before the profile step. */
|
||||
needsProfile: boolean;
|
||||
};
|
||||
|
||||
export type UseLoginVerifyPageOptions = {
|
||||
/** The number step, keeping `?redirect=`. */
|
||||
phoneHref: string;
|
||||
/** Where a signed-in person goes: the page that asked, else their role's home. */
|
||||
landing: (viewer: SignedInViewer) => string;
|
||||
};
|
||||
|
||||
/** code: the code step. suspended: a valid code for a suspended account, with no session. */
|
||||
export type LoginVerifyView = 'code' | 'suspended';
|
||||
|
||||
export type LoginVerifyPageModel = CodeStepModel & { view: LoginVerifyView };
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
import { showToast } from '@lumina/island/molecules/toast';
|
||||
import { handleError } from '@lumina/libs/error-handler';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { profileRepository } from '../../../profile';
|
||||
import { login } from '../../actions/login';
|
||||
import { useCodeStep } from '../code-step';
|
||||
import type {
|
||||
LoginVerifyPageModel,
|
||||
LoginVerifyView,
|
||||
UseLoginVerifyPageOptions,
|
||||
} from './types';
|
||||
|
||||
/** A creator who left registration before the profile step goes back to it. A failed read never blocks sign-in. */
|
||||
async function needsCreatorProfile(): Promise<boolean> {
|
||||
try {
|
||||
return !(await profileRepository.getMine()).profileComplete;
|
||||
} catch (error) {
|
||||
handleError(error, { where: 'action', name: 'creator-landing' });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Login step 2: the code. A valid code signs the person in and sends them on with the toast; a
|
||||
* suspended account stays here on the suspended screen, with no session.
|
||||
*/
|
||||
export function useLoginVerifyPage({
|
||||
phoneHref,
|
||||
landing,
|
||||
}: UseLoginVerifyPageOptions): LoginVerifyPageModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
const [view, setView] = useState<LoginVerifyView>('code');
|
||||
|
||||
const step = useCodeStep({
|
||||
purpose: 'login',
|
||||
phoneHref,
|
||||
failedMessage: t('login.verify-failed'),
|
||||
verify: async (args) => {
|
||||
const result = await login(args);
|
||||
if (result.status === 'suspended') {
|
||||
setView('suspended');
|
||||
return 'stay';
|
||||
}
|
||||
const { role, username } = result.account;
|
||||
const needsProfile = role === 'creator' && (await needsCreatorProfile());
|
||||
showToast({ tone: 'success', message: t('login.success') });
|
||||
router.replace(landing({ role, username, needsProfile }));
|
||||
return 'leave';
|
||||
},
|
||||
});
|
||||
|
||||
return { ...step, view };
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { useLoginPage } from './use-login-page';
|
||||
export type { LoginPageModel, UseLoginPageOptions } from './types';
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import type { UseFormReturn } from 'react-hook-form';
|
||||
|
||||
import type {
|
||||
PhoneFormOutput,
|
||||
PhoneFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
|
||||
export type UseLoginPageOptions = {
|
||||
/** The code step, keeping `?redirect=`. */
|
||||
codeHref: string;
|
||||
/** Registration, keeping `?redirect=`. */
|
||||
registerHref: string;
|
||||
};
|
||||
|
||||
export type LoginPageModel = {
|
||||
form: UseFormReturn<PhoneFormValues, unknown, PhoneFormOutput>;
|
||||
submit: () => Promise<void>;
|
||||
isSubmitting: boolean;
|
||||
/** The code could not be sent for a reason that isn't the number's (network, server). */
|
||||
formError: string | undefined;
|
||||
/** The server knows no account for the number: offer registration with it. */
|
||||
isUnknownPhone: boolean;
|
||||
registerHref: string;
|
||||
/** Carries the typed number to registration's number step. */
|
||||
carryPhone: () => void;
|
||||
};
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { applyServerErrors, toLocalMobile } from '../../../../shared/utils';
|
||||
import { phoneSchema } from '../../../../shared/validations';
|
||||
import type {
|
||||
PhoneFormOutput,
|
||||
PhoneFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { sendCode } from '../../actions/send-code';
|
||||
import { AUTH_ERROR_COPY } from '../../repositories/auth';
|
||||
import type { LoginPageModel, UseLoginPageOptions } from './types';
|
||||
|
||||
/**
|
||||
* Login step 1: the number. A valid number gets a code and moves to the code step; the number
|
||||
* stays in the flow store, never in the URL. A number with no account offers registration.
|
||||
*/
|
||||
export function useLoginPage({
|
||||
codeHref,
|
||||
registerHref,
|
||||
}: UseLoginPageOptions): LoginPageModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
// Back from the code step, or over from registration: the number is already typed.
|
||||
const [phone] = useState(() => useAuthFlowStore.getState().phone ?? '');
|
||||
const form = useForm<PhoneFormValues, unknown, PhoneFormOutput>({
|
||||
resolver: valibotResolver(phoneSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: { phone },
|
||||
});
|
||||
|
||||
const submit = form.handleSubmit(async (values) => {
|
||||
try {
|
||||
await sendCode({ purpose: 'login', phone: values.phone });
|
||||
router.push(codeHref);
|
||||
} catch (error) {
|
||||
applyServerErrors(form, error, {
|
||||
t,
|
||||
failedMessage: t('phone.send-failed'),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const { errors, isSubmitting } = form.formState;
|
||||
return {
|
||||
form,
|
||||
submit: () => submit(),
|
||||
isSubmitting,
|
||||
formError: errors.root?.server?.message,
|
||||
isUnknownPhone: errors.phone?.message === AUTH_ERROR_COPY.phoneUnknown,
|
||||
registerHref,
|
||||
carryPhone: () =>
|
||||
useAuthFlowStore
|
||||
.getState()
|
||||
.carryPhone(toLocalMobile(form.getValues('phone'))),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
export { useCreatorIdentityPart } from './use-creator-identity-part';
|
||||
export { useInvestorDetailsPart } from './use-investor-details-part';
|
||||
export { useRegisterDetailsPage } from './use-register-details-page';
|
||||
export type {
|
||||
CreatorIdentityPartModel,
|
||||
IdCardSide,
|
||||
InvestorDetailsPartModel,
|
||||
RegisterDetailsPageModel,
|
||||
RegistrationTimePhase,
|
||||
UseDetailsPartOptions,
|
||||
UseRegisterDetailsPageOptions,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
import type { UseFormReturn } from 'react-hook-form';
|
||||
|
||||
import type {
|
||||
CreatorIdentityFormOutput,
|
||||
CreatorIdentityFormValues,
|
||||
InvestorDetailsFormOutput,
|
||||
InvestorDetailsFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import type { RegistrationDraft } from '../../../../stores/auth-flow';
|
||||
import type { UserRole } from '../../entities/user';
|
||||
|
||||
export type UseRegisterDetailsPageOptions = {
|
||||
/** Step 2, where a missing token (after a reload) sends the person back. */
|
||||
phoneHref: string;
|
||||
/** Step 3, for a new code once the token ran out. */
|
||||
codeHref: string;
|
||||
};
|
||||
|
||||
/** open: time enough. warning: two minutes left. expired: the token is gone; a new code is needed. */
|
||||
export type RegistrationTimePhase = 'open' | 'warning' | 'expired';
|
||||
|
||||
export type RegisterDetailsPageModel = {
|
||||
/** `null` until known; the page then redirects to step 2. */
|
||||
role: UserRole | null;
|
||||
phase: RegistrationTimePhase;
|
||||
/** When the token runs out, ms since epoch. */
|
||||
expiresAt: number | null;
|
||||
/** The server said the token is gone before the clock did. */
|
||||
expire: () => void;
|
||||
/** Keeps step 4's values, sends a new code to the same number and opens step 3. */
|
||||
reverify: (draft: RegistrationDraft) => void;
|
||||
isReverifying: boolean;
|
||||
};
|
||||
|
||||
export type UseDetailsPartOptions = {
|
||||
/** Step 5, the profile, keeping `?redirect=`. */
|
||||
profileHref: string;
|
||||
/** The token ran out on submit. */
|
||||
onExpired: () => void;
|
||||
};
|
||||
|
||||
export type InvestorDetailsPartModel = {
|
||||
form: UseFormReturn<
|
||||
InvestorDetailsFormValues,
|
||||
unknown,
|
||||
InvestorDetailsFormOutput
|
||||
>;
|
||||
submit: () => Promise<void>;
|
||||
isSubmitting: boolean;
|
||||
formError: string | undefined;
|
||||
/** The values to keep while the number is confirmed again. */
|
||||
draft: () => RegistrationDraft;
|
||||
};
|
||||
|
||||
export type IdCardSide = 'idCardFront' | 'idCardBack';
|
||||
|
||||
export type CreatorIdentityPartModel = {
|
||||
form: UseFormReturn<
|
||||
CreatorIdentityFormValues,
|
||||
unknown,
|
||||
CreatorIdentityFormOutput
|
||||
>;
|
||||
submit: () => Promise<void>;
|
||||
isSubmitting: boolean;
|
||||
formError: string | undefined;
|
||||
/** A picked image is checked at once; a rejected one leaves the box empty with its message. */
|
||||
pickImage: (side: IdCardSide, file: File | null) => void;
|
||||
/** 0–100 while the images upload. */
|
||||
progress: number | undefined;
|
||||
cancelUpload: () => void;
|
||||
draft: () => RegistrationDraft;
|
||||
};
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { showToast } from '@lumina/island/molecules/toast';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import * as v from 'valibot';
|
||||
|
||||
import { applyServerErrors } from '../../../../shared/utils';
|
||||
import {
|
||||
creatorIdentitySchema,
|
||||
idCardImage,
|
||||
} from '../../../../shared/validations';
|
||||
import type {
|
||||
CreatorIdentityFormOutput,
|
||||
CreatorIdentityFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { registerCreator } from '../../actions/register-creator';
|
||||
import { AUTH_ERROR_CODES, authErrorCode } from '../../repositories/auth';
|
||||
import type {
|
||||
CreatorIdentityPartModel,
|
||||
IdCardSide,
|
||||
UseDetailsPartOptions,
|
||||
} from './types';
|
||||
import { useLeaveGuard } from './use-leave-guard';
|
||||
|
||||
/**
|
||||
* Step 4 for a creator: the public username and the private identity (names, national code, both
|
||||
* sides of the ID card), sent together for the admin review. The images stay in memory, upload
|
||||
* with progress and can be cancelled. The username stands in for the display name the API wants
|
||||
* now; the profile step sets the real one.
|
||||
*/
|
||||
export function useCreatorIdentityPart({
|
||||
profileHref,
|
||||
onExpired,
|
||||
}: UseDetailsPartOptions): CreatorIdentityPartModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
const [draft] = useState(() => useAuthFlowStore.getState().draft);
|
||||
const [progress, setProgress] = useState<number>();
|
||||
const [isDone, setIsDone] = useState(false);
|
||||
const [upload, setUpload] = useState<AbortController | null>(null);
|
||||
const form = useForm<
|
||||
CreatorIdentityFormValues,
|
||||
unknown,
|
||||
CreatorIdentityFormOutput
|
||||
>({
|
||||
resolver: valibotResolver(creatorIdentitySchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: {
|
||||
username: draft?.username ?? '',
|
||||
firstName: draft?.firstName ?? '',
|
||||
lastName: draft?.lastName ?? '',
|
||||
nationalId: draft?.nationalId ?? '',
|
||||
idCardFront: draft?.idCardFront ?? null,
|
||||
idCardBack: draft?.idCardBack ?? null,
|
||||
},
|
||||
});
|
||||
const { errors, isSubmitting, isDirty } = form.formState;
|
||||
useLeaveGuard(isDirty && !isDone);
|
||||
|
||||
const pickImage = (side: IdCardSide, file: File | null) => {
|
||||
const checked = file ? v.safeParse(idCardImage, file) : null;
|
||||
if (checked && !checked.success) {
|
||||
form.setValue(side, null, { shouldDirty: true });
|
||||
form.setError(side, { type: 'pick', message: checked.issues[0].message });
|
||||
return;
|
||||
}
|
||||
form.setValue(side, file, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: form.getFieldState(side).isTouched || file !== null,
|
||||
});
|
||||
};
|
||||
|
||||
const submit = form.handleSubmit(async (values) => {
|
||||
const { phone, registration } = useAuthFlowStore.getState();
|
||||
if (!phone || !registration) {
|
||||
onExpired();
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setUpload(controller);
|
||||
setProgress(0);
|
||||
try {
|
||||
await registerCreator(
|
||||
{
|
||||
phone,
|
||||
registrationToken: registration.token,
|
||||
username: values.username,
|
||||
displayName: values.username,
|
||||
firstName: values.firstName,
|
||||
lastName: values.lastName,
|
||||
nationalIdNumber: values.nationalId,
|
||||
nationalIdFrontImage: values.idCardFront,
|
||||
nationalIdBackImage: values.idCardBack,
|
||||
},
|
||||
{
|
||||
signal: controller.signal,
|
||||
onProgress: ({ percent }) => setProgress(percent),
|
||||
},
|
||||
);
|
||||
setIsDone(true);
|
||||
showToast({ tone: 'success', message: t('register.identity.success') });
|
||||
router.replace(profileHref);
|
||||
} catch (error) {
|
||||
if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) {
|
||||
onExpired();
|
||||
return;
|
||||
}
|
||||
applyServerErrors(form, error, {
|
||||
t,
|
||||
failedMessage: t('register.identity.failed'),
|
||||
});
|
||||
} finally {
|
||||
setUpload(null);
|
||||
setProgress(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
form,
|
||||
submit: () => submit(),
|
||||
isSubmitting,
|
||||
formError: errors.root?.server?.message,
|
||||
pickImage,
|
||||
progress,
|
||||
cancelUpload: () => upload?.abort(),
|
||||
draft: () => form.getValues(),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { showToast } from '@lumina/island/molecules/toast';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { applyServerErrors } from '../../../../shared/utils';
|
||||
import { investorDetailsSchema } from '../../../../shared/validations';
|
||||
import type {
|
||||
InvestorDetailsFormOutput,
|
||||
InvestorDetailsFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { registerInvestor } from '../../actions/register-investor';
|
||||
import { AUTH_ERROR_CODES, authErrorCode } from '../../repositories/auth';
|
||||
import type { InvestorDetailsPartModel, UseDetailsPartOptions } from './types';
|
||||
import { useLeaveGuard } from './use-leave-guard';
|
||||
|
||||
/**
|
||||
* Step 4 for an investor: name, last name and username. «ساخت حساب» creates the account, swaps
|
||||
* the token for the session and opens the profile step. Errors show on blur and on submit; a
|
||||
* banner only for network or server failures.
|
||||
*/
|
||||
export function useInvestorDetailsPart({
|
||||
profileHref,
|
||||
onExpired,
|
||||
}: UseDetailsPartOptions): InvestorDetailsPartModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
// Back from a new code after the token ran out: what was typed comes back.
|
||||
const [draft] = useState(() => useAuthFlowStore.getState().draft);
|
||||
const form = useForm<
|
||||
InvestorDetailsFormValues,
|
||||
unknown,
|
||||
InvestorDetailsFormOutput
|
||||
>({
|
||||
resolver: valibotResolver(investorDetailsSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: {
|
||||
firstName: draft?.firstName ?? '',
|
||||
lastName: draft?.lastName ?? '',
|
||||
username: draft?.username ?? '',
|
||||
},
|
||||
});
|
||||
const [isDone, setIsDone] = useState(false);
|
||||
const { errors, isSubmitting, isDirty } = form.formState;
|
||||
useLeaveGuard(isDirty && !isDone);
|
||||
|
||||
const submit = form.handleSubmit(async (values) => {
|
||||
const { phone, registration } = useAuthFlowStore.getState();
|
||||
if (!phone || !registration) {
|
||||
onExpired();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await registerInvestor({
|
||||
phone,
|
||||
registrationToken: registration.token,
|
||||
...values,
|
||||
});
|
||||
setIsDone(true);
|
||||
showToast({ tone: 'success', message: t('register.details.success') });
|
||||
router.replace(profileHref);
|
||||
} catch (error) {
|
||||
if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) {
|
||||
onExpired();
|
||||
return;
|
||||
}
|
||||
applyServerErrors(form, error, {
|
||||
t,
|
||||
failedMessage: t('register.details.failed'),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
form,
|
||||
submit: () => submit(),
|
||||
isSubmitting,
|
||||
formError: errors.root?.server?.message,
|
||||
draft: () => form.getValues(),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import { useEffect } from 'react';
|
||||
|
||||
/** While the form holds unsent values, leaving the page asks first (the browser's own prompt). */
|
||||
export function useLeaveGuard(isDirty: boolean): void {
|
||||
useEffect(() => {
|
||||
if (!isDirty) return undefined;
|
||||
const ask = (event: BeforeUnloadEvent) => event.preventDefault();
|
||||
window.addEventListener('beforeunload', ask);
|
||||
return () => window.removeEventListener('beforeunload', ask);
|
||||
}, [isDirty]);
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { showActionError } from '../../../../shared/utils';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import type { RegistrationDraft } from '../../../../stores/auth-flow';
|
||||
import { sendCode } from '../../actions/send-code';
|
||||
import { REGISTRATION_WARNING_SECONDS } from '../../constants';
|
||||
import type {
|
||||
RegisterDetailsPageModel,
|
||||
RegistrationTimePhase,
|
||||
UseRegisterDetailsPageOptions,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Registration step 4's page: the account type it asks for, and the 15-minute token it runs on.
|
||||
* Two minutes before the end it warns; at the end (or when the server says so) it halts, and a
|
||||
* new code brings the person back with everything they typed. The API can't renew the token.
|
||||
*/
|
||||
export function useRegisterDetailsPage({
|
||||
phoneHref,
|
||||
codeHref,
|
||||
}: UseRegisterDetailsPageOptions): RegisterDetailsPageModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
// Read once: registering resets the flow while this page is still on screen.
|
||||
const [{ role, phone, registration }] = useState(() =>
|
||||
useAuthFlowStore.getState(),
|
||||
);
|
||||
const expiresAt = registration?.expiresAt ?? null;
|
||||
const [phase, setPhase] = useState<RegistrationTimePhase>('open');
|
||||
const [isReverifying, setIsReverifying] = useState(false);
|
||||
|
||||
// A reload forgets the token, so the number is confirmed again.
|
||||
useEffect(() => {
|
||||
if (!role || !phone || !registration) router.replace(phoneHref);
|
||||
}, [role, phone, registration, phoneHref, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (expiresAt === null) return undefined;
|
||||
const left = expiresAt - Date.now();
|
||||
const warning = setTimeout(
|
||||
() => setPhase((current) => (current === 'open' ? 'warning' : current)),
|
||||
Math.max(0, left - REGISTRATION_WARNING_SECONDS * 1000),
|
||||
);
|
||||
const expired = setTimeout(() => setPhase('expired'), Math.max(0, left));
|
||||
return () => {
|
||||
clearTimeout(warning);
|
||||
clearTimeout(expired);
|
||||
};
|
||||
}, [expiresAt]);
|
||||
|
||||
const reverify = (draft: RegistrationDraft) => {
|
||||
if (!phone) return;
|
||||
useAuthFlowStore.getState().keepDraft(draft);
|
||||
setIsReverifying(true);
|
||||
sendCode({ purpose: 'register', phone })
|
||||
.then(() => router.replace(codeHref))
|
||||
.catch((error: unknown) => {
|
||||
setIsReverifying(false);
|
||||
showActionError(error, {
|
||||
t,
|
||||
failedMessage: t('phone.send-failed'),
|
||||
retry: () => reverify(draft),
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
role,
|
||||
phase,
|
||||
expiresAt,
|
||||
expire: () => setPhase('expired'),
|
||||
reverify,
|
||||
isReverifying,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export { useRegisterPhonePage } from './use-register-phone-page';
|
||||
export type {
|
||||
RegisterPhonePageModel,
|
||||
UseRegisterPhonePageOptions,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import type { UseFormReturn } from 'react-hook-form';
|
||||
|
||||
import type {
|
||||
PhoneFormOutput,
|
||||
PhoneFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import type { UserRole } from '../../entities/user';
|
||||
|
||||
export type UseRegisterPhonePageOptions = {
|
||||
/** Step 1, where a missing account type (after a reload) sends the person back. */
|
||||
typeHref: string;
|
||||
/** Step 3. */
|
||||
codeHref: string;
|
||||
/** Login's code step, for a number that already has an account. */
|
||||
loginCodeHref: string;
|
||||
};
|
||||
|
||||
export type RegisterPhonePageModel = {
|
||||
/** `null` until known; the page then redirects to step 1. */
|
||||
role: UserRole | null;
|
||||
form: UseFormReturn<PhoneFormValues, unknown, PhoneFormOutput>;
|
||||
submit: () => Promise<void>;
|
||||
isSubmitting: boolean;
|
||||
formError: string | undefined;
|
||||
/** The number already has an account: offer to sign in with it. */
|
||||
isTakenPhone: boolean;
|
||||
/** Sends a login code to the number and opens login's code step. */
|
||||
loginWithPhone: () => void;
|
||||
isLoggingIn: boolean;
|
||||
/** Carries the typed number to login. */
|
||||
carryPhone: () => void;
|
||||
};
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import {
|
||||
applyServerErrors,
|
||||
showActionError,
|
||||
toLocalMobile,
|
||||
} from '../../../../shared/utils';
|
||||
import { phoneSchema } from '../../../../shared/validations';
|
||||
import type {
|
||||
PhoneFormOutput,
|
||||
PhoneFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import { sendCode } from '../../actions/send-code';
|
||||
import { AUTH_ERROR_COPY } from '../../repositories/auth';
|
||||
import type {
|
||||
RegisterPhonePageModel,
|
||||
UseRegisterPhonePageOptions,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Registration step 2: the number, for the account type chosen at step 1. A number that already
|
||||
* has an account gets no code; the way out is signing in with it.
|
||||
*/
|
||||
export function useRegisterPhonePage({
|
||||
typeHref,
|
||||
codeHref,
|
||||
loginCodeHref,
|
||||
}: UseRegisterPhonePageOptions): RegisterPhonePageModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
const [{ role, phone }] = useState(() => useAuthFlowStore.getState());
|
||||
const [isLoggingIn, setIsLoggingIn] = useState(false);
|
||||
const form = useForm<PhoneFormValues, unknown, PhoneFormOutput>({
|
||||
resolver: valibotResolver(phoneSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: { phone: phone ?? '' },
|
||||
});
|
||||
|
||||
// A reload forgets the account type, so registration starts again at step 1.
|
||||
useEffect(() => {
|
||||
if (!role) router.replace(typeHref);
|
||||
}, [role, typeHref, router]);
|
||||
|
||||
const submit = form.handleSubmit(async (values) => {
|
||||
try {
|
||||
await sendCode({ purpose: 'register', phone: values.phone });
|
||||
router.push(codeHref);
|
||||
} catch (error) {
|
||||
applyServerErrors(form, error, {
|
||||
t,
|
||||
failedMessage: t('phone.send-failed'),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const loginWithPhone = () => {
|
||||
const typed = toLocalMobile(form.getValues('phone'));
|
||||
setIsLoggingIn(true);
|
||||
sendCode({ purpose: 'login', phone: typed })
|
||||
.then(() => router.push(loginCodeHref))
|
||||
.catch((error: unknown) => {
|
||||
setIsLoggingIn(false);
|
||||
showActionError(error, {
|
||||
t,
|
||||
failedMessage: t('phone.send-failed'),
|
||||
retry: loginWithPhone,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const { errors, isSubmitting } = form.formState;
|
||||
return {
|
||||
role,
|
||||
form,
|
||||
submit: () => submit(),
|
||||
isSubmitting,
|
||||
formError: errors.root?.server?.message,
|
||||
isTakenPhone: errors.phone?.message === AUTH_ERROR_COPY.phoneTaken,
|
||||
loginWithPhone,
|
||||
isLoggingIn,
|
||||
carryPhone: () =>
|
||||
useAuthFlowStore
|
||||
.getState()
|
||||
.carryPhone(toLocalMobile(form.getValues('phone'))),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export { useRegisterTypePage } from './use-register-type-page';
|
||||
export type {
|
||||
RegisterTypePageModel,
|
||||
UseRegisterTypePageOptions,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import type { UseFormReturn } from 'react-hook-form';
|
||||
|
||||
import type {
|
||||
AccountTypeFormOutput,
|
||||
AccountTypeFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
|
||||
export type UseRegisterTypePageOptions = {
|
||||
/** Step 2, keeping `?redirect=`. */
|
||||
phoneHref: string;
|
||||
};
|
||||
|
||||
export type RegisterTypePageModel = {
|
||||
form: UseFormReturn<AccountTypeFormValues, unknown, AccountTypeFormOutput>;
|
||||
submit: () => Promise<void>;
|
||||
};
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { accountTypeSchema } from '../../../../shared/validations';
|
||||
import type {
|
||||
AccountTypeFormOutput,
|
||||
AccountTypeFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import { useAuthFlowStore } from '../../../../stores/auth-flow';
|
||||
import type {
|
||||
RegisterTypePageModel,
|
||||
UseRegisterTypePageOptions,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Registration step 1: the account type. Nothing is pre-selected and «ادامه» is never disabled:
|
||||
* pressed with no choice, it says so. The choice travels in the flow store to step 2.
|
||||
*/
|
||||
export function useRegisterTypePage({
|
||||
phoneHref,
|
||||
}: UseRegisterTypePageOptions): RegisterTypePageModel {
|
||||
const router = useRouter();
|
||||
// Back from step 2: the choice is still made.
|
||||
const [role] = useState(() => useAuthFlowStore.getState().role ?? '');
|
||||
const form = useForm<AccountTypeFormValues, unknown, AccountTypeFormOutput>({
|
||||
resolver: valibotResolver(accountTypeSchema),
|
||||
defaultValues: { role },
|
||||
});
|
||||
|
||||
const submit = form.handleSubmit((values) => {
|
||||
useAuthFlowStore.getState().chooseRole(values.role);
|
||||
router.push(phoneHref);
|
||||
});
|
||||
|
||||
return { form, submit: () => submit() };
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export { useRegisterVerifyPage } from './use-register-verify-page';
|
||||
export type {
|
||||
RegisterVerifyPageModel,
|
||||
UseRegisterVerifyPageOptions,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import type { UserRole } from '../../entities/user';
|
||||
import type { CodeStepModel } from '../code-step';
|
||||
|
||||
export type UseRegisterVerifyPageOptions = {
|
||||
/** Step 2, keeping `?redirect=`. */
|
||||
phoneHref: string;
|
||||
/** Step 4. */
|
||||
detailsHref: string;
|
||||
};
|
||||
|
||||
export type RegisterVerifyPageModel = CodeStepModel & {
|
||||
role: UserRole | null;
|
||||
};
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import { useRouter } from 'next/navigation';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useFlowRole } from '../../../../stores/auth-flow';
|
||||
import { verifyRegistrationCode } from '../../actions/verify-registration-code';
|
||||
import { useCodeStep } from '../code-step';
|
||||
import type {
|
||||
RegisterVerifyPageModel,
|
||||
UseRegisterVerifyPageOptions,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Registration step 3: login's code step, ending in the 15-minute registration token. The code
|
||||
* is used up, so step 4 replaces this page in the history.
|
||||
*/
|
||||
export function useRegisterVerifyPage({
|
||||
phoneHref,
|
||||
detailsHref,
|
||||
}: UseRegisterVerifyPageOptions): RegisterVerifyPageModel {
|
||||
const { t } = useTranslation('auth');
|
||||
const router = useRouter();
|
||||
const role = useFlowRole();
|
||||
|
||||
const step = useCodeStep({
|
||||
purpose: 'register',
|
||||
phoneHref,
|
||||
failedMessage: t('register.verify.failed'),
|
||||
verify: async (args) => {
|
||||
await verifyRegistrationCode(args);
|
||||
router.replace(detailsHref);
|
||||
return 'leave';
|
||||
},
|
||||
});
|
||||
|
||||
return { ...step, role };
|
||||
}
|
||||
|
|
@ -1,6 +1,9 @@
|
|||
import type { UploadProgress } from '@lumina/libs/http';
|
||||
|
||||
import { renameFieldErrors } from '../../../../shared/utils';
|
||||
import { authHttp } from '../../http';
|
||||
import { AUTH_ENDPOINTS, AUTH_FIELD_NAMES } from './constants';
|
||||
import { toAuthError } from './errors';
|
||||
import {
|
||||
toCreatorRegisteredPayload,
|
||||
toOtpSentPayload,
|
||||
|
|
@ -33,12 +36,13 @@ import type {
|
|||
* Passwordless phone auth. Every request sends `skipRefresh`: these run without a session, and the
|
||||
* API answers a wrong code with 400 and field errors, so a 401 here never means "refresh". A
|
||||
* successful sign-in or registration sets the HttpOnly session cookies; the body is the account.
|
||||
* Failures carry an auth code and Persian copy (`toAuthError`).
|
||||
*/
|
||||
async function send<T>(request: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await request();
|
||||
} catch (error) {
|
||||
throw renameFieldErrors(error, AUTH_FIELD_NAMES);
|
||||
throw toAuthError(renameFieldErrors(error, AUTH_FIELD_NAMES));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -90,14 +94,22 @@ export const authRepository = {
|
|||
return toSessionPayload(response);
|
||||
},
|
||||
|
||||
/** Multipart with the two ID images; reports upload progress and can be cancelled. */
|
||||
async registerCreator(
|
||||
args: RegisterCreatorArgs,
|
||||
{
|
||||
signal,
|
||||
onProgress,
|
||||
}: {
|
||||
signal?: AbortSignal;
|
||||
onProgress?: (progress: UploadProgress) => void;
|
||||
} = {},
|
||||
): Promise<CreatorRegisteredPayload> {
|
||||
const response = await send(() =>
|
||||
authHttp.upload<CreatorRegisteredResponseDto>(
|
||||
AUTH_ENDPOINTS.registerCreator,
|
||||
toRegisterCreatorFormData(args),
|
||||
{ skipRefresh: true },
|
||||
{ skipRefresh: true, signal, onProgress },
|
||||
),
|
||||
);
|
||||
return toCreatorRegisteredPayload(response);
|
||||
|
|
|
|||
|
|
@ -18,3 +18,102 @@ export const AUTH_FIELD_NAMES = {
|
|||
phone_number: 'phone',
|
||||
otp: 'code',
|
||||
} as const;
|
||||
|
||||
/** Auth failures the pages tell apart, set as `HttpError.code` by the repository. */
|
||||
export const AUTH_ERROR_CODES = {
|
||||
codeWrong: 'AUTH_CODE_WRONG',
|
||||
codeExpired: 'AUTH_CODE_EXPIRED',
|
||||
blocked: 'AUTH_BLOCKED',
|
||||
cooldown: 'AUTH_COOLDOWN',
|
||||
phoneUnknown: 'AUTH_PHONE_UNKNOWN',
|
||||
phoneTaken: 'AUTH_PHONE_TAKEN',
|
||||
usernameTaken: 'AUTH_USERNAME_TAKEN',
|
||||
registrationExpired: 'AUTH_REGISTRATION_EXPIRED',
|
||||
fileTooLarge: 'AUTH_FILE_TOO_LARGE',
|
||||
} as const;
|
||||
|
||||
/** Each auth failure's copy, an `errors:` key the error handler and the fields translate. */
|
||||
export const AUTH_ERROR_COPY = {
|
||||
codeWrong: 'errors:auth.code-wrong',
|
||||
codeExpired: 'errors:auth.code-expired',
|
||||
blocked: 'errors:auth.blocked',
|
||||
blockedHint: 'errors:auth.blocked-hint',
|
||||
cooldown: 'errors:auth.cooldown',
|
||||
phoneUnknown: 'errors:auth.phone-unknown',
|
||||
phoneTaken: 'errors:auth.phone-taken',
|
||||
usernameTaken: 'errors:auth.username-taken',
|
||||
registrationExpired: 'errors:auth.registration-expired',
|
||||
fileTooLarge: 'errors:auth.file-too-large',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The gateway answers auth failures with English text and no code, so each rule matches the start
|
||||
* of its text and gives the code, its copy under `errors:auth`, and the `*Args` field it belongs
|
||||
* to. Text that matches no rule passes through unchanged.
|
||||
*/
|
||||
export const AUTH_ERROR_RULES = [
|
||||
{
|
||||
text: 'Invalid OTP',
|
||||
code: AUTH_ERROR_CODES.codeWrong,
|
||||
message: AUTH_ERROR_COPY.codeWrong,
|
||||
field: 'code',
|
||||
},
|
||||
{
|
||||
text: 'OTP expired',
|
||||
code: AUTH_ERROR_CODES.codeExpired,
|
||||
message: AUTH_ERROR_COPY.codeExpired,
|
||||
field: 'code',
|
||||
},
|
||||
{
|
||||
text: 'No active OTP',
|
||||
code: AUTH_ERROR_CODES.codeExpired,
|
||||
message: AUTH_ERROR_COPY.codeExpired,
|
||||
field: 'code',
|
||||
},
|
||||
{
|
||||
text: 'Too many failed OTP attempts',
|
||||
code: AUTH_ERROR_CODES.blocked,
|
||||
message: AUTH_ERROR_COPY.blocked,
|
||||
hint: AUTH_ERROR_COPY.blockedHint,
|
||||
},
|
||||
{
|
||||
text: 'Please wait before requesting a new OTP',
|
||||
code: AUTH_ERROR_CODES.cooldown,
|
||||
message: AUTH_ERROR_COPY.cooldown,
|
||||
},
|
||||
{
|
||||
text: 'User not found',
|
||||
code: AUTH_ERROR_CODES.phoneUnknown,
|
||||
message: AUTH_ERROR_COPY.phoneUnknown,
|
||||
field: 'phone',
|
||||
},
|
||||
{
|
||||
text: 'Phone number already registered',
|
||||
code: AUTH_ERROR_CODES.phoneTaken,
|
||||
message: AUTH_ERROR_COPY.phoneTaken,
|
||||
field: 'phone',
|
||||
},
|
||||
{
|
||||
// The phone was checked at step 2, so a clash at step 4 is the username.
|
||||
text: 'Phone number or username already registered',
|
||||
code: AUTH_ERROR_CODES.usernameTaken,
|
||||
message: AUTH_ERROR_COPY.usernameTaken,
|
||||
field: 'username',
|
||||
},
|
||||
{
|
||||
text: 'Phone verification is required',
|
||||
code: AUTH_ERROR_CODES.registrationExpired,
|
||||
message: AUTH_ERROR_COPY.registrationExpired,
|
||||
},
|
||||
{
|
||||
text: 'File too large',
|
||||
code: AUTH_ERROR_CODES.fileTooLarge,
|
||||
message: AUTH_ERROR_COPY.fileTooLarge,
|
||||
},
|
||||
] as const satisfies readonly {
|
||||
text: string;
|
||||
code: string;
|
||||
message: string;
|
||||
hint?: string;
|
||||
field?: string;
|
||||
}[];
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
import { HttpError, isHttpError } from '@lumina/libs/http';
|
||||
|
||||
import { AUTH_ERROR_CODES, AUTH_ERROR_RULES } from './constants';
|
||||
import type { AuthErrorCode } from './types';
|
||||
|
||||
const CODES: ReadonlySet<string> = new Set(Object.values(AUTH_ERROR_CODES));
|
||||
|
||||
/**
|
||||
* Gives a known auth failure its code, its Persian copy (an `errors:` key the error handler
|
||||
* translates) and its field, so pages can branch on the code and forms show the message under the
|
||||
* right field. Anything else passes through unchanged.
|
||||
*/
|
||||
export function toAuthError(error: unknown): unknown {
|
||||
if (!isHttpError(error)) return error;
|
||||
const rule = AUTH_ERROR_RULES.find(({ text }) =>
|
||||
error.message.startsWith(text),
|
||||
);
|
||||
if (!rule) return error;
|
||||
return new HttpError({
|
||||
...error.toJSON(),
|
||||
code: rule.code,
|
||||
message: rule.message,
|
||||
hint: 'hint' in rule ? rule.hint : error.hint,
|
||||
fieldErrors:
|
||||
'field' in rule ? { [rule.field]: rule.message } : error.fieldErrors,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
/** The auth failure an error stands for, or `null` for any other error. */
|
||||
export function authErrorCode(error: unknown): AuthErrorCode | null {
|
||||
return isHttpError(error) && CODES.has(error.code)
|
||||
? (error.code as AuthErrorCode)
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* When a blocked number may try again (ms since epoch): the server's `blockedUntil`, else its
|
||||
* `retryAfterSeconds` from now, else `null` for an error that is no block.
|
||||
*/
|
||||
export function blockEndOf(error: unknown): number | null {
|
||||
if (
|
||||
authErrorCode(error) !== AUTH_ERROR_CODES.blocked ||
|
||||
!isHttpError(error)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const until = error.details?.blockedUntil;
|
||||
const parsed = typeof until === 'string' ? Date.parse(until) : Number.NaN;
|
||||
if (!Number.isNaN(parsed)) return parsed;
|
||||
return error.retryAfter ? Date.now() + error.retryAfter * 1000 : null;
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
export { authRepository } from './auth';
|
||||
export { AUTH_ENDPOINTS } from './constants';
|
||||
export { AUTH_ENDPOINTS, AUTH_ERROR_CODES, AUTH_ERROR_COPY } from './constants';
|
||||
export { authErrorCode, blockEndOf } from './errors';
|
||||
export type {
|
||||
AuthErrorCode,
|
||||
CreatorRegisteredPayload,
|
||||
OtpSentPayload,
|
||||
RegisterCreatorArgs,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import type { UserEntity, UserRole } from '../../entities/user';
|
||||
import type { AccountPayload } from '../account';
|
||||
import type { AUTH_ERROR_CODES } from './constants';
|
||||
|
||||
export type AuthErrorCode =
|
||||
(typeof AUTH_ERROR_CODES)[keyof typeof AUTH_ERROR_CODES];
|
||||
|
||||
// Phone numbers are typed in any digits and form; mappers send E.164.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,17 @@
|
|||
import type { ViewerStatus } from '../../stores/auth';
|
||||
import type { AUTH_PURPOSES } from './constants';
|
||||
import type { UserRole } from './entities/user';
|
||||
|
||||
export type AuthPurpose = (typeof AUTH_PURPOSES)[number];
|
||||
|
||||
/** Why the session ended: the user signed out, or the refresh token was dead. */
|
||||
export type LogoutReason = 'signed-out' | 'session-ended';
|
||||
|
||||
declare module '@lumina/libs/event-emitter' {
|
||||
interface EventMap {
|
||||
'auth.restore': { status: ViewerStatus };
|
||||
'auth.code-sent': { purpose: AuthPurpose };
|
||||
'auth.phone-verified': { purpose: AuthPurpose };
|
||||
'auth.login': { userId: string; role: UserRole };
|
||||
'auth.register': { userId: string; role: UserRole };
|
||||
'auth.logout': { reason: LogoutReason };
|
||||
|
|
|
|||
|
|
@ -0,0 +1,173 @@
|
|||
{
|
||||
"header": {
|
||||
"brand": "لومینا",
|
||||
"home": "صفحه اصلی لومینا",
|
||||
"back": "بازگشت به مرحله قبل",
|
||||
"support": "پشتیبانی"
|
||||
},
|
||||
"support": {
|
||||
"link": "تماس با پشتیبانی",
|
||||
"title": "پشتیبانی لومینا",
|
||||
"bale": "گفتگو در بله",
|
||||
"telegram": "گفتگو در تلگرام",
|
||||
"hours": "ساعت پاسخگویی: {{hours}}",
|
||||
"terms": "شرایط اشتراک",
|
||||
"close": "بستن",
|
||||
"opens-new-tab": "در برنامه یا زبانهی جدید باز میشود"
|
||||
},
|
||||
"loading": "در حال بارگذاری…",
|
||||
"phone": {
|
||||
"label": "شماره موبایل",
|
||||
"placeholder": "0912 345 6789",
|
||||
"send-failed": "کد تأیید ارسال نشد",
|
||||
"send-failed-banner": "ارسال کد تأیید ناموفق بود. دوباره تلاش کنید."
|
||||
},
|
||||
"login": {
|
||||
"meta-title": "ورود",
|
||||
"header": "ورود",
|
||||
"title": "ورود به لومینا",
|
||||
"description": "شماره موبایل خود را وارد کنید.",
|
||||
"submit": "دریافت کد",
|
||||
"no-account": "حساب کاربری ندارید؟",
|
||||
"register": "ثبتنام",
|
||||
"register-with-phone": "ثبتنام با این شماره",
|
||||
"verify-meta-title": "کد تأیید ورود",
|
||||
"verify-submit": "ورود",
|
||||
"verify-failed": "ورود انجام نشد",
|
||||
"success": "با موفقیت وارد شدید."
|
||||
},
|
||||
"code": {
|
||||
"title": "کد تأیید را وارد کنید",
|
||||
"description": "کد 6 رقمی ارسالشده به {{phone}} را وارد کنید.",
|
||||
"label": "کد تأیید 6 رقمی",
|
||||
"edit-phone": "ویرایش شماره",
|
||||
"wrong": "کد واردشده اشتباه است. لطفاً دوباره تلاش کنید.",
|
||||
"wrong-last": "کد واردشده اشتباه است. یک تلاش دیگر باقی مانده است.",
|
||||
"blocked-title": "تعداد تلاشهای مجاز به پایان رسید.",
|
||||
"blocked-description": "10 دقیقه دیگر تلاش کنید.",
|
||||
"resend-failed": "کد جدید ارسال نشد",
|
||||
"resend": {
|
||||
"counting": "ارسال دوباره کد تا",
|
||||
"ready": "ارسال دوباره کد",
|
||||
"sending": "در حال ارسال…",
|
||||
"sent": "کد جدید ارسال شد.",
|
||||
"limited": "ارسال دوباره کد پس از",
|
||||
"hint": "کد را دریافت نکردید؟",
|
||||
"ready-announcement": "اکنون میتوانید کد جدید دریافت کنید."
|
||||
}
|
||||
},
|
||||
"suspended": {
|
||||
"title": "حساب شما تعلیق شده است.",
|
||||
"description": "برای اطلاعات بیشتر با پشتیبانی تماس بگیرید."
|
||||
},
|
||||
"register": {
|
||||
"meta-title": "ثبتنام",
|
||||
"header": "ثبتنام",
|
||||
"steps-label": "مراحل ثبتنام",
|
||||
"step-count": "مرحله {{step}} از {{total}}",
|
||||
"steps": {
|
||||
"type": "نوع حساب",
|
||||
"phone": "شماره موبایل",
|
||||
"code": "کد تأیید",
|
||||
"details": "اطلاعات حساب",
|
||||
"identity": "احراز هویت",
|
||||
"profile": "پروفایل"
|
||||
},
|
||||
"has-account": "حساب کاربری دارید؟",
|
||||
"login": "ورود",
|
||||
"login-with-phone": "ورود با این شماره",
|
||||
"type": {
|
||||
"title": "ثبتنام در لومینا",
|
||||
"description": "نوع حساب خود را انتخاب کنید.",
|
||||
"label": "نوع حساب",
|
||||
"investor": "سرمایهگذار",
|
||||
"investor-description": "تحلیلگران را با کارنامهشان مقایسه میکنم و در کانالشان مشترک میشوم.",
|
||||
"creator": "تحلیلگر",
|
||||
"creator-description": "تحلیل و پیشبینی منتشر میکنم و از اشتراک کانالم درآمد دارم.",
|
||||
"note": "نوع حساب پس از ثبتنام قابل تغییر نیست.",
|
||||
"submit": "ادامه"
|
||||
},
|
||||
"phone": {
|
||||
"title": "شماره موبایل خود را وارد کنید",
|
||||
"description": "کد تأیید به این شماره پیامک میشود.",
|
||||
"as-investor": "ثبتنام بهعنوان سرمایهگذار",
|
||||
"as-creator": "ثبتنام بهعنوان تحلیلگر",
|
||||
"change": "تغییر",
|
||||
"submit": "دریافت کد"
|
||||
},
|
||||
"verify": {
|
||||
"meta-title": "کد تأیید ثبتنام",
|
||||
"submit": "تأیید و ادامه",
|
||||
"failed": "شماره تأیید نشد"
|
||||
},
|
||||
"details": {
|
||||
"meta-title": "اطلاعات حساب",
|
||||
"title": "اطلاعات حساب",
|
||||
"description": "نام شما فقط در اطلاعات کاربری دیده میشود؛ دیگران شما را با نام کاربری میشناسند.",
|
||||
"submit": "ساخت حساب",
|
||||
"terms-before": "با ساخت حساب، ",
|
||||
"failed": "حساب ساخته نشد",
|
||||
"network-title": "خطا در ثبت اطلاعات.",
|
||||
"success": "حساب شما ساخته شد."
|
||||
},
|
||||
"identity": {
|
||||
"title": "احراز هویت",
|
||||
"description": "این اطلاعات فقط برای تأیید هویت شما است و به سرمایهگذاران نمایش داده نمیشود.",
|
||||
"public-title": "شناسه عمومی",
|
||||
"public-description": "سرمایهگذاران شما را با این نام میشناسند.",
|
||||
"username-note": "نام کاربری شناسه عمومی شما در پلتفرم است و پس از ثبت اولیه قابل تغییر نیست.",
|
||||
"private-title": "اطلاعات هویتی",
|
||||
"private-description": "محرمانه است و فقط برای تأیید هویت بررسی میشود.",
|
||||
"submit": "ثبت و ادامه",
|
||||
"terms-before": "با ثبت اطلاعات، ",
|
||||
"failed": "اطلاعات ثبت نشد",
|
||||
"success": "اطلاعات شما برای بررسی ارسال شد.",
|
||||
"cancel": "لغو ارسال"
|
||||
},
|
||||
"terms-link": "قوانین لومینا را میپذیرید.",
|
||||
"fields": {
|
||||
"first-name": "نام",
|
||||
"first-name-placeholder": "مثال: علی",
|
||||
"last-name": "نام خانوادگی",
|
||||
"last-name-placeholder": "مثال: رضایی",
|
||||
"username": "نام کاربری",
|
||||
"username-placeholder": "ali_investor",
|
||||
"username-hint": "فقط حروف انگلیسی، عدد و _ ، از 3 تا 30 کاراکتر. پس از ثبت قابل تغییر نیست.",
|
||||
"national-id": "کد ملی",
|
||||
"national-id-placeholder": "0012345678",
|
||||
"id-card-front": "تصویر کارت ملی (رو)",
|
||||
"id-card-back": "تصویر کارت ملی (پشت)",
|
||||
"id-card-hint": "یک تصویر واضح از کارت ملی خود آپلود کنید.",
|
||||
"id-card-pick": "انتخاب فایل",
|
||||
"id-card-rules": "JPG یا PNG، حداکثر 5 مگابایت",
|
||||
"id-card-remove": "حذف تصویر",
|
||||
"id-card-uploading": "در حال بارگذاری… {{percent}}٪",
|
||||
"file-size": "{{size}} مگابایت"
|
||||
},
|
||||
"expiry": {
|
||||
"warning-title": "زمان این مرحله رو به پایان است.",
|
||||
"title": "زمان ثبتنام به پایان رسید",
|
||||
"description": "برای امنیت حساب، شماره موبایل خود را دوباره تأیید کنید. اطلاعاتی که وارد کردهاید حفظ میشود.",
|
||||
"submit": "ارسال کد تأیید",
|
||||
"warning-before": "برای امنیت حساب، این صفحه تا",
|
||||
"warning-after": "دیگر باز است."
|
||||
}
|
||||
},
|
||||
"validation": {
|
||||
"phone-invalid": "شماره موبایل واردشده معتبر نیست.",
|
||||
"code-length": "کد 6 رقمی را کامل وارد کنید.",
|
||||
"role-required": "نوع حساب را انتخاب کنید.",
|
||||
"required": "این فیلد الزامی است.",
|
||||
"first-name-persian": "لطفاً نام را به فارسی وارد کنید.",
|
||||
"last-name-persian": "لطفاً نام خانوادگی را به فارسی وارد کنید.",
|
||||
"username-required": "وارد کردن نام کاربری الزامی است.",
|
||||
"username-characters": "نام کاربری فقط میتواند شامل حروف انگلیسی، اعداد و آندرلاین باشد.",
|
||||
"username-short": "نام کاربری باید حداقل 3 کاراکتر باشد.",
|
||||
"username-long": "نام کاربری حداکثر 30 کاراکتر است.",
|
||||
"national-id-length": "کد ملی باید 10 رقم باشد.",
|
||||
"national-id-invalid": "کد ملی معتبر نیست.",
|
||||
"id-card-required": "تصویر کارت ملی را بارگذاری کنید.",
|
||||
"id-card-type": "فقط فایلهای JPG یا PNG مجاز هستند.",
|
||||
"id-card-size": "حجم فایل نباید بیشتر از 5 مگابایت باشد."
|
||||
}
|
||||
}
|
||||
|
|
@ -50,5 +50,25 @@
|
|||
"description": "اگر فکر میکنید اشتباهی رخ داده است، با پشتیبانی تماس بگیرید."
|
||||
},
|
||||
"home": "بازگشت به خانه"
|
||||
},
|
||||
"action": {
|
||||
"try-again": "تلاش مجدد",
|
||||
"reload": "بارگذاری دوباره"
|
||||
},
|
||||
"support": {
|
||||
"with-reference": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، کد پیگیری {{referenceId}} را به پشتیبانی بگویید.",
|
||||
"without-reference": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید."
|
||||
},
|
||||
"auth": {
|
||||
"code-wrong": "کد واردشده اشتباه است. لطفاً دوباره تلاش کنید.",
|
||||
"code-expired": "کد منقضی شده. یک کد جدید دریافت کنید.",
|
||||
"blocked": "تعداد تلاشهای مجاز به پایان رسید.",
|
||||
"blocked-hint": "10 دقیقه دیگر تلاش کنید.",
|
||||
"cooldown": "برای این شماره همین حالا کد ارسال شده است.",
|
||||
"phone-unknown": "حسابی با این شماره وجود ندارد.",
|
||||
"phone-taken": "این شماره قبلاً ثبت شده است.",
|
||||
"username-taken": "این نام کاربری قبلاً انتخاب شده. نام دیگری امتحان کنید.",
|
||||
"registration-expired": "زمان ثبتنام به پایان رسید.",
|
||||
"file-too-large": "حجم فایل نباید بیشتر از 5 مگابایت باشد."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import faAuth from './fa/auth.json';
|
||||
import faCommon from './fa/common.json';
|
||||
import faErrors from './fa/errors.json';
|
||||
|
||||
/** The product is Persian only; every route loads both namespaces, because any route can fail. */
|
||||
/** The product is Persian only; every route loads every namespace, because any route can fail. */
|
||||
export const DEFAULT_LOCALE = 'fa';
|
||||
|
||||
export const DEFAULT_NAMESPACE = 'common';
|
||||
|
|
@ -9,6 +10,7 @@ export const DEFAULT_NAMESPACE = 'common';
|
|||
export const resources = {
|
||||
fa: {
|
||||
common: faCommon,
|
||||
auth: faAuth,
|
||||
errors: faErrors,
|
||||
},
|
||||
} as const;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
import { classifyError, describeError } from '@lumina/libs/error-handler';
|
||||
import { isHttpError } from '@lumina/libs/http';
|
||||
import type { FieldValues, Path, UseFormReturn } from 'react-hook-form';
|
||||
|
||||
import { showActionError } from './show-action-error';
|
||||
import { asTranslateFn } from './translate-message';
|
||||
import type { ShowActionErrorOptions } from './show-action-error';
|
||||
|
||||
/**
|
||||
* A failed form submission: each server field error goes under its field (the first one gets
|
||||
* focus), field errors for fields the form doesn't render and errors about the whole submission go
|
||||
* to the form alert (`root.server`), then the action-error toast. A field counts as rendered when
|
||||
* it has a value, so every form sets `defaultValues` for every field. The form keeps every value.
|
||||
*/
|
||||
export function applyServerErrors<T extends FieldValues>(
|
||||
form: UseFormReturn<T>,
|
||||
error: unknown,
|
||||
options: ShowActionErrorOptions,
|
||||
): void {
|
||||
if (classifyError(error).action === 'silent') return;
|
||||
|
||||
const unmatched: string[] = [];
|
||||
let hasFieldError = false;
|
||||
const fieldErrors = isHttpError(error) ? (error.fieldErrors ?? {}) : {};
|
||||
for (const [field, message] of Object.entries(fieldErrors)) {
|
||||
if (form.getValues(field as Path<T>) === undefined) {
|
||||
unmatched.push(message);
|
||||
continue;
|
||||
}
|
||||
form.setError(
|
||||
field as Path<T>,
|
||||
{ type: 'server', message },
|
||||
{ shouldFocus: !hasFieldError },
|
||||
);
|
||||
hasFieldError = true;
|
||||
}
|
||||
|
||||
if (!hasFieldError && unmatched.length === 0) {
|
||||
unmatched.push(
|
||||
describeError(error, asTranslateFn(options.t)).message ??
|
||||
options.failedMessage,
|
||||
);
|
||||
}
|
||||
if (unmatched.length > 0) {
|
||||
form.setError('root.server', {
|
||||
type: 'server',
|
||||
message: unmatched.join(' '),
|
||||
});
|
||||
}
|
||||
|
||||
showActionError(error, options);
|
||||
}
|
||||
|
|
@ -1,3 +1,8 @@
|
|||
export { applyServerErrors } from './apply-server-errors';
|
||||
export { toApiUrl } from './api-url';
|
||||
export { toE164Mobile } from './mobile';
|
||||
export { formatMobile, toE164Mobile, toLocalMobile } from './mobile';
|
||||
export { renameFieldErrors } from './rename-field-errors';
|
||||
export { showActionError } from './show-action-error';
|
||||
export type { ShowActionErrorOptions } from './show-action-error';
|
||||
export { asTranslateFn, translateMessage } from './translate-message';
|
||||
export type { AnyTranslate } from './translate-message';
|
||||
|
|
|
|||
|
|
@ -1,12 +1,34 @@
|
|||
import { latinDigits } from '@lumina/tools/format';
|
||||
|
||||
const MOBILE_PATTERN = /^(?:\+98|0098|98|0)?(9\d{9})$/;
|
||||
|
||||
/** Latin digits without spaces, dashes or brackets. */
|
||||
function bareDigits(value: string): string {
|
||||
return latinDigits(value).replace(/[\s()-]/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* An Iranian mobile number as typed (`۰۹۱۲ ۳۴۵ ۶۷۸۹`, `0912…`, `+98912…`, `98912…`) → E.164
|
||||
* (`+989123456789`), the one form the API stores. Anything else is returned trimmed, so the
|
||||
* server can reject it with its own message.
|
||||
*/
|
||||
export function toE164Mobile(value: string): string {
|
||||
const digits = latinDigits(value).replace(/[\s()-]/g, '');
|
||||
const match = /^(?:\+98|0098|98|0)?(9\d{9})$/.exec(digits);
|
||||
const digits = bareDigits(value);
|
||||
const match = MOBILE_PATTERN.exec(digits);
|
||||
return match ? `+98${match[1]}` : digits;
|
||||
}
|
||||
|
||||
/** The same number in its local form (`09123456789`), the one the pages keep. Anything else: its bare digits. */
|
||||
export function toLocalMobile(value: string): string {
|
||||
const digits = bareDigits(value);
|
||||
const match = MOBILE_PATTERN.exec(digits);
|
||||
return match ? `0${match[1]}` : digits;
|
||||
}
|
||||
|
||||
/** `09123456789` → `0912 345 6789`, shown left to right; the font draws the digits in Persian. */
|
||||
export function formatMobile(value: string): string {
|
||||
const local = toLocalMobile(value);
|
||||
return /^09\d{9}$/.test(local)
|
||||
? `${local.slice(0, 4)} ${local.slice(4, 7)} ${local.slice(7)}`
|
||||
: value;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
import { showToast } from '@lumina/island/molecules/toast';
|
||||
import { describeError, handleError } from '@lumina/libs/error-handler';
|
||||
|
||||
import { asTranslateFn } from './translate-message';
|
||||
import type { AnyTranslate } from './translate-message';
|
||||
|
||||
export type ShowActionErrorOptions = {
|
||||
t: AnyTranslate;
|
||||
/** What failed, naming the object: «کد تأیید ارسال نشد». */
|
||||
failedMessage: string;
|
||||
/** Only when running the action again is safe. */
|
||||
retry?: () => void;
|
||||
/** Refetches the data the action changed, for 409 and 404. */
|
||||
reload?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The one error toast for a failed action. It handles the error once, says what failed, adds the
|
||||
* server's message and hint (or a support sentence with the reference code), and offers the button
|
||||
* the error's retry kind allows. It stays until dismissed; a repeated failure replaces it.
|
||||
*/
|
||||
export function showActionError(
|
||||
error: unknown,
|
||||
{ t: anyT, failedMessage, retry, reload }: ShowActionErrorOptions,
|
||||
): void {
|
||||
const t = asTranslateFn(anyT);
|
||||
const errorClass = handleError(error, { where: 'action' });
|
||||
if (errorClass.action === 'silent') return;
|
||||
|
||||
const { message, hint, referenceId } = describeError(error, t);
|
||||
const details = [message, hint].filter(Boolean).join(' ');
|
||||
const action =
|
||||
errorClass.retry === 'again' && retry
|
||||
? { label: t('errors:action.try-again'), onClick: retry }
|
||||
: errorClass.retry === 'reload' && reload
|
||||
? { label: t('errors:action.reload'), onClick: reload }
|
||||
: undefined;
|
||||
|
||||
showToast({
|
||||
id: `action-error:${failedMessage}`,
|
||||
tone: 'error',
|
||||
message: failedMessage,
|
||||
description:
|
||||
details ||
|
||||
(referenceId
|
||||
? t('errors:support.with-reference', { referenceId })
|
||||
: t('errors:support.without-reference')),
|
||||
action,
|
||||
duration: Infinity,
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import type { TranslateFn } from '@lumina/libs/error-handler';
|
||||
|
||||
/**
|
||||
* i18next's `t` from `useTranslation`, for any namespace. Its key types reject the keys the error
|
||||
* handler passes (`errors:http.network`), so the helpers here take it untyped.
|
||||
*/
|
||||
export type AnyTranslate = (...args: never[]) => unknown;
|
||||
|
||||
export function asTranslateFn(t: AnyTranslate): TranslateFn {
|
||||
return t as unknown as TranslateFn;
|
||||
}
|
||||
|
||||
/** `auth:validation.phone-invalid`, `errors:auth.code-wrong`: a namespace, a colon and a dotted key. */
|
||||
const KEY_PATTERN = /^[a-z]+:[\w.-]+$/;
|
||||
|
||||
/**
|
||||
* A form message as the field shows it. Validation messages and mapped server errors are i18n
|
||||
* keys and get translated; any other server text is already the user's language and passes
|
||||
* through.
|
||||
*/
|
||||
export function translateMessage(
|
||||
t: AnyTranslate,
|
||||
message: string | undefined,
|
||||
): string | undefined {
|
||||
if (!message) return undefined;
|
||||
return KEY_PATTERN.test(message) ? asTranslateFn(t)(message) : message;
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
import * as v from 'valibot';
|
||||
|
||||
import { mobileNumber, nationalId, persianName } from './base-validations';
|
||||
import {
|
||||
ACCOUNT_TYPES,
|
||||
CODE_PATTERN,
|
||||
ID_CARD_IMAGE,
|
||||
USERNAME_LENGTH,
|
||||
USERNAME_PATTERN,
|
||||
} from './constants';
|
||||
|
||||
export const phoneSchema = v.object({
|
||||
phone: mobileNumber('auth:validation.phone-invalid'),
|
||||
});
|
||||
|
||||
export const codeSchema = v.object({
|
||||
code: v.pipe(
|
||||
v.string(),
|
||||
v.regex(CODE_PATTERN, 'auth:validation.code-length'),
|
||||
),
|
||||
});
|
||||
|
||||
/** Nothing is pre-selected, so the empty choice is the form's start. */
|
||||
export const accountTypeSchema = v.object({
|
||||
role: v.pipe(
|
||||
v.string(),
|
||||
v.nonEmpty('auth:validation.role-required'),
|
||||
v.picklist(ACCOUNT_TYPES, 'auth:validation.role-required'),
|
||||
),
|
||||
});
|
||||
|
||||
/** Stored lower-case, so capitals are taken as typed and lowered. */
|
||||
const username = v.pipe(
|
||||
v.string(),
|
||||
v.trim(),
|
||||
v.toLowerCase(),
|
||||
v.nonEmpty('auth:validation.username-required'),
|
||||
v.regex(USERNAME_PATTERN, 'auth:validation.username-characters'),
|
||||
v.minLength(USERNAME_LENGTH.min, 'auth:validation.username-short'),
|
||||
v.maxLength(USERNAME_LENGTH.max, 'auth:validation.username-long'),
|
||||
);
|
||||
|
||||
const names = {
|
||||
firstName: persianName(
|
||||
'auth:validation.required',
|
||||
'auth:validation.first-name-persian',
|
||||
),
|
||||
lastName: persianName(
|
||||
'auth:validation.required',
|
||||
'auth:validation.last-name-persian',
|
||||
),
|
||||
};
|
||||
|
||||
/** JPG or PNG up to 5 MB, checked when picked and again on submit. */
|
||||
export const idCardImage = v.pipe(
|
||||
v.nullable(v.file()),
|
||||
v.check((file) => file !== null, 'auth:validation.id-card-required'),
|
||||
v.transform((file) => file as File),
|
||||
v.file(),
|
||||
v.mimeType(ID_CARD_IMAGE.types, 'auth:validation.id-card-type'),
|
||||
v.maxSize(ID_CARD_IMAGE.maxBytes, 'auth:validation.id-card-size'),
|
||||
);
|
||||
|
||||
export const investorDetailsSchema = v.object({
|
||||
...names,
|
||||
username,
|
||||
});
|
||||
|
||||
export const creatorIdentitySchema = v.object({
|
||||
username,
|
||||
...names,
|
||||
nationalId: nationalId(
|
||||
'auth:validation.national-id-length',
|
||||
'auth:validation.national-id-invalid',
|
||||
),
|
||||
idCardFront: idCardImage,
|
||||
idCardBack: idCardImage,
|
||||
});
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import { latinDigits } from '@lumina/tools/format';
|
||||
import * as v from 'valibot';
|
||||
|
||||
import { toLocalMobile } from '../utils/mobile';
|
||||
import { NATIONAL_ID_LENGTH, PERSIAN_NAME_PATTERN } from './constants';
|
||||
import { isNationalId } from './national-id';
|
||||
|
||||
// Every message is an i18n key; the field translates it.
|
||||
|
||||
export const requiredString = (message: string) =>
|
||||
v.pipe(v.string(), v.trim(), v.nonEmpty(message));
|
||||
|
||||
/** Any way a mobile number is typed (Persian digits, +98, spaces) → `09XXXXXXXXX`. */
|
||||
export const mobileNumber = (message: string) =>
|
||||
v.pipe(v.string(), v.transform(toLocalMobile), v.regex(/^09\d{9}$/, message));
|
||||
|
||||
export const persianName = (required: string, persian: string) =>
|
||||
v.pipe(
|
||||
v.string(),
|
||||
v.trim(),
|
||||
v.nonEmpty(required),
|
||||
v.regex(PERSIAN_NAME_PATTERN, persian),
|
||||
);
|
||||
|
||||
/** 10 digits (Persian digits accepted) with a matching check digit. */
|
||||
export const nationalId = (length: string, invalid: string) =>
|
||||
v.pipe(
|
||||
v.string(),
|
||||
v.transform((value) => latinDigits(value).replace(/\s/g, '')),
|
||||
v.regex(new RegExp(`^\\d{${NATIONAL_ID_LENGTH}}$`), length),
|
||||
v.check(isNationalId, invalid),
|
||||
);
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
/** Persian letters, the space and the zero-width non-joiner (ZWNJ), for names. */
|
||||
export const PERSIAN_NAME_PATTERN = /^[ء-غف-يً-ْآپچژکگی ]+$/;
|
||||
|
||||
/** Lower-case Latin letters, digits and the underscore. */
|
||||
export const USERNAME_PATTERN = /^[a-z0-9_]+$/;
|
||||
|
||||
export const USERNAME_LENGTH = { min: 3, max: 30 } as const;
|
||||
|
||||
export const NATIONAL_ID_LENGTH = 10;
|
||||
|
||||
/** The national ID card images the API accepts. */
|
||||
export const ID_CARD_IMAGE = {
|
||||
types: ['image/jpeg', 'image/png'],
|
||||
maxBytes: 5 * 1024 * 1024,
|
||||
} as const;
|
||||
|
||||
export const ACCOUNT_TYPES = ['investor', 'creator'] as const;
|
||||
|
||||
export const CODE_PATTERN = /^\d{6}$/;
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
export {
|
||||
accountTypeSchema,
|
||||
codeSchema,
|
||||
creatorIdentitySchema,
|
||||
idCardImage,
|
||||
investorDetailsSchema,
|
||||
phoneSchema,
|
||||
} from './auth-validations';
|
||||
export { ID_CARD_IMAGE, USERNAME_LENGTH } from './constants';
|
||||
export type {
|
||||
AccountTypeFormOutput,
|
||||
AccountTypeFormValues,
|
||||
CodeFormValues,
|
||||
CreatorIdentityFormOutput,
|
||||
CreatorIdentityFormValues,
|
||||
InvestorDetailsFormOutput,
|
||||
InvestorDetailsFormValues,
|
||||
PhoneFormOutput,
|
||||
PhoneFormValues,
|
||||
} from './types';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue