Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored Login.jsx: Enhanced error handling, simplified logic, and … #656

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions client/src/components/Anonymous.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ import useCheckTimePassed from 'src/hooks/useCheckTimePassed';

const centerItems = `flex items-center justify-center`;

const Anonymous = ({
onChatClosed,
const Anonymous = ({
onChatClosed,

}) => {
const { app, endSearch } = useApp();
const { currentChatId, onlineStatus } = app;
Expand Down Expand Up @@ -290,8 +290,8 @@ const Anonymous = ({
'flex-auto',
])}
>
<Chat
<Chat

/>
</div>
</div>
Expand Down
16 changes: 9 additions & 7 deletions client/src/components/Dialog.jsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';

import PropTypes from 'prop-types';

import { useDialog } from 'src/context/DialogContext';
import { useApp } from 'src/context/AppContext';

const Dialog = ({ ...rest }) => {
const { dialog, setDialog } = useDialog();
const { isOpen, text, handler, noBtnText, yesBtnText } = dialog;

const { app } = useApp();

const { settings } = app;

const resetDialog = () => {
Expand All @@ -35,21 +31,27 @@ const Dialog = ({ ...rest }) => {
};
window.addEventListener('keydown', handleKeydown);
return () => window.removeEventListener('keydown', handleKeydown);
}, [resetDialog]);
}, []);

if (!isOpen) {
return null;
}

return ReactDOM.createPortal(
<div className={`${settings.theme && 'dark'}`}>
<div id="overlay" className="z-50 fixed inset-0 bg-black opacity-60" onClick={resetDialog} />
<div
id="overlay"
className="z-50 fixed inset-0 bg-black opacity-60"
onClick={resetDialog}
/>
<dialog
open={isOpen}
{...rest}
className="z-50 rounded-lg fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 m-0 bg-light dark:bg-secondary w-[90%] md:w-auto md:max-w-md px-6 py-6"
>
<p className="text-primary dark:text-white text-[1rem]">{text || 'Are you sure?'}</p>
<p className="text-primary dark:text-white text-[1rem]">
{text || 'Are you sure?'}
</p>

<div className="flex justify-end gap-2 mt-6">
<button
Expand Down
293 changes: 151 additions & 142 deletions client/src/pages/Login.jsx
Original file line number Diff line number Diff line change
@@ -1,151 +1,160 @@
/* eslint-disable require-atomic-updates */

import React, { useRef, useState } from 'react'
import React, { useRef, useState } from 'react';
import { decrypt, encrypt, generateCode } from 'src/lib/utils';

import { PropTypes } from 'prop-types';
import PropTypes from 'prop-types';
import { api } from 'src/lib/axios';
import { useAuth } from 'src/context/AuthContext';

const Login = () => {
const { dispatchAuth } = useAuth()

const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
const [toInputCode, setToInputCode] = useState(false)
const [email, setEmail] = useState(null)

const emailRef = useRef();
const codeRef = useRef();

const handleEmailInput = async () => {
const email = emailRef.current.value

if (!email || email.length === '') {
setError('Email not provided')
return
}

try {
setIsLoading(true)
const code = generateCode()
const response = await api.post('/code', {
email,
code
})

localStorage.setItem('code', encrypt(code))

if (response.status === 200) {
setToInputCode(true)
setEmail(email)
}
} catch (error) {
console.error(error)
} finally {
setIsLoading(false)
emailRef.current.value = ''
}
}

const handleCodeInput = async () => {
const inputedCode = codeRef.current.value
if (!inputedCode || inputedCode.length === '') {
setError('No Code provided')
return
}

try {
setIsLoading(true)
const code = decrypt(localStorage.getItem('code'))
if (inputedCode === code) {
const response = await api.post('/login', {
email,
});

const data = await response.data;
if (response.status === 200) {
const id = data.id;

dispatchAuth({
type: 'LOGIN',
payload: {
loginId: id,
loginType: 'email',
email,
},
});
} else if (response.status === 500) {
throw new Error(data.message);
}
} else {
setError('Wrong Code, Try Again')
}

} catch (error) {
console.error(error)
} finally {
setIsLoading(false)
codeRef.current.value = ''
}
}

return (
<section className='flex flex-col gap-3'>
{toInputCode ?
<InputMethod
refProp={codeRef}
isLoading={isLoading}
handleSubmit={handleCodeInput}
inputValue={{ type: 'text', name: 'code', placeholder: "Enter Code Recieved" }}

/>
:
<InputMethod
refProp={emailRef}
isLoading={isLoading}
handleSubmit={handleEmailInput}
inputValue={{ type: "email", name: "email", placeholder: "Enter Your Email" }}
/>}
{error && <p className='text-red text-center'>{error}</p>}
</section>
)
}

export default Login
const { dispatchAuth } = useAuth();

const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [toInputCode, setToInputCode] = useState(false);
const [email, setEmail] = useState('');

const emailRef = useRef();
const codeRef = useRef();

const handleEmailInput = async () => {
const email = emailRef.current.value.trim();

if (!email) {
setError('Email not provided');
return;
}

try {
setIsLoading(true);
const code = generateCode();
const response = await api.post('/code', {
email,
code,
});

localStorage.setItem('code', encrypt(code));

if (response.status === 200) {
setToInputCode(true);
setEmail(email);
}
} catch (error) {
setError('Failed to send code. Please try again.');
console.error(error);
} finally {
setIsLoading(false);
emailRef.current.value = '';
}
};

const handleCodeInput = async () => {
const inputedCode = codeRef.current.value.trim();

if (!inputedCode) {
setError('No code provided');
return;
}

try {
setIsLoading(true);
const storedCode = decrypt(localStorage.getItem('code'));

if (inputedCode === storedCode) {
const response = await api.post('/login', { email });

if (response.status === 200) {
const { id } = response.data;

dispatchAuth({
type: 'LOGIN',
payload: {
loginId: id,
loginType: 'email',
email,
},
});
} else {
setError(response.data.message || 'Login failed. Please try again.');
}
} else {
setError('Wrong code. Please try again.');
}
} catch (error) {
setError('Login failed. Please try again.');
console.error(error);
} finally {
setIsLoading(false);
codeRef.current.value = '';
}
};

return (
<section className="flex flex-col gap-3">
{toInputCode ? (
<InputMethod
refProp={codeRef}
isLoading={isLoading}
handleSubmit={handleCodeInput}
inputValue={{
type: 'text',
name: 'code',
placeholder: 'Enter the code received',
}}
/>
) : (
<InputMethod
refProp={emailRef}
isLoading={isLoading}
handleSubmit={handleEmailInput}
inputValue={{
type: 'email',
name: 'email',
placeholder: 'Enter your email',
}}
/>
)}
{error && <p className="text-red-500 text-center">{error}</p>}
</section>
);
};

export default Login;

const InputMethod = ({ refProp, isLoading, handleSubmit, inputValue }) => {
return <>
{inputValue.name === 'code' && <p className='text-center'>Check Your Email For the Code</p>}
<label htmlFor="email" className="w-full flex items-center justify-center">
<input
type={inputValue.type}
className="w-full max-w-[600px] min-w-[300px] p-3 rounded-md text-black border-highlight border"
name={inputValue.name}
ref={refProp}
placeholder={inputValue.placeholder}
/>
</label>
<button
disabled={isLoading}
onClick={handleSubmit}
className="bg-highlight w-[80%] max-w-[400px] min-w-[300px] py-2 rounded-md"
>
{isLoading ? 'Loading' : 'Submit'}
</button>
</>
}
return (
<>
{inputValue.name === 'code' && <p className="text-center">Check your email for the code</p>}
<label htmlFor={inputValue.name} className="w-full flex items-center justify-center">
<input
type={inputValue.type}
className="w-full max-w-[600px] min-w-[300px] p-3 rounded-md text-black border-highlight border"
name={inputValue.name}
ref={refProp}
placeholder={inputValue.placeholder}
/>
</label>
<button
disabled={isLoading}
onClick={handleSubmit}
className={`bg-highlight w-[80%] max-w-[400px] min-w-[300px] py-2 rounded-md ${
isLoading ? 'opacity-50 cursor-not-allowed' : ''
}`}
>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</>
);
};

InputMethod.propTypes = {
refProp: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({ current: PropTypes.instanceOf(Element) })
]),
isLoading: PropTypes.bool,
handleSubmit: PropTypes.func,
inputValue: PropTypes.shape({
type: PropTypes.string,
name: PropTypes.string,
placeholder: PropTypes.string,
})
}
refProp: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({ current: PropTypes.instanceOf(Element) }),
]),
isLoading: PropTypes.bool,
handleSubmit: PropTypes.func,
inputValue: PropTypes.shape({
type: PropTypes.string,
name: PropTypes.string,
placeholder: PropTypes.string,
}),
};
Loading