mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-26 19:12:50 +00:00
Refactor imports and improve LoginPage validation logic
This commit is contained in:
@@ -1,17 +1,31 @@
|
||||
export { AuthConfigProvider, useAuthConfig } from './lib/AuthConfig';
|
||||
export type { AuthConfigValue } from './lib/AuthConfig';
|
||||
export { AuthShell, BrandMark } from './lib/components/AuthShell';
|
||||
export { ProtectedRoute } from './lib/components/ProtectedRoute';
|
||||
export { AuthBootstrap } from './lib/components/AuthBootstrap';
|
||||
export { LoginPage } from './lib/pages/LoginPage';
|
||||
export { SignupPage } from './lib/pages/SignupPage';
|
||||
export { ForgotPasswordPage } from './lib/pages/ForgotPasswordPage';
|
||||
export { SetPasswordPage } from './lib/pages/SetPasswordPage';
|
||||
export { OTPVerificationPage } from './lib/pages/OTPVerificationPage';
|
||||
export { authReducer, loginSuccess, setUser, setCurrentProfile, clearCurrentProfile, logout, hydrateAuth } from './lib/store/auth.slice';
|
||||
export { signupReducer, setSignupData, setSignupStep, resetSignup } from './lib/store/signup.slice';
|
||||
export { usePermissions } from './lib/hooks/usePermissions';
|
||||
export type { PermissionSet } from './lib/hooks/usePermissions';
|
||||
export { AuthConfigProvider, useAuthConfig } from "./lib/AuthConfig";
|
||||
export type { AuthConfigValue } from "./lib/AuthConfig";
|
||||
export { AuthShell, BrandMark } from "./lib/components/AuthShell";
|
||||
export { ProtectedRoute } from "./lib/components/ProtectedRoute";
|
||||
export { AuthBootstrap } from "./lib/components/AuthBootstrap";
|
||||
export { LoginPage } from "./lib/pages/LoginPage";
|
||||
export { SignupPage } from "./lib/pages/SignupPage";
|
||||
export { ForgotPasswordPage } from "./lib/pages/ForgotPasswordPage";
|
||||
export { SetPasswordPage } from "./lib/pages/SetPasswordPage";
|
||||
export { OTPVerificationPage } from "./lib/pages/OTPVerificationPage";
|
||||
export {
|
||||
authReducer,
|
||||
loginSuccess,
|
||||
setUser,
|
||||
setCurrentProfile,
|
||||
clearCurrentProfile,
|
||||
logout,
|
||||
hydrateAuth,
|
||||
setToken,
|
||||
} from "./lib/store/auth.slice";
|
||||
export {
|
||||
signupReducer,
|
||||
setSignupData,
|
||||
setSignupStep,
|
||||
resetSignup,
|
||||
} from "./lib/store/signup.slice";
|
||||
export { usePermissions } from "./lib/hooks/usePermissions";
|
||||
export type { PermissionSet } from "./lib/hooks/usePermissions";
|
||||
export {
|
||||
useCurrentProfile,
|
||||
useGetMyProfileQuery,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Anchor,
|
||||
@@ -11,29 +11,56 @@ import {
|
||||
Text,
|
||||
TextInput,
|
||||
Title,
|
||||
} from '@mantine/core';
|
||||
} from "@mantine/core";
|
||||
import {
|
||||
IconArrowRight,
|
||||
IconDeviceMobile,
|
||||
IconLock,
|
||||
IconMail,
|
||||
} from '@tabler/icons-react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useApiMutation } from '@ema-platform/api';
|
||||
import { notify } from '@ema-platform/ui';
|
||||
import { AuthShell } from '../components/AuthShell';
|
||||
import { loginSuccess, setUser, setCurrentProfile } from '../store/auth.slice';
|
||||
import type { LoginPayload, AuthUser, CurrentProfile } from '../types/auth.types';
|
||||
import { useAuthConfig } from '../AuthConfig';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
} from "@tabler/icons-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { useNavigate, Link } from "react-router-dom";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useApiMutation } from "@ema-platform/api";
|
||||
import { notify, useErrorHandler } from "@ema-platform/ui";
|
||||
import { AuthShell } from "../components/AuthShell";
|
||||
import { loginSuccess, setUser, setCurrentProfile } from "../store/auth.slice";
|
||||
import type {
|
||||
LoginPayload,
|
||||
AuthUser,
|
||||
CurrentProfile,
|
||||
} from "../types/auth.types";
|
||||
import { useAuthConfig } from "../AuthConfig";
|
||||
import { authStorage } from "../utils/auth-storage";
|
||||
const emailOrPhone = z
|
||||
.string()
|
||||
.trim()
|
||||
.transform((value) => {
|
||||
// Convert 09xxxxxxxx -> +2519xxxxxxxx
|
||||
if (/^09\d{8}$/.test(value)) {
|
||||
return `+251${value.substring(1)}`;
|
||||
}
|
||||
|
||||
return value;
|
||||
})
|
||||
.refine(
|
||||
(value) => {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
const phoneRegex = /^\+2519\d{8}$/;
|
||||
|
||||
return emailRegex.test(value) || phoneRegex.test(value);
|
||||
},
|
||||
{
|
||||
message: "Enter a valid email or phone number (+2519xxxxxxxx)",
|
||||
},
|
||||
);
|
||||
const schema = z.object({
|
||||
email: z.string().email({ message: 'Enter a valid email' }),
|
||||
password: z.string().min(5, { message: 'Password must be at least 6 characters' }),
|
||||
email: emailOrPhone,
|
||||
password: z
|
||||
.string()
|
||||
.min(8, { message: "Password must be at least 8 characters" }),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
@@ -46,9 +73,7 @@ export function LoginPage() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [rememberMe, setRememberMe] = useState(true);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
// MFA second step: set once /auth/login answers `mfaRequired` (US-IAM-006).
|
||||
const [mfaEmail, setMfaEmail] = useState<string | null>(null);
|
||||
const [mfaOtp, setMfaOtp] = useState('');
|
||||
const { handleError } = useErrorHandler();
|
||||
const [loginTrigger] = useApiMutation<LoginPayload>();
|
||||
const [meTrigger] = useApiMutation<AuthUser>();
|
||||
const [profileTrigger] = useApiMutation<{ profile: CurrentProfile | null }>();
|
||||
@@ -65,57 +90,15 @@ export function LoginPage() {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await loginTrigger({
|
||||
url: '/auth/login',
|
||||
method: 'POST',
|
||||
url: "/auth/login",
|
||||
method: "POST",
|
||||
body: values,
|
||||
}).unwrap();
|
||||
|
||||
// MFA-enabled accounts get no tokens yet — an OTP has been sent, and
|
||||
// the session only exists once /auth/mfa-verify accepts it (US-IAM-006).
|
||||
if (data.mfaRequired) {
|
||||
setMfaEmail(values.email);
|
||||
notify.success('Enter the verification code we just sent you');
|
||||
return;
|
||||
}
|
||||
await completeSession(data);
|
||||
} catch (err: unknown) {
|
||||
const msg =
|
||||
(err as { data?: { message?: string } })?.data?.message ??
|
||||
(err instanceof Error ? err.message : 'Something went wrong');
|
||||
setServerError(msg);
|
||||
notify.error(msg);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const verifyMfa = async () => {
|
||||
if (!mfaEmail || !mfaOtp.trim()) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await loginTrigger({
|
||||
url: '/auth/mfa-verify',
|
||||
method: 'POST',
|
||||
body: { email: mfaEmail, otp: mfaOtp.trim() },
|
||||
}).unwrap();
|
||||
// The second factor proves possession of the verified phone.
|
||||
await completeSession({ ...data, isPhoneNumberVerified: true });
|
||||
} catch (err: unknown) {
|
||||
const msg =
|
||||
(err as { data?: { message?: string } })?.data?.message ??
|
||||
'Verification failed';
|
||||
setServerError(msg === 'unable_to_log_in' ? 'Invalid or expired code' : msg);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const completeSession = async (data: LoginPayload) => {
|
||||
dispatch(loginSuccess(data));
|
||||
dispatch(loginSuccess(data));
|
||||
|
||||
const me = await meTrigger({
|
||||
url: '/auth/me',
|
||||
method: 'GET',
|
||||
url: "/auth/me",
|
||||
method: "GET",
|
||||
}).unwrap();
|
||||
dispatch(setUser(me));
|
||||
|
||||
@@ -126,8 +109,8 @@ export function LoginPage() {
|
||||
// `useCurrentProfile` resolves it again on demand.
|
||||
try {
|
||||
const { profile } = await profileTrigger({
|
||||
url: '/profiles/me',
|
||||
method: 'GET',
|
||||
url: "/profiles/me",
|
||||
method: "GET",
|
||||
}).unwrap();
|
||||
if (profile) {
|
||||
authStorage.setProfileId(profile.id);
|
||||
@@ -137,17 +120,23 @@ export function LoginPage() {
|
||||
// Offline or a 5xx — the portal still works; the resolver retries.
|
||||
}
|
||||
|
||||
if (!me.isPhoneNumberVerified) {
|
||||
navigate('/otp-verify', {
|
||||
state: {
|
||||
email: me.email,
|
||||
phoneNumber: me.phoneNumber,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!me.isPhoneNumberVerified) {
|
||||
navigate("/otp-verify", {
|
||||
state: {
|
||||
email: me.email,
|
||||
phoneNumber: me.phoneNumber,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
navigate(loginRedirectPath);
|
||||
navigate(loginRedirectPath);
|
||||
} catch (err: unknown) {
|
||||
setServerError(handleError(err));
|
||||
} finally {
|
||||
localStorage.setItem("rememberMe", String(rememberMe));
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -163,47 +152,16 @@ export function LoginPage() {
|
||||
</div>
|
||||
|
||||
{serverError && (
|
||||
<Alert variant="light" color="red" withCloseButton onClose={() => setServerError(null)}>
|
||||
<Alert
|
||||
variant="light"
|
||||
color="red"
|
||||
withCloseButton
|
||||
onClose={() => setServerError(null)}
|
||||
>
|
||||
{serverError}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{mfaEmail ? (
|
||||
<Stack gap="md">
|
||||
<Alert variant="light" color="blue" icon={<IconDeviceMobile size={18} />}>
|
||||
This account requires a second factor. Enter the code we sent to
|
||||
your registered phone.
|
||||
</Alert>
|
||||
<TextInput
|
||||
label="Verification code"
|
||||
placeholder="6-digit code"
|
||||
size="md"
|
||||
value={mfaOtp}
|
||||
onChange={(e) => setMfaOtp(e.currentTarget.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && verifyMfa()}
|
||||
/>
|
||||
<Button
|
||||
size="md"
|
||||
loading={isLoading}
|
||||
disabled={!mfaOtp.trim()}
|
||||
onClick={verifyMfa}
|
||||
rightSection={<IconArrowRight size={18} />}
|
||||
>
|
||||
Verify and sign in
|
||||
</Button>
|
||||
<Anchor
|
||||
size="sm"
|
||||
ta="center"
|
||||
onClick={() => {
|
||||
setMfaEmail(null);
|
||||
setMfaOtp('');
|
||||
setServerError(null);
|
||||
}}
|
||||
>
|
||||
Back to sign in
|
||||
</Anchor>
|
||||
</Stack>
|
||||
) : (
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
@@ -212,7 +170,7 @@ export function LoginPage() {
|
||||
size="md"
|
||||
leftSection={<IconMail size={18} />}
|
||||
error={errors.email?.message}
|
||||
{...register('email')}
|
||||
{...register("email")}
|
||||
/>
|
||||
<PasswordInput
|
||||
label="Password"
|
||||
@@ -220,7 +178,7 @@ export function LoginPage() {
|
||||
size="md"
|
||||
leftSection={<IconLock size={18} />}
|
||||
error={errors.password?.message}
|
||||
{...register('password')}
|
||||
{...register("password")}
|
||||
/>
|
||||
|
||||
<Group justify="space-between">
|
||||
@@ -253,23 +211,9 @@ export function LoginPage() {
|
||||
</Button>
|
||||
</Stack>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<Divider label="or" labelPosition="center" />
|
||||
|
||||
<Button
|
||||
variant="default"
|
||||
fullWidth
|
||||
size="md"
|
||||
leftSection={<IconDeviceMobile size={18} />}
|
||||
onClick={() => notify.info('Phone sign-in is coming soon.')}
|
||||
>
|
||||
Sign in with phone number
|
||||
</Button>
|
||||
|
||||
{enableSignup && (
|
||||
<Text ta="center" size="sm" c="dimmed">
|
||||
Don't have an account?{' '}
|
||||
Don't have an account?{" "}
|
||||
<Anchor component={Link} to="/signup" fw={700}>
|
||||
Create one
|
||||
</Anchor>
|
||||
@@ -278,4 +222,4 @@ export function LoginPage() {
|
||||
</Stack>
|
||||
</AuthShell>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user