Skip to content

Instantly share code, notes, and snippets.

@chriskearney
Created March 18, 2023 23:22
Show Gist options
  • Save chriskearney/23c247065866f44ac59ec00fc5b57493 to your computer and use it in GitHub Desktop.
Save chriskearney/23c247065866f44ac59ec00fc5b57493 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
import axios from 'axios';
import { useHistory } from 'react-router-dom';
import { Container, Form, FormGroup, Label, Input, Button, Alert } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
function LoginPage({ onLogin }) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(null);
const history = useHistory();
const [csrfToken, setCsrfToken] = useState('');
useEffect(() => {
const fetchCsrfToken = async () => {
try {
const response = await axios.get('http://localhost:8080/pub/api/csrf/token');
setCsrfToken(response.data.token);
} catch (error) {
console.log('Error fetching CSRF token:', error);
}
};
fetchCsrfToken();
}, []);
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post('http://localhost:8080/pub/api/login', {
username: username,
password: password
}, {
withCredentials: true,
headers: {
'X-XSRF-TOKEN': csrfToken
}
});
onLogin(response.data);
history.push('/');
} catch (error) {
setError('Invalid username or password');
}
};
return (
<Container>
<h2>Login</h2>
{error && <Alert color="danger">{error}</Alert>}
<Form onSubmit={handleSubmit}>
<FormGroup>
<Label for="username">Username</Label>
<Input type="text" id="username" value={username} onChange={(e) => setUsername(e.target.value)} />
</FormGroup>
<FormGroup>
<Label for="password">Password</Label>
<Input type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</FormGroup>
<Button color="primary" type="submit">Login</Button>
</Form>
</Container>
);
}
export default LoginPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment