112 lines
3.1 KiB
JavaScript
112 lines
3.1 KiB
JavaScript
import React from 'react';
|
|
import { Form, Button, Spinner } from 'react-bootstrap';
|
|
import ModalBox from './ModalBox.js';
|
|
import './App.css';
|
|
|
|
class LoginForm extends React.Component {
|
|
constructor(props) {
|
|
super(props);
|
|
|
|
this.state = {
|
|
user: '', password: '',
|
|
loggedIn: props.loggedIn,
|
|
loading: false,
|
|
error: false
|
|
};
|
|
}
|
|
|
|
componentDidUpdate() {
|
|
if (this.state.error) {
|
|
console.log(this.state);
|
|
this.timeout = setTimeout(this.resetComponentState, 3000);
|
|
}
|
|
}
|
|
|
|
componentDidMount() {
|
|
fetch(this.props.targetUrl + '/status', {credentials: 'include'})
|
|
.then(response => response.json())
|
|
.then(data => this.setState({
|
|
loggedIn: data.logged_in
|
|
})
|
|
);
|
|
}
|
|
|
|
componentWillUnmount() {
|
|
clearTimeout(this.timeout)
|
|
}
|
|
|
|
handleUserChange = (event) => {
|
|
this.setState({user: event.target.value});
|
|
};
|
|
|
|
handlePasswordChange = (event) => {
|
|
this.setState({password: event.target.value});
|
|
};
|
|
|
|
handleSubmit = (event) => {
|
|
event.preventDefault();
|
|
|
|
this.setState({loading: true});
|
|
|
|
const formData = event.target.elements;
|
|
var data = {username: formData["username"].value, password: formData["password"].value};
|
|
|
|
fetch(this.props.targetUrl + '/login', {
|
|
method: 'POST',
|
|
body: JSON.stringify(data),
|
|
credentials: 'include'
|
|
})
|
|
.then(response => response.json())
|
|
.then(jsonData => this.setState({loggedIn: jsonData.logged_in, loading: false}))
|
|
.catch((error) => {console.log(error); this.setState({error: true})})
|
|
}
|
|
|
|
dynForm() {
|
|
const form =
|
|
<ModalBox
|
|
title=<h2>Login Form</h2>
|
|
data=
|
|
<Form onSubmit={this.handleSubmit}>
|
|
<Form.Group controlId="username">
|
|
<Form.Control onChange={this.handleUserChange} type="text" name="username" placeholder="Username" />
|
|
</Form.Group>
|
|
|
|
<Form.Group controlId="password">
|
|
<Form.Control onChange={this.handlePasswordChange} type="password" name="password" placeholder="Password" />
|
|
</Form.Group>
|
|
|
|
<Button variant="primary" type="submit">Send</Button>
|
|
</Form>
|
|
/>;
|
|
|
|
const loading =
|
|
<ModalBox
|
|
title="Login"
|
|
data=<Spinner animation="border" variant="primary" />
|
|
/>;
|
|
|
|
if (this.state.loading) {
|
|
return loading;
|
|
} else {
|
|
return form;
|
|
}
|
|
}
|
|
|
|
resetComponentState = () => {
|
|
this.setState({error: false, loading: false, username: '', password: ''})
|
|
}
|
|
|
|
render() {
|
|
if (this.state.loggedIn) {
|
|
return (<ModalBox title="Login" data=<h2>Yet logged in!</h2> />);
|
|
}
|
|
if (this.state.error) {
|
|
return (<div><h2>Error!</h2></div>);
|
|
} else {
|
|
return this.dynForm();
|
|
}
|
|
}
|
|
}
|
|
|
|
export default LoginForm;
|