diff --git a/projects/pi-nexus-iam/frontend/components/Login.tsx b/projects/pi-nexus-iam/frontend/components/Login.tsx new file mode 100644 index 000000000..bed11c3fe --- /dev/null +++ b/projects/pi-nexus-iam/frontend/components/Login.tsx @@ -0,0 +1,59 @@ +import React, { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { yupResolver } from '@hookform/resolvers/yup'; +import * as yup from 'yup'; +import axios from 'axios'; +import { useHistory } from 'react-router-dom'; + +interface LoginForm { + email: string; + password: string; +} + +const schema = yup.object().shape({ + email: yup.string().email('Invalid email').required('Email is required'), + password: yup.string().min(8, 'Password must be at least 8 characters').required('Password is required'), +}); + +const Login: React.FC = () => { + const { register, handleSubmit, errors } = useForm({ + resolver: yupResolver(schema), + }); + const [loading, setLoading] = useState(false); + const history = useHistory(); + + const onSubmit = async (data: LoginForm) => { + try { + setLoading(true); + const response = await axios.post('/api/auth/login', data); + const { accessToken, refreshToken } = response.data; + localStorage.setItem('accessToken', accessToken); + localStorage.setItem('refreshToken', refreshToken); + history.push('/dashboard'); + } catch (error) { + console.error(error); + setLoading(false); + } + }; + + return ( +
+

Login

+
+ + + {errors.email &&
{errors.email.message}
} +
+ + + {errors.password &&
{errors.password.message}
} +
+ +
+
+ ); +}; + +export default Login;