blob: 4339539ccbffb66360f9867bfb1945bcdbf726b8 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
import React from "react";
import PropTypes from "prop-types";
import Button from "@mui/material/Button";
import Paper from "@mui/material/Paper";
import TextField from "@mui/material/TextField";
class Login extends React.Component {
static propTypes = {
setToken: PropTypes.func.isRequired,
setError: PropTypes.func.isRequired
};
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
loginFailed: false
};
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
}
// NOTE: btoa() limits email, password to ASCII
login(email, password) {
fetch(process.env.JWT_URL, {
method: "POST",
headers: { Authorization: "Basic " + btoa(email + ":" + password) }
})
.then(resp => {
if (resp.status === 401) {
// Unauthorized: Wrong email/password
this.setState({ loginFailed: true });
return;
}
if (resp.status !== 200)
throw new Error(
`Unexpected HTTP response code from JWT server: ${resp.status} ${resp.statusText}`
);
return resp;
})
.then(resp => resp.json())
.then(data => {
this.props.setToken(data.access_token);
});
}
logout() {
localStorage.removeItem("token");
}
render() {
return (
<div id="login-container">
<Paper id="login" variant="outlined" color="green">
<TextField
type="text"
name="email"
placeholder="Username..."
onChange={event => {
this.setState({
email: event.target.value
});
}}
onKeyDown={event => {
if (event.key === "Enter")
this.login(
this.state.email,
this.state.password
);
}}
/>
<TextField
type="password"
placeholder="Password..."
name="password"
onChange={event => {
this.setState({
password: event.target.value
});
}}
onKeyDown={event => {
if (event.key === "Enter")
this.login(
this.state.email,
this.state.password
);
}}
sx={{
marginTop: "1em"
}}
/>
<Button
variant="contained"
className="submit"
onClick={e => {
this.login(this.state.email, this.state.password);
}}
sx={{
marginTop: "1em"
}}
>
Sign in
</Button>
{this.state.loginFailed && (
<p className="error">Wrong username or password</p>
)}
</Paper>
</div>
);
}
}
export default Login;
|