You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

157 lines
3.3 KiB
JavaScript

import {Button, Form, Container, Col, Row} from 'react-bootstrap';
import { useState, useEffect, useContext } from 'react';
import {Navigate} from "react-router-dom";
import UserContext from "../UserContext.js";
import Swal from 'sweetalert2';
export default function Login(){
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isActive, setIsActive] = useState(false);
const { user, setUser} = useContext(UserContext);
useEffect(() =>{
if(email !== '' && password !== ''){
setIsActive(false);
}else{
setIsActive(true);
}
}, [email, password]);
function loginUser(event) {
event.preventDefault();
fetch(`${process.env.REACT_APP_API_BASE_URL}/users/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password
})
})
.then(result => result.json())
.then(data => {
if(data.accessToken){
localStorage.setItem('token', data.accessToken);
retrieveUserDetails(data.accessToken);
Swal.fire({
title: "Login Successful",
icon: "success",
text: "Welcome to Arcade Alley!"
})
setEmail('');
setPassword('');
}else{
Swal.fire({
title: "Login Unsuccessful",
icon: "error",
text: "Please try again!"
})
}
})
setEmail('');
setPassword('');
}
const retrieveUserDetails = (token) => {
fetch(`${process.env.REACT_APP_API_BASE_URL}/users/details`, {
method: "GET",
headers: {
Authorization : `Bearer ${token}`
}
})
.then(result => result.json())
.then(data => {
setUser({
id: data._id,
isAdmin: data.isAdmin,
token: localStorage.token
})
})
}
return(
(user.id !== null)
?
<Navigate to = "/products" />
:
(user.isAdmin !== null)
?
<Navigate to = "/" />
:
<Container>
<Row>
<h1 className = "text-center my-4">LOGIN</h1>
<Col className = "col-3 mx-auto mb-3 forms">
<Form onSubmit= {event => loginUser(event)} className = "p-2">
<Form.Group className="mb-3" controlId="loginFormBasicEmail">
<Form.Label>Email address:</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
required
value = {email}
onChange = {event => {
setEmail(event.target.value);
}}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="loginFormPassword">
<Form.Label>Password:</Form.Label>
<Form.Control
type="password"
placeholder="Password"
required
value ={password}
onChange = {event => {
setPassword(event.target.value);
}}
/>
</Form.Group>
<div className = "col-10 mx-auto d-flex justify-content-around">
<Button disabled = {isActive} variant="success" type="submit" className = "nes-btn btn-submit">
Login
</Button>
</div>
</Form>
</Col>
</Row>
</Container>
)
}