Merge pull request #15 from rkheftan/feat/auth

Feat/auth
This commit is contained in:
SajadMRjl
2025-08-16 02:45:33 +03:30
committed by GitHub
29 changed files with 765 additions and 1040 deletions

7
.env
View File

@@ -1 +1,6 @@
VITE_GOOGLE_CLIENT_ID=https://272098283932-bft2gvlgjn8edopg0lnqjq1i9ekdmipt.apps.googleusercontent.com/
VITE_GOOGLE_CLIENT_ID=https://272098283932-bft2gvlgjn8edopg0lnqjq1i9ekdmipt.apps.googleusercontent.com/
VITE_DEFUALT_AUTH_RETURN_URL=/setting/profile
VITE_API_URL=https://accounts.business-harmony.com/api/
VITE_IDENTITY_URL=https://accounts.business-harmony.com/connect/token
VITE_IDENTITY_CLIENT_ID=harmony_identity
VITE_IDENTITY_SCOPE=openid profile offline_access harmony_identity

1049
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,7 +7,8 @@
"loginWithGoogle": "Login with google",
"emailIsInvalid": "Email is invalid",
"phoneNumberIsInvalid": "Phone number is invalid",
"thisFieldIsRequired": "This field is requried"
"thisFieldIsRequired": "This field is requried",
"googleAuthenticationFailed": "Login with google failed"
},
"verify": {
"verify": "Verify",

View File

@@ -246,5 +246,9 @@
"yemen": "Yemen",
"zambia": "Zambia",
"zimbabwe": "Zimbabwe"
},
"messages": {
"noResualtFound": "No result found.",
"serverError": "Internal server error"
}
}

View File

@@ -7,7 +7,8 @@
"loginWithGoogle": "ورود با گوگل",
"emailIsInvalid": "ایمیل وارد شده نامعتبر میباشد",
"phoneNumberIsInvalid": "شماره وارد شده نامعتبر میباشد",
"thisFieldIsRequired": "این فیلد الزامی است"
"thisFieldIsRequired": "این فیلد الزامی است",
"googleAuthenticationFailed": "ورود با گوگل با خطا مواجه شد"
},
"verify": {
"verify": "اعتبارسنجی",

View File

@@ -185,7 +185,8 @@
"zimbabwe": "زیمبابوه"
},
"messages": {
"noResualtFound": "نتیجه ای یافت نشد."
"noResualtFound": "نتیجه ای یافت نشد.",
"serverError": "خطای سمت سرور"
},
"side": {
"account": "حساب کاربری",

View File

@@ -0,0 +1,13 @@
import { getAccessToken } from '@/lib/apiClient';
import { type PropsWithChildren } from 'react';
import { Navigate } from 'react-router-dom';
export const ProtectedRoute = ({ children }: PropsWithChildren) => {
if (!getAccessToken()) {
// If no token, redirect to login page
return <Navigate to="/login" replace />;
}
// If token exists, render the children components
return children;
};

View File

@@ -1,7 +1,5 @@
import type { ApiResponse } from '@/types/apiResponse';
import type { FetchPromise } from '@/types/fetchPromise';
import type {
CompleteUserInformationRequest,
ConfirmEmailOtpRequest,
ConfirmForgetPassCodeRequest,
ConfirmOtpResponse,
@@ -19,86 +17,66 @@ import type {
SendForgetPassCodeRequest,
SendSmsOtpRequest,
} from '../types/userTypes';
const API_URL = 'https://accounts.business-harmony.com/api';
export const fetchRequest = <T = ApiResponse>(
url: string,
body: Object | null,
): FetchPromise<T> => {
return fetch(`${API_URL}/${url}`, {
body: JSON.stringify(body),
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
};
import apiClient from '@/lib/apiClient';
// GetUserStatusByPhoneNumberOrEmail
export const getUserStatusByPhoneNumberOrEmail = async (
body: GetUserStatusByPhoneNumberOrEmailRequest,
) => {
return fetchRequest<GetUserStatusByPhoneNumberOrEmailResponse>(
return apiClient.post<GetUserStatusByPhoneNumberOrEmailResponse>(
'User/GetUserStatusByPhoneNumberOrEmail',
body,
);
};
export const loginOrSignUpWithOtp = async (body: LoginRequest) => {
return fetchRequest<LoginResponse>('User/LoginOrSignUpWithOtp', body);
return apiClient.post<LoginResponse>('User/LoginOrSignUpWithOtp', body);
};
export const loginWithPassword = async (body: PasswordLoginRequest) => {
return fetchRequest<LoginResponse>('User/LoginWithPassword', body);
return apiClient.post<LoginResponse>('User/LoginWithPassword', body);
};
export const sendSmsOtp = async (body: SendSmsOtpRequest) => {
return fetchRequest<ApiResponse>('User/SendSmsOtp', body);
return apiClient.post<ApiResponse>('User/SendSmsOtp', body);
};
export const sendEmailOtp = async (body: SendEmailOtpRequest) => {
return fetchRequest<ApiResponse>('User/SendEmailOtp', body);
return apiClient.post<ApiResponse>('User/SendEmailOtp', body);
};
export const confirmSmsOtp = async (body: ConfirmSmsOtpRequest) => {
return fetchRequest<ConfirmOtpResponse>('User/ConfirmSmsOtp', body);
return apiClient.post<ConfirmOtpResponse>('User/ConfirmSmsOtp', body);
};
export const confirmEmailOtp = async (body: ConfirmEmailOtpRequest) => {
return fetchRequest<ConfirmOtpResponse>('User/ConfirmEmailOtp', body);
return apiClient.post<ConfirmOtpResponse>('User/ConfirmEmailOtp', body);
};
export const resetPassword = async (body: ResetPasswordRequest) => {
return fetchRequest<ResetPasswordResponse>('User/ResetPassword', body);
return apiClient.post<ResetPasswordResponse>('User/ResetPassword', body);
};
export const sendForgetPassCode = async (body: SendForgetPassCodeRequest) => {
return fetchRequest<ApiResponse>('User/SendForgetPassCode', body);
return apiClient.post<ApiResponse>('User/SendForgetPassCode', body);
};
export const confirmForgetPassCode = async (
body: ConfirmForgetPassCodeRequest,
) => {
return fetchRequest<ConfirmOtpResponse>('User/ConfirmForgetPassCode', body);
return apiClient.post<ConfirmOtpResponse>('User/ConfirmForgetPassCode', body);
};
export const loginOrSignUpWithGoogle = async (
body: LoginOrSignUpWithGoogleRequest,
) => {
return fetchRequest<LoginOrSignUpWithGoogleResponse>(
return apiClient.post<LoginOrSignUpWithGoogleResponse>(
'User/LoginOrSignUpWithGoogle',
body,
);
};
export const completeUserInformation = async (
body: CompleteUserInformationRequest,
) => {
return fetchRequest<ApiResponse>('User/CompleteUserInformation', body);
};
export const logOut = async () => {
return fetchRequest<ApiResponse>('User/LogOut', {});
return apiClient.post<ApiResponse>('User/LogOut', {});
};

View File

@@ -12,10 +12,10 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
export const AuthenticationSteps = (): JSX.Element => {
const navigate = useNavigate();
const DEFAULT_RETURN_URL = '/profile';
const [searchParams] = useSearchParams();
const authReturnUrl: string =
searchParams.get('returnUrl') ?? DEFAULT_RETURN_URL;
const authReturnUrl: string | null = searchParams.get('returnUrl');
const authReturnUrlOrDefault: string =
authReturnUrl ?? import.meta.env.VITE_DEFUALT_AUTH_RETURN_URL;
const [authMode, setAuthMode] = useState<AuthMode>('register');
const [authType, setAuthType] = useState<AuthType>('phone');
const [currentStep, setCurrentStep] = useState<AuthStep>('emailOrPhone');
@@ -66,8 +66,8 @@ export const AuthenticationSteps = (): JSX.Element => {
};
const redirectToReturnUrl = () => {
if (authReturnUrl === DEFAULT_RETURN_URL) {
navigate(DEFAULT_RETURN_URL);
if (!authReturnUrl) {
navigate(import.meta.env.VITE_DEFUALT_AUTH_RETURN_URL);
} else {
location.href = authReturnUrl;
}
@@ -77,7 +77,7 @@ export const AuthenticationSteps = (): JSX.Element => {
<>
{currentStep === 'emailOrPhone' && (
<LoginRegisterForm
authReturnUrl={authReturnUrl}
authReturnUrl={authReturnUrlOrDefault}
onGoogleAuthenticated={handleUserLoggedIn}
countryCode={countryCode}
setCountryCode={setCountryCode}
@@ -92,7 +92,7 @@ export const AuthenticationSteps = (): JSX.Element => {
{currentStep === 'verify' && (
<OtpVerifyForm
onVerifyPhoneNumber={handleConfrimPhoneNumber}
authReturnUrl={authReturnUrl}
authReturnUrl={authReturnUrlOrDefault}
countryCode={countryCode}
onOTPVerified={handleUserLoggedIn}
onEditValue={() => setCurrentStep('emailOrPhone')}
@@ -104,7 +104,7 @@ export const AuthenticationSteps = (): JSX.Element => {
{currentStep === 'enterPassword' && (
<EnterPasswordForm
authReturnUrl={authReturnUrl}
authReturnUrl={authReturnUrlOrDefault}
loginRegisterValue={loginRegisterValue}
countryCode={countryCode}
authType={authType}

View File

@@ -6,6 +6,7 @@ import { AuthenticationCard } from '../AuthenticationCard';
import { CountryCodeSelector } from '../CountryCodeSelector';
import { sendSmsOtp } from '../../api/authorizationAPI';
import type { CountryCode } from '@/types/commonTypes';
import { useApi } from '@/hooks/useApi';
export interface CompleteSignUpProps {
email: string;
@@ -30,7 +31,7 @@ export const CompleteSignUp = ({
const inputRef = useRef<HTMLInputElement>(null);
const [touched, setTouched] = useState<boolean>(false);
const inputError: boolean = touched && !!error;
const [sendOtpLoading, setSendOtpLoading] = useState<boolean>(false);
const { loading: sendSmsLoading, execute: sendSmsCall } = useApi(sendSmsOtp);
const isPhoneValid = (code: string, phone: string) => {
const phoneNumber = parsePhoneNumberFromString(code + phone);
@@ -61,12 +62,8 @@ export const CompleteSignUp = ({
if (!value || !isPhoneValid(countryCode, value)) {
inputRef.current?.focus();
} else {
setSendOtpLoading(true);
await sendSmsOtp({ phoneNumber: countryCode + value });
await sendSmsCall({ phoneNumber: countryCode + value });
onCompleteSignUp(countryCode, value);
setSendOtpLoading(false);
}
};
@@ -110,7 +107,7 @@ export const CompleteSignUp = ({
sx={{ my: 4 }}
/>
<Button loading={sendOtpLoading} onClick={handleCompleteSignUp}>
<Button loading={sendSmsLoading} onClick={handleCompleteSignUp}>
{t('verify.confirmAndContinue')}
</Button>
</AuthenticationCard>

View File

@@ -10,7 +10,6 @@ import {
Typography,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { Toast } from '@/components/Toast';
import { Link } from 'react-router-dom';
import type { AuthType } from '../../types/authTypes';
import type { CountryCode, GUID } from '@/types/commonTypes';
@@ -20,6 +19,8 @@ import {
sendSmsOtp,
} from '../../api/authorizationAPI';
import type { PasswordLoginRequest } from '../../types/userTypes';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
export interface EnterPasswordFormProps {
onEditValue: () => void;
@@ -47,11 +48,16 @@ export const EnterPasswordForm = ({
const [inputTouched, setInputTouched] = useState<boolean>(false);
const [showPassword, setShowPassword] = useState<boolean>(false);
const inputRef = useRef<HTMLInputElement>(null);
const [loginLoading, setLoginLoading] = useState<boolean>(false);
const [isLoginStatusSuccess, setIsLoginStatusSuccess] = useState<boolean>();
const [loginAlertOpen, setLoginAlertOpen] = useState<boolean>(false);
const [loginFailedMessage, setLoginFailedMessage] = useState<string>('');
const [sendOtpLoading, setSendOtpLoading] = useState<boolean>(false);
const toast = useToast();
const { loading: smsResendLoading, execute: smsResendCall } =
useApi(sendSmsOtp);
const { loading: emailResendLoading, execute: emailResendCall } =
useApi(sendEmailOtp);
const {
data: loginWithPassResult,
loading: loginWithPassLoading,
execute: loginWithPassCall,
} = useApi(loginWithPassword);
const handleBlur = () => {
setInputTouched(true);
@@ -61,8 +67,6 @@ export const EnterPasswordForm = ({
if (!passValue) {
inputRef.current?.focus();
} else {
setLoginLoading(true);
const apiRequest: PasswordLoginRequest = {
phoneNumber:
authType === 'phone' ? countryCode + loginRegisterValue : undefined,
@@ -70,46 +74,38 @@ export const EnterPasswordForm = ({
password: passValue,
returnUrl: authReturnUrl,
};
const result = await loginWithPassword(apiRequest);
const jsonRes = await result.json();
await loginWithPassCall(apiRequest);
if (jsonRes.success) {
setIsLoginStatusSuccess(true);
onLoggedIn(jsonRes.userId);
if (!loginWithPassResult) return;
if (loginWithPassResult.success) {
onLoggedIn(loginWithPassResult.userId);
toast({
message: t('verify.youHaveSuccessfullyLoggedIn'),
severity: 'success',
});
} else {
setIsLoginStatusSuccess(false);
setLoginFailedMessage(jsonRes.message);
toast({
message: loginWithPassResult.message,
severity: 'error',
});
}
setLoginAlertOpen(true);
setLoginLoading(false);
}
};
const handleLoginWithOtp = async () => {
setSendOtpLoading(true);
if (authType === 'phone') {
await sendSmsOtp({ phoneNumber: countryCode + loginRegisterValue });
await smsResendCall({ phoneNumber: countryCode + loginRegisterValue });
} else {
await sendEmailOtp({ email: loginRegisterValue });
await emailResendCall({ email: loginRegisterValue });
}
setSendOtpLoading(false);
onLoginWithOTP();
};
return (
<AuthenticationCard>
<Toast
open={loginAlertOpen}
onClose={() => setLoginAlertOpen(false)}
color={!isLoginStatusSuccess ? 'error' : 'success'}
>
{!isLoginStatusSuccess
? loginFailedMessage
: t('verify.youHaveSuccessfullyLoggedIn')}
</Toast>
<Box
sx={{
display: 'flex',
@@ -128,7 +124,7 @@ export const EnterPasswordForm = ({
variant="outlined"
size="large"
sx={{ width: 'auto' }}
endIcon={<Edit2 />}
endIcon={<Icon Component={Edit2} />}
onClick={onEditValue}
>
{emailOrPhone}
@@ -159,7 +155,11 @@ export const EnterPasswordForm = ({
color="primary"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <Eye /> : <EyeSlash />}
{showPassword ? (
<Icon Component={Eye} />
) : (
<Icon Component={EyeSlash} />
)}
</IconButton>
),
},
@@ -171,14 +171,14 @@ export const EnterPasswordForm = ({
onClick={handleLoginWithOtp}
sx={{ width: 'auto', mb: 2 }}
variant="text"
loading={sendOtpLoading}
endIcon={<ArrowLeft />}
loading={emailResendLoading || smsResendLoading}
endIcon={<Icon Component={ArrowLeft} />}
>
{t('enterPassword.loginWithOneTimeCode')}
</Button>
<Stack spacing={1}>
<Button loading={loginLoading} onClick={handleSubmit}>
<Button loading={loginWithPassLoading} onClick={handleSubmit}>
{t('verify.confirmAndLogin')}
</Button>
<Link to="/forget-password">

View File

@@ -1,10 +1,12 @@
import { Button } from '@mui/material';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { GoogleCodeClientResponse } from '../../types/userTypes';
import { loginOrSignUpWithGoogle } from '../../api/authorizationAPI';
import type { GUID } from '@/types/commonTypes';
import { Google } from 'iconsax-react';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
export interface GoogleAuthenticationProps {
disabled: boolean;
@@ -18,9 +20,12 @@ export const GoogleAuthentication = ({
onGoogleAuthenticated,
}: GoogleAuthenticationProps) => {
const { t } = useTranslation('authentication');
const [loginWithGoogleLoading, setLoginWithGoogleLoading] =
useState<boolean>(false);
const {
data: loginWithGoogleResult,
loading: loginWithGoogleLoading,
execute: loginWithGoogleCall,
} = useApi(loginOrSignUpWithGoogle);
const toast = useToast();
const clientRef = useRef<any>(null);
useEffect(() => {
@@ -37,21 +42,21 @@ export const GoogleAuthentication = ({
ux_mode: 'popup',
response_type: 'id_token',
callback: async (resp: GoogleCodeClientResponse) => {
setLoginWithGoogleLoading(true);
const result = await loginOrSignUpWithGoogle({
await loginWithGoogleCall({
idToken: resp.id_token,
returnUrl: authReturnUrl,
});
const jsonRes = await result.json();
if (jsonRes.success) {
onGoogleAuthenticated(jsonRes.userId);
if (!loginWithGoogleResult) return;
if (loginWithGoogleResult.success) {
onGoogleAuthenticated(loginWithGoogleResult.userId);
} else {
// Todo: Add useToast to handle error
toast({
message: t('loginForm.googleAuthenticationFailed'),
severity: 'error',
});
}
setLoginWithGoogleLoading(false);
},
});
};
@@ -73,7 +78,7 @@ export const GoogleAuthentication = ({
disabled={disabled}
loading={loginWithGoogleLoading}
variant="outlined"
startIcon={<Google variant="Bold" />}
startIcon={<Icon Component={Google} variant="Bold" />}
>
{t('loginForm.loginWithGoogle')}
</Button>

View File

@@ -8,10 +8,11 @@ import { AuthenticationCard } from '../AuthenticationCard';
import { CountryCodeSelector } from '../CountryCodeSelector';
import type { UserStatus } from '../../types/userTypes';
import { getUserStatusByPhoneNumberOrEmail } from '../../api/authorizationAPI';
import { Toast } from '@/components/Toast';
import type { CountryCode, GUID } from '@/types/commonTypes';
import { GoogleAuthentication } from './GoogleAuthentication';
import { isPhoneNumber } from '@/utils/regexes/isValidPhoneNumber';
import { useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
export interface LoginRegisterFormProps {
loginRegisterValue: string;
@@ -36,14 +37,18 @@ export function LoginRegisterForm({
authReturnUrl,
onGoogleAuthenticated,
}: LoginRegisterFormProps) {
const [checkStatusLoading, setCheckStatusLoading] = useState<boolean>(false);
const { t } = useTranslation('authentication');
const textFieldRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string>();
const [touched, setTouched] = useState<boolean>(false);
const [errorMessage, setErrorMessage] = useState<string>();
const inputError: boolean = touched && !!error;
const toast = useToast();
const {
data: userStatus,
loading: userStatusLoading,
execute: execUserStatus,
} = useApi(getUserStatusByPhoneNumberOrEmail);
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = event.target.value;
@@ -88,20 +93,21 @@ export function LoginRegisterForm({
const handleSubmit = async () => {
if (validateInput(loginRegisterValue, authType, false)) {
setCheckStatusLoading(true);
const result = await getUserStatusByPhoneNumberOrEmail({
await execUserStatus({
phoneNumber:
authType === 'phone' ? countryCode + loginRegisterValue : undefined,
email: authType === 'email' ? loginRegisterValue : undefined,
});
const jsonResult = await result.json();
if (jsonResult.success) {
onLoginRegisterSubmit(loginRegisterValue, jsonResult.userStatus);
} else {
setErrorMessage(jsonResult.message);
if (!userStatus) {
return;
}
if (userStatus.success) {
onLoginRegisterSubmit(loginRegisterValue, userStatus.userStatus);
} else {
toast({ message: userStatus.message, severity: 'error' });
}
setCheckStatusLoading(false);
} else {
inputRef.current?.focus();
validateInput(loginRegisterValue, authType);
@@ -112,14 +118,6 @@ export function LoginRegisterForm({
return (
<AuthenticationCard>
<Toast
color="error"
onClose={() => setErrorMessage(undefined)}
open={!!errorMessage}
>
{errorMessage}
</Toast>
<Stack spacing={1}>
<Typography variant="h5">{t('loginForm.title')}</Typography>
<Typography variant="body2" color="text.secondary">
@@ -155,14 +153,14 @@ export function LoginRegisterForm({
/>
<Stack spacing={2}>
<Button loading={checkStatusLoading} onClick={handleSubmit}>
<Button loading={userStatusLoading} onClick={handleSubmit}>
{t('loginForm.submitButton')}
</Button>
<GoogleAuthentication
authReturnUrl={authReturnUrl}
onGoogleAuthenticated={onGoogleAuthenticated}
disabled={checkStatusLoading}
disabled={userStatusLoading}
/>
</Stack>
</AuthenticationCard>

View File

@@ -4,7 +4,6 @@ import { Edit2 } from 'iconsax-react';
import DigitInput from '@/components/components/DigitsInput';
import type { AuthMode, AuthType } from '../../types/authTypes';
import { useEffect, useState } from 'react';
import { Toast } from '@/components/Toast';
import { AuthenticationCard } from '../AuthenticationCard';
import type { LoginRequest } from '../../types/userTypes';
import {
@@ -13,6 +12,8 @@ import {
sendSmsOtp,
} from '../../api/authorizationAPI';
import type { CountryCode, GUID } from '@/types/commonTypes';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
interface OtpVerifyFormProps {
value: string;
@@ -37,15 +38,20 @@ export function OtpVerifyForm({
}: OtpVerifyFormProps) {
const [otpCode, setOtpCode] = useState<string>('');
const [otpDigitInvalid, setOtpDigitInvalid] = useState<boolean>(false);
const [verifyStatus, setVerifyStatus] = useState<'success' | 'failed'>();
const [errorMessage, setErrorMessage] = useState<string>();
const [verifyStatusLoading, setVerifyStatusLoading] =
useState<boolean>(false);
const [verifyAlertOpen, setVerifyAlertOpen] = useState<boolean>(false);
const [isStatusSuccess, setIsStatusSuccess] = useState<boolean>();
const { t } = useTranslation('authentication');
const [resendTimer, setResendTimer] = useState<number>(120);
const [canResend, setCanResend] = useState(false);
const [resendLoading, setResendLoading] = useState<boolean>(false);
const toast = useToast();
const { loading: smsResendLoading, execute: smsResendCall } =
useApi(sendSmsOtp);
const { loading: emailResendLoading, execute: emailResendCall } =
useApi(sendEmailOtp);
const {
data: loginSignUpResult,
loading: loginSignUpLoading,
execute: loginSignUpCall,
} = useApi(loginOrSignUpWithOtp);
useEffect(() => {
let interval: NodeJS.Timeout;
@@ -61,17 +67,14 @@ export function OtpVerifyForm({
}, [resendTimer]);
const handleResendOTPCode = async () => {
setResendLoading(true);
if (authType === 'phone') {
await sendSmsOtp({ phoneNumber: countryCode + value });
await smsResendCall({ phoneNumber: countryCode + value });
} else {
await sendEmailOtp({ email: value });
await emailResendCall({ email: value });
}
setResendTimer(120);
setCanResend(false);
setResendLoading(false);
};
const formatTime = (seconds: number) => {
@@ -90,7 +93,6 @@ export function OtpVerifyForm({
const handleLoginOrSignUp = async () => {
setOtpDigitInvalid(false);
setVerifyStatusLoading(true);
const loginRequest: LoginRequest = {
otpCode: otpCode,
@@ -98,27 +100,39 @@ export function OtpVerifyForm({
email: authType === 'email' ? value : undefined,
returnUrl: authReturnUrl,
};
const result = await loginOrSignUpWithOtp(loginRequest);
const jsonRes = await result.json();
await loginSignUpCall(loginRequest);
if (jsonRes.success) {
setVerifyStatus('success');
if (jsonRes.registeredWithOutPhoneNumber) {
onVerifyPhoneNumber(jsonRes.userId);
} else {
onOTPVerified(jsonRes.userId);
}
} else {
setVerifyStatus('failed');
setErrorMessage(jsonRes.message);
if (!loginSignUpResult) {
return;
}
setVerifyAlertOpen(true);
setVerifyStatusLoading(false);
if (loginSignUpResult && loginSignUpResult.success) {
setIsStatusSuccess(true);
if (loginSignUpResult.registeredWithOutPhoneNumber) {
onVerifyPhoneNumber(loginSignUpResult.userId);
} else {
onOTPVerified(loginSignUpResult.userId);
}
toast({
message:
authMode === 'login'
? t('verify.youHaveSuccessfullyLoggedIn')
: t('verify.youHaveSuccessfullySignedIn'),
severity: 'success',
});
} else {
setIsStatusSuccess(false);
toast({
message: loginSignUpResult.message,
severity: 'error',
});
}
};
const otpMessage = (): string => {
const otpMessageFn = (): string => {
if (authType === 'phone' && authMode === 'login') {
return t(
'verify.a4DigitVerificationCodeHasBeenSentToYourBobileNumberPleaseEnterIt',
@@ -140,26 +154,11 @@ export function OtpVerifyForm({
return '';
};
const toastMessage =
verifyStatus === 'failed'
? (errorMessage ?? t('verify.theVerificationCodeIsIncorrect'))
: verifyStatus === 'success' && authMode === 'register'
? t('verify.youHaveSuccessfullySignedIn')
: verifyStatus === 'success' && authMode === 'login'
? t('verify.youHaveSuccessfullyLoggedIn')
: '';
const otpMessage = otpMessageFn();
return (
<Stack alignItems="center">
<AuthenticationCard>
<Toast
open={verifyAlertOpen}
onClose={() => setVerifyAlertOpen(false)}
color={verifyStatus === 'failed' ? 'error' : 'success'}
>
{toastMessage}
</Toast>
<Box
sx={{
display: 'flex',
@@ -176,7 +175,7 @@ export function OtpVerifyForm({
variant="outlined"
size="large"
sx={{ textTransform: 'lowercase', width: 'auto' }}
endIcon={<Edit2 />}
endIcon={<Icon Component={Edit2} />}
onClick={onEditValue}
>
{authType === 'phone' ? countryCode + value : value}
@@ -184,16 +183,16 @@ export function OtpVerifyForm({
</Box>
<Typography variant="body2" color="textSecondary" sx={{ mt: 1 }}>
{otpMessage()}
{otpMessage}
</Typography>
<DigitInput
error={otpDigitInvalid || verifyStatus === 'failed'}
success={verifyStatus === 'success'}
error={otpDigitInvalid || isStatusSuccess === false}
success={isStatusSuccess === true}
onChange={(value) => setOtpCode(value)}
/>
<Button onClick={handleVerifyOTP} loading={verifyStatusLoading}>
<Button onClick={handleVerifyOTP} loading={loginSignUpLoading}>
{authMode === 'register'
? t('verify.confirmAndContinue')
: t('verify.confirmAndLogin')}
@@ -212,7 +211,7 @@ export function OtpVerifyForm({
<Button
variant="text"
loading={resendLoading}
loading={smsResendLoading || emailResendLoading}
sx={{ width: 'auto' }}
onClick={canResend ? handleResendOTPCode : undefined}
>

View File

@@ -3,11 +3,12 @@ import { Box, Button, Stack, Typography } from '@mui/material';
import { Edit2 } from 'iconsax-react';
import DigitInput from '@/components/components/DigitsInput';
import { useEffect, useState } from 'react';
import { Toast } from '@/components/Toast';
import { AuthenticationCard } from '../AuthenticationCard';
import type { ConfirmSmsOtpRequest } from '../../types/userTypes';
import { confirmSmsOtp, sendSmsOtp } from '../../api/authorizationAPI';
import type { CountryCode } from '@/types/commonTypes';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
interface VerifyPhoneNumberProps {
value: string;
@@ -24,15 +25,18 @@ export function VerifyPhoneNumber({
}: VerifyPhoneNumberProps) {
const [otpCode, setOtpCode] = useState<string>('');
const [otpDigitInvalid, setOtpDigitInvalid] = useState<boolean>(false);
const [verifyStatus, setVerifyStatus] = useState<'success' | 'failed'>();
const [errorMessage, setErrorMessage] = useState<string>();
const [verifyStatusLoading, setVerifyStatusLoading] =
useState<boolean>(false);
const [verifyAlertOpen, setVerifyAlertOpen] = useState<boolean>(false);
const [isStatusSuccess, setIsStatusSuccess] = useState<boolean>();
const { t } = useTranslation('authentication');
const [resendTimer, setResendTimer] = useState<number>(120);
const [canResend, setCanResend] = useState(false);
const [resendLoading, setResendLoading] = useState<boolean>(false);
const toast = useToast();
const { loading: smsResendLoading, execute: smsResendCall } =
useApi(sendSmsOtp);
const {
data: confirmSmsOtpResult,
loading: confirmSmsOtpLoading,
execute: confirmSmsOtpCall,
} = useApi(confirmSmsOtp);
useEffect(() => {
let interval: NodeJS.Timeout;
@@ -48,13 +52,10 @@ export function VerifyPhoneNumber({
}, [resendTimer]);
const handleResendOTPCode = async () => {
setResendLoading(true);
await sendSmsOtp({ phoneNumber: countryCode + value });
await smsResendCall({ phoneNumber: countryCode + value });
setResendTimer(120);
setCanResend(false);
setResendLoading(false);
};
const formatTime = (seconds: number) => {
@@ -68,47 +69,37 @@ export function VerifyPhoneNumber({
setOtpDigitInvalid(true);
} else {
setOtpDigitInvalid(false);
setVerifyStatusLoading(true);
const confirmSmsOtpRequest: ConfirmSmsOtpRequest = {
otpCode: otpCode,
phoneNumber: countryCode + value,
};
const result = await confirmSmsOtp(confirmSmsOtpRequest);
const jsonRes = await result.json();
await confirmSmsOtpCall(confirmSmsOtpRequest);
if (jsonRes.success) {
setVerifyStatus('success');
if (!confirmSmsOtpResult) return;
if (confirmSmsOtpResult.success) {
setIsStatusSuccess(true);
toast({
message: t('verify.youHaveSuccessfullyLoggedIn'),
severity: 'success',
});
onPhoneNumberVerified();
} else {
setVerifyStatus('failed');
setErrorMessage(jsonRes.message);
setIsStatusSuccess(false);
toast({
message:
confirmSmsOtpResult.message ??
t('verify.theVerificationCodeIsIncorrect'),
severity: 'error',
});
}
setVerifyAlertOpen(true);
setVerifyStatusLoading(false);
}
};
const verifyAlertMessage = (): string => {
if (verifyStatus === 'failed') {
return errorMessage ?? t('verify.theVerificationCodeIsIncorrect');
} else {
return t('verify.youHaveSuccessfullyLoggedIn');
}
};
return (
<Stack alignItems="center">
<AuthenticationCard>
<Toast
open={verifyAlertOpen}
onClose={() => setVerifyAlertOpen(false)}
color={verifyStatus === 'failed' ? 'error' : 'success'}
>
{verifyAlertMessage()}
</Toast>
<Box
sx={{
display: 'flex',
@@ -125,7 +116,7 @@ export function VerifyPhoneNumber({
variant="outlined"
size="large"
sx={{ textTransform: 'lowercase', width: 'auto' }}
endIcon={<Edit2 />}
endIcon={<Icon Component={Edit2} />}
onClick={onEditValue}
>
{countryCode + value}
@@ -139,12 +130,12 @@ export function VerifyPhoneNumber({
</Typography>
<DigitInput
error={otpDigitInvalid || verifyStatus === 'failed'}
success={verifyStatus === 'success'}
error={otpDigitInvalid || isStatusSuccess === false}
success={isStatusSuccess === true}
onChange={(value) => setOtpCode(value)}
/>
<Button onClick={handleVerifyOTP} loading={verifyStatusLoading}>
<Button onClick={handleVerifyOTP} loading={confirmSmsOtpLoading}>
{t('verify.confirmAndLogin')}
</Button>
</AuthenticationCard>
@@ -161,7 +152,7 @@ export function VerifyPhoneNumber({
<Button
variant="text"
loading={resendLoading}
loading={smsResendLoading}
sx={{ width: 'auto' }}
onClick={canResend ? handleResendOTPCode : undefined}
>

View File

@@ -15,6 +15,7 @@ import ReactCountryFlag from 'react-country-flag';
import { useTranslation } from 'react-i18next';
import { countries, type Country } from '../../../countries';
import type { CountryCode } from '@/types/commonTypes';
import { Icon } from '@rkheftan/harmony-ui';
interface CountryCodeSelectorProps {
show: boolean;
value: CountryCode;
@@ -114,7 +115,7 @@ export function CountryCodeSelector({
}}
>
{/* This inner Box prevents the content from being squeezed during the transition */}
<ArrowDown2 size="24" variant="Bold" />
<Icon Component={ArrowDown2} size="medium" variant="Bold" />
<Typography
variant="body1"

View File

@@ -20,6 +20,8 @@ import type { ResetPasswordRequest } from '../../types/userTypes';
import type { AuthType } from '../../types/authTypes';
import type { CountryCode } from '@/types/commonTypes';
import { resetPassword } from '../../api/authorizationAPI';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
export interface ChangePasswordProps {
onEditInfo: () => void;
@@ -48,15 +50,12 @@ export const ChangePassword = ({
useState<boolean>(false);
const inputRef = useRef<HTMLInputElement>(null);
const confirmInputRef = useRef<HTMLInputElement>(null);
const [changePasswordLoading, setChangePasswordLoading] =
useState<boolean>(false);
const [changePasswordStatus, setChangePasswordStatus] = useState<
'success' | 'failed'
>();
const [changePassAlertOpen, setChangePassAlertOpen] =
useState<boolean>(false);
const [changePassFailedMessage, setChangePassFailedMessage] =
useState<string>('');
const toast = useToast();
const {
data: resetPasswordData,
loading: resetPasswordLoading,
execute: resetPasswordCall,
} = useApi(resetPassword);
const passwordValidationRules = [
{ title: t('forgetPassword.includingANumber'), validator: containsNumber },
@@ -84,8 +83,6 @@ export const ChangePassword = ({
setConfirmInputTouched(true);
confirmInputRef.current?.focus();
} else {
setChangePasswordLoading(true);
const apiRequest: ResetPasswordRequest = {
email: infoType === 'email' ? forgettedPasswordInfo : undefined,
phoneNumber:
@@ -96,19 +93,22 @@ export const ChangePassword = ({
confirmNewPassword: confirmPassValue,
};
const result = await resetPassword(apiRequest);
const jsonRes = await result.json();
await resetPasswordCall(apiRequest);
if (jsonRes.success) {
setChangePasswordStatus('success');
if (!resetPasswordData) return;
if (resetPasswordData.success) {
onPasswordChanged();
toast({
message: t('forgetPassword.passwordChangedSuccessfully'),
severity: 'success',
});
} else {
setChangePasswordStatus('failed');
setChangePassFailedMessage(jsonRes.message);
toast({
message: resetPasswordData.message,
severity: 'error',
});
}
setChangePassAlertOpen(true);
setChangePasswordLoading(false);
}
};
@@ -123,16 +123,6 @@ export const ChangePassword = ({
return (
<AuthenticationCard>
<Toast
open={changePassAlertOpen}
onClose={() => setChangePassAlertOpen(false)}
color={changePasswordStatus === 'failed' ? 'error' : 'success'}
>
{changePasswordStatus === 'failed'
? changePassFailedMessage
: t('forgetPassword.passwordChangedSuccessfully')}
</Toast>
<Box
sx={{
display: 'flex',
@@ -151,7 +141,7 @@ export const ChangePassword = ({
variant="outlined"
size="large"
sx={{ textTransform: 'lowercase', width: 'auto' }}
endIcon={<Edit2 />}
endIcon={<Icon Component={Edit2} />}
onClick={onEditInfo}
>
{forgettedPasswordInfo}
@@ -177,14 +167,22 @@ export const ChangePassword = ({
startAdornment: confirmPassValue &&
isValidPassword(passValue) &&
passValue === confirmPassValue && (
<TickCircle variant="Bold" color={theme.palette.success.main} />
<Icon
Component={TickCircle}
variant="Bold"
color="success.main"
/>
),
endAdornment: passValue ? (
<IconButton
color="primary"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <Eye /> : <EyeSlash />}
{showPassword ? (
<Icon Component={Eye} />
) : (
<Icon Component={EyeSlash} />
)}
</IconButton>
) : (
''
@@ -198,12 +196,11 @@ export const ChangePassword = ({
<Stack spacing={1} sx={{ mt: 2 }}>
{passwordValidationRules.map((rule) => (
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<TickCircle
<Icon
Component={TickCircle}
variant={rule.validator(passValue) ? 'Bold' : 'Linear'}
color={
rule.validator(passValue)
? theme.palette.success.main
: theme.palette.primary.light
rule.validator(passValue) ? 'success.main' : 'primary.light'
}
/>
@@ -227,14 +224,22 @@ export const ChangePassword = ({
startAdornment: confirmPassValue &&
isValidPassword(passValue) &&
passValue === confirmPassValue && (
<TickCircle variant="Bold" color={theme.palette.success.main} />
<Icon
Component={TickCircle}
variant="Bold"
color="success.main"
/>
),
endAdornment: confirmPassValue ? (
<IconButton
color="primary"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
>
{showConfirmPassword ? <Eye /> : <EyeSlash />}
{showConfirmPassword ? (
<Icon Component={Eye} />
) : (
<Icon Component={EyeSlash} />
)}
</IconButton>
) : (
''
@@ -245,7 +250,7 @@ export const ChangePassword = ({
/>
<Stack spacing={1}>
<Button loading={changePasswordLoading} onClick={handleSubmit}>
<Button loading={resetPasswordLoading} onClick={handleSubmit}>
{t('forgetPassword.confirm')}
</Button>
</Stack>

View File

@@ -4,8 +4,10 @@ import { ForgettedPasswordInfo } from './ForgettedPasswordInfo';
import { ForgetPasswordOtp } from './ForgetPasswordOtp';
import { ChangePassword } from './ChangePassword';
import type { CountryCode } from '@/types/commonTypes';
import { useNavigate } from 'react-router-dom';
export const ForgetPasswordContainer = () => {
const navigate = useNavigate();
const [forgetPassCurrentStep, setForgetPassCurrentStep] = useState<
'enterInfo' | 'verifyOtp' | 'setPassword'
>('enterInfo');
@@ -27,7 +29,7 @@ export const ForgetPasswordContainer = () => {
};
const handlePasswordChanged = () => {
console.log('changingPasswordTo');
navigate('/login');
};
return (

View File

@@ -6,9 +6,17 @@ import type { AuthType } from '../../types/authTypes';
import { useEffect, useState } from 'react';
import { Toast } from '@/components/Toast';
import { AuthenticationCard } from '../AuthenticationCard';
import type { ConfirmForgetPassCodeRequest } from '../../types/userTypes';
import type {
ConfirmForgetPassCodeRequest,
SendForgetPassCodeRequest,
} from '../../types/userTypes';
import type { CountryCode } from '@/types/commonTypes';
import { confirmForgetPassCode } from '../../api/authorizationAPI';
import {
confirmForgetPassCode,
sendForgetPassCode,
} from '../../api/authorizationAPI';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
interface ForgetPasswordOtpProps {
forgettedPasswordInfo: string;
@@ -27,14 +35,21 @@ export function ForgetPasswordOtp({
}: ForgetPasswordOtpProps) {
const [otpCode, setOtpCode] = useState<string>('');
const [otpDigitInvalid, setOtpDigitInvalid] = useState<boolean>(false);
const [verifyStatus, setVerifyStatus] = useState<'failed' | 'success'>();
const [verifyStatusLoading, setVerifyStatusLoading] =
useState<boolean>(false);
const [verifyAlertMessage, setVerifyAlertMessage] = useState<string>();
const [isStatusSuccess, setIsStatusSuccess] = useState<boolean>();
const { t } = useTranslation('authentication');
const [resendTimer, setResendTimer] = useState<number>(120);
const [canResend, setCanResend] = useState(false);
const [resendLoading, setResendLoading] = useState<boolean>(false);
const toast = useToast();
const {
data: sendForgetPassCodeData,
loading: sendForgetPassCodeLoading,
execute: sendForgetPassCodeCall,
} = useApi(sendForgetPassCode);
const {
data: confirmForgetPassCodeData,
loading: confirmForgetPassCodeLoading,
execute: confirmForgetPassCodeCall,
} = useApi(confirmForgetPassCode);
useEffect(() => {
let interval: NodeJS.Timeout;
@@ -49,18 +64,16 @@ export function ForgetPasswordOtp({
return () => clearInterval(interval);
}, [resendTimer]);
const handleResendOTPCode = () => {
setResendLoading(true);
const handleResendOTPCode = async () => {
const sendCodeRequest: SendForgetPassCodeRequest = {
email: infoType === 'email' ? forgettedPasswordInfo : undefined,
phoneNumber:
infoType === 'phone' ? countryCode + forgettedPasswordInfo : undefined,
};
await sendForgetPassCodeCall(sendCodeRequest);
// TODO: Call API here instead of settimeout
setTimeout(() => {
console.log('resended');
setResendTimer(120);
setCanResend(false);
setResendLoading(false);
}, 1000);
setResendTimer(120);
setCanResend(false);
};
const formatTime = (seconds: number) => {
@@ -74,7 +87,6 @@ export function ForgetPasswordOtp({
setOtpDigitInvalid(true);
} else {
setOtpDigitInvalid(false);
setVerifyStatusLoading(true);
// Change setTimeout to api call
const apiRequest: ConfirmForgetPassCodeRequest = {
@@ -86,32 +98,26 @@ export function ForgetPasswordOtp({
code: otpCode,
};
const result = await confirmForgetPassCode(apiRequest);
const jsonRes = await result.json();
confirmForgetPassCodeCall(apiRequest);
if (jsonRes.success) {
setVerifyStatus('success');
if (!confirmForgetPassCodeData) return;
if (confirmForgetPassCodeData.success) {
setIsStatusSuccess(true);
onOTPVerified(otpCode);
} else {
setVerifyStatus('failed');
setVerifyAlertMessage(jsonRes.message);
setIsStatusSuccess(false);
toast({
message: confirmForgetPassCodeData.message,
severity: 'error',
});
}
setVerifyStatusLoading(false);
}
};
return (
<Stack alignItems="center">
<AuthenticationCard>
<Toast
open={!!verifyAlertMessage}
onClose={() => setVerifyAlertMessage(undefined)}
color={'error'}
>
{verifyAlertMessage}
</Toast>
<Box
sx={{
display: 'flex',
@@ -130,7 +136,7 @@ export function ForgetPasswordOtp({
variant="outlined"
size="large"
sx={{ textTransform: 'lowercase', width: 'auto' }}
endIcon={<Edit2 />}
endIcon={<Icon Component={Edit2} />}
onClick={onEditInfo}
>
{infoType === 'phone'
@@ -150,12 +156,15 @@ export function ForgetPasswordOtp({
</Typography>
<DigitInput
error={otpDigitInvalid || verifyStatus === 'failed'}
success={verifyStatus === 'success'}
error={otpDigitInvalid || isStatusSuccess === false}
success={isStatusSuccess === true}
onChange={(value) => setOtpCode(value)}
/>
<Button onClick={handleVerifyOTP} loading={verifyStatusLoading}>
<Button
onClick={handleVerifyOTP}
loading={confirmForgetPassCodeLoading}
>
{t('forgetPassword.confirm')}
</Button>
</AuthenticationCard>
@@ -172,7 +181,7 @@ export function ForgetPasswordOtp({
<Button
variant="text"
loading={resendLoading}
loading={sendForgetPassCodeLoading}
sx={{ width: 'auto' }}
onClick={canResend ? handleResendOTPCode : undefined}
>

View File

@@ -11,6 +11,8 @@ import { sendForgetPassCode } from '../../api/authorizationAPI';
import type { SendForgetPassCodeRequest } from '../../types/userTypes';
import { Toast } from '@/components/Toast';
import { isPhoneNumber } from '@/utils/regexes/isValidPhoneNumber';
import { useToast } from '@rkheftan/harmony-ui';
import { useApi } from '@/hooks/useApi';
export interface ForgettedPasswordInfoProps {
forgettedPasswordInfo: string;
@@ -36,9 +38,13 @@ export function ForgettedPasswordInfo({
const inputRef = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string>();
const [touched, setTouched] = useState<boolean>(false);
const [errorMessage, setErrorMessage] = useState<string>();
const [sendCodeLoading, setSendCodeLoading] = useState<boolean>(false);
const inputError: boolean = touched && !!error;
const toast = useToast();
const {
data: sendForgetPassCodeData,
loading: sendForgetPassCodeLoading,
execute: sendForgetPassCodeCall,
} = useApi(sendForgetPassCode);
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = event.target.value;
@@ -79,8 +85,6 @@ export function ForgettedPasswordInfo({
const handleSubmit = async () => {
if (validateInput(forgettedPasswordInfo, infoType, false)) {
setSendCodeLoading(true);
const sendCodeRequest: SendForgetPassCodeRequest = {
email: infoType === 'email' ? forgettedPasswordInfo : undefined,
phoneNumber:
@@ -88,14 +92,17 @@ export function ForgettedPasswordInfo({
? countryCode + forgettedPasswordInfo
: undefined,
};
const result = await sendForgetPassCode(sendCodeRequest);
const jsonRes = await result.json();
sendForgetPassCodeCall(sendCodeRequest);
if (!jsonRes.success) {
setErrorMessage(jsonRes.message);
if (!sendForgetPassCodeData) return;
if (!sendForgetPassCodeData.success) {
toast({
message: sendForgetPassCodeData.message,
severity: 'error',
});
}
setSendCodeLoading(false);
onVerifyOtp(forgettedPasswordInfo);
} else {
inputRef.current?.focus();
@@ -108,14 +115,6 @@ export function ForgettedPasswordInfo({
return (
<AuthenticationCard>
<Toast
color="error"
onClose={() => setErrorMessage(undefined)}
open={!!errorMessage}
>
{errorMessage}
</Toast>
<Stack spacing={1}>
<Typography variant="h5">
{t('forgetPassword.forgetPassword')}
@@ -155,7 +154,7 @@ export function ForgettedPasswordInfo({
/>
<Stack spacing={2}>
<Button loading={sendCodeLoading} onClick={handleSubmit}>
<Button loading={sendForgetPassCodeLoading} onClick={handleSubmit}>
{t('forgetPassword.confirm')}
</Button>
</Stack>

View File

@@ -0,0 +1,2 @@
export * from './routes/AuthenticationPage';
export * from './routes/ForgetPasswordPage';

View File

@@ -115,24 +115,3 @@ export interface LoginOrSignUpWithGoogleResponse extends ApiResponse {
completedUserInformation: boolean;
returnUrl: string;
}
// CompleteUserInformation
export interface CompleteUserInformationRequest {
firstName?: string;
lastName?: string;
gender?: Gender;
nationalCode?: string;
savePassword?: boolean;
password?: string;
saveEmail?: boolean;
email?: string;
birthDate?: string;
countryCode?: string;
userId?: GUID;
}
export enum Gender {
Male = 1,
Female = 2,
}

View File

@@ -1,4 +1,10 @@
// FIXME: all the responses should extend this interface
// import type { ApiResponse } from '@/types/apiResponse';
import { useToast } from '@rkheftan/harmony-ui';
import type { AxiosError } from 'axios';
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
// Define options for the hook
interface UseApiOptions {
// If true, the API call will be executed immediately on mount
@@ -9,9 +15,13 @@ export function useApi<T, P extends any[]>(
apiFunction: (...args: P) => Promise<{ data: T }>,
options: UseApiOptions = {},
) {
const toast = useToast();
const navigate = useNavigate();
const { t } = useTranslation();
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<unknown>(null);
const execute = useCallback(
async (...args: P) => {
setLoading(true);
@@ -21,15 +31,28 @@ export function useApi<T, P extends any[]>(
const response = await apiFunction(...args);
setData(response.data);
} catch (err) {
// TODO: can handle some common errors here, 400 and 500 errors
} catch (err: unknown) {
const axisoError: AxiosError = err as AxiosError;
if (axisoError.response?.status === 401) {
navigate('/login');
}
if (axisoError.response?.status === 500) {
toast({
message: t('messages.serverError'),
severity: 'error',
});
}
setError(err);
} finally {
setLoading(false);
}
},
[apiFunction],
);
[apiFunction, navigate, t, toast],
)
// If the 'immediate' option is true, execute the function on mount
useEffect(() => {

View File

@@ -1,11 +1,12 @@
import axios from 'axios';
// Function to get the token from local storage or state management
const getToken = () => localStorage.getItem('authToken');
export const ACCESS_TOKEN_KEY: 'access_token' = 'access_token' as const;
export const getAccessToken = () => sessionStorage.getItem(ACCESS_TOKEN_KEY);
const apiClient = axios.create({
// Define the base URL for all API requests
baseURL: 'https://accounts.business-harmony.com/api/',
baseURL: import.meta.env.VITE_API_URL,
// Set a timeout for requests (e.g., 10 seconds)
timeout: 10000,
@@ -21,7 +22,7 @@ const apiClient = axios.create({
// This runs BEFORE each request is sent
apiClient.interceptors.request.use(
(config) => {
const token = getToken();
const token = getAccessToken();
if (token) {
// Add the authorization token to the headers
config.headers.Authorization = `Bearer ${token}`;

14
src/lib/identityClient.ts Normal file
View File

@@ -0,0 +1,14 @@
import axios from 'axios';
const identityClient = axios.create({
// Define the base URL for all API requests
baseURL: import.meta.env.VITE_IDENTITY_URL,
// Set a timeout for requests (e.g., 10 seconds)
timeout: 10000,
// Set default headers
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});

View File

@@ -1,4 +1,8 @@
import { Layout } from '@/components/Layout/Layout';
import {
AuthenticationPage,
ForgetPasswordPage,
} from '@/features/authorization';
import {
Calendar,
Devices,
@@ -18,6 +22,7 @@ import { Navigate } from 'react-router-dom';
export interface RouteConfig {
path: string;
element?: ReactNode;
authorize?: boolean;
navConfig?: {
title: string; // Translation key
icon?: Icon;
@@ -27,6 +32,20 @@ export interface RouteConfig {
// can lazy load component if needed (ex. lazy(() => import('@/features/home/routes/HomePage'));)
export const appRoutes: RouteConfig[] = [
{
path: '/',
element: <Navigate to="/setting/profile" replace />,
},
{
path: '/login',
element: <AuthenticationPage />,
authorize: l,
},
{
path: '/forget-password',
element: <ForgetPasswordPage />,
authorize: false,
},
{
path: '/',
element: <Navigate to="/setting/profile" replace />,

View File

@@ -1,6 +1,7 @@
import { Suspense, type ReactNode } from 'react';
import { createBrowserRouter, type RouteObject } from 'react-router-dom';
import { appRoutes, type RouteConfig } from './config';
import { ProtectedRoute } from '@/components/ProtectedRoute';
/**
* A recursive function to map our custom route config to the format
@@ -18,10 +19,9 @@ function mapRoutes(routes: RouteConfig[]): RouteObject[] {
// element = <route.layout>{element}</route.layout>;
// }
// Conditionally wrap the element in the authentication guard
// if (route.authRequired) {
// element = <ProtectedRoute>{element}</ProtectedRoute>;
// }
if (route.authorize) {
element = <ProtectedRoute>{element}</ProtectedRoute>;
}
return {
path: route.path,

View File

@@ -4,7 +4,7 @@ import type { Palette } from './color.type';
export const PALETTE: Palette = {
primary: {
light: {
main: blue[400],
main: blue.A400,
dark: blue[700],
light: blue[100],
contrastText: '#FFFFFF',

View File

@@ -1,5 +0,0 @@
export type FetchPromise<T = ''> = Promise<FetchResponse<T>>;
export interface FetchResponse<T> extends Response {
json(): Promise<T>;
}