update: improve code formatting and error handling in SignIn component

This commit is contained in:
2025-10-02 15:35:07 +07:00
parent 3484683074
commit 50aa323b5f

View File

@@ -7,111 +7,155 @@ import sypiu_ggcp from 'assets/sypiu_ggcp.jpg';
import logo from 'assets/freepik/LOGOPIU.png'; import logo from 'assets/freepik/LOGOPIU.png';
const SignIn = () => { const SignIn = () => {
const [captchaSvg, setCaptchaSvg] = useState(''); const [captchaSvg, setCaptchaSvg] = useState('');
const [captchaText, setCaptchaText] = useState(''); const [captchaText, setCaptchaText] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
const moveToSignUp = () => { const moveToSignUp = () => {
navigate("/signup"); navigate('/signup');
}; };
// ambil captcha // ambil captcha
const fetchCaptcha = async () => { const fetchCaptcha = async () => {
try { try {
const res = await SendRequest({ method: 'get', prefix: 'auth/generate-captcha', token: false }); const res = await SendRequest({
setCaptchaSvg(res.data.svg || ''); method: 'get',
setCaptchaText(res.data.text || ''); prefix: 'auth/generate-captcha',
} catch (err) { token: false,
console.error('Error fetching captcha:', err); });
} setCaptchaSvg(res.data.svg || '');
}; setCaptchaText(res.data.text || '');
} catch (err) {
console.error('Error fetching captcha:', err);
}
};
useEffect(() => { fetchCaptcha(); }, []); useEffect(() => {
const handleOnSubmit = async (values) => {
setLoading(true);
try {
const res = await SendRequest({
method: 'post',
prefix: 'auth/login',
params: {
email: values.email,
password: values.password,
captcha: values.captcha,
captchaText: captchaText,
},
withCredentials: true
});
const user = res?.data?.user || res?.user;
const accessToken = res?.data?.accessToken || res?.tokens?.accessToken;
if (user && accessToken) {
localStorage.setItem('token', accessToken);
localStorage.setItem('user', JSON.stringify(user));
NotifOk({
icon: 'success',
title: 'Login Berhasil',
message: res?.message || 'Selamat datang!',
});
navigate('/dashboard/home');
} else {
NotifAlert({
icon: 'error',
title: 'Login Gagal',
message: res?.message || 'Terjadi kesalahan',
});
fetchCaptcha(); fetchCaptcha();
} }, []);
} catch (err) {
console.error(err);
NotifAlert({ icon: 'error', title: 'Login Gagal', message: err?.message || 'Terjadi kesalahan' });
fetchCaptcha();
} finally { setLoading(false); }
};
return ( const handleOnSubmit = async (values) => {
<Flex align="center" justify="center" style={{ height: '100vh', backgroundImage: `url(${sypiu_ggcp})`, backgroundSize: 'cover', backgroundPosition: 'center' }}> setLoading(true);
<Card style={{ boxShadow: '0px 4px 8px rgba(0,0,0,0.1)' }}> try {
<Flex align="center" justify="center"> const res = await SendRequest({
<Image src={logo} height={150} width={220} preview={false} alt="logo" /> method: 'post',
</Flex> prefix: 'auth/login',
<br /> params: {
<Form layout="vertical" style={{ width: '250px' }} onFinish={handleOnSubmit}> email: values.email,
<Form.Item label="Email" name="email" rules={[{ required: true, type: 'email', message: 'Email tidak boleh kosong' }]}> password: values.password,
<Input placeholder="Email" size="large" /> captcha: values.captcha,
</Form.Item> captchaText: captchaText,
},
withCredentials: true,
});
<Form.Item label="Password" name="password" rules={[{ required: true, message: 'Password tidak boleh kosong' }]}> const user = res?.data?.user || res?.user;
<Input.Password placeholder="Password" size="large" /> const accessToken = res?.data?.accessToken || res?.tokens?.accessToken;
</Form.Item>
<div dangerouslySetInnerHTML={{ __html: captchaSvg }} /> if (user && accessToken) {
localStorage.setItem('token', accessToken);
localStorage.setItem('user', JSON.stringify(user));
<Form.Item label="CAPTCHA" name="captcha" rules={[{ required: true, message: 'Silahkan masukkan CAPTCHA' }]}> NotifOk({
<Input placeholder="Masukkan CAPTCHA" size="large" /> icon: 'success',
</Form.Item> title: 'Login Berhasil',
message: res?.message || 'Selamat datang!',
});
<Form.Item> navigate('/dashboard/home');
<Space direction="vertical" style={{ width: '100%' }}> }
<Button type="primary" htmlType="submit" loading={loading} style={{ width: '100%' }}>Sign In</Button> } catch (err) {
</Space> // hanya handle invalid captcha disini
</Form.Item> if (err?.response?.data?.message?.toLowerCase().includes('captcha')) {
</Form> NotifAlert({
<Button icon: 'warning',
type="primary" title: 'Peringatan',
htmlType="submit" message: 'Invalid captcha',
style={{ width: '100%' }} });
onClick={() => moveToSignUp()} fetchCaptcha();
} else {
NotifAlert({
icon: 'error',
title: 'Login Gagal',
message: err?.message || 'Terjadi kesalahan',
});
fetchCaptcha();
}
} finally {
setLoading(false);
}
};
return (
<Flex
align="center"
justify="center"
style={{
height: '100vh',
backgroundImage: `url(${sypiu_ggcp})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
}}
> >
Registration <Card style={{ boxShadow: '0px 4px 8px rgba(0,0,0,0.1)' }}>
</Button> <Flex align="center" justify="center">
</Card> <Image src={logo} height={150} width={220} preview={false} alt="logo" />
</Flex> </Flex>
); <br />
<Form layout="vertical" style={{ width: '250px' }} onFinish={handleOnSubmit}>
<Form.Item
label="Email"
name="email"
rules={[
{ required: true, type: 'email', message: 'Email tidak boleh kosong' },
]}
>
<Input placeholder="Email" size="large" />
</Form.Item>
<Form.Item
label="Password"
name="password"
rules={[{ required: true, message: 'Password tidak boleh kosong' }]}
>
<Input.Password placeholder="Password" size="large" />
</Form.Item>
<div dangerouslySetInnerHTML={{ __html: captchaSvg }} />
<Form.Item
label="CAPTCHA"
name="captcha"
rules={[{ required: true, message: 'Silahkan masukkan CAPTCHA' }]}
>
<Input placeholder="Masukkan CAPTCHA" size="large" />
</Form.Item>
<Form.Item>
<Space direction="vertical" style={{ width: '100%' }}>
<Button
type="primary"
htmlType="submit"
loading={loading}
style={{ width: '100%' }}
>
Sign In
</Button>
</Space>
</Form.Item>
</Form>
<Button
type="primary"
htmlType="submit"
style={{ width: '100%' }}
onClick={() => moveToSignUp()}
>
Registration
</Button>
</Card>
</Flex>
);
}; };
export default SignIn; export default SignIn;