-
Notifications
You must be signed in to change notification settings - Fork 12
/
Login.jsx
106 lines (98 loc) · 3.23 KB
/
Login.jsx
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
import React from 'react';
import alertifyjs from 'alertifyjs';
import { Paper, TextField, Button } from '@material-ui/core';
import { values, map, get } from 'lodash';
import APIService from '../../services/APIService';
import { refreshCurrentUserCache } from '../../common/utils';
class Login extends React.Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: '',
serverError: null,
}
}
handleSubmit = event => {
event.preventDefault()
const { username, password } = this.state;
if(username && password)
this.handleLogin(username, password)
return false
}
onFieldChange = event => {
this.setState({[event.target.id]: event.target.value})
}
handleLogin(username, password) {
this.setState({serverError: null}, () => {
APIService.users().login().post({username: username, password: password}).then(response => {
if(get(response, 'status') === 200 && get(response, 'data.token')) {
this.afterLoginSuccess(response.data.token)
} else if(get(response, 'non_field_errors')) {
this.setState({serverError: values(response)})
} else {
this.setState({serverError: ['Something bad happened!']})
}
})
})
}
afterLoginSuccess(token) {
localStorage.setItem('token', token)
this.cacheUserData()
}
cacheUserData() {
refreshCurrentUserCache(response => {
alertifyjs.success(`Successfully signed in as ${this.state.username}.`)
window.location.hash = '#' + response.data.url
})
}
render() {
const { serverError } = this.state;
return (
<div className='col-md-12' style={{marginTop: '25px'}}>
<div className='col-md-4' />
<div className='col-md-4'>
<Paper style={{padding: '10px'}} className='login-paper'>
<h1 style={{textAlign: 'center'}}>Sign In</h1>
{
serverError &&
<div className='col-md-12 alert-danger'>
<ul> {map(serverError, error => (<li key={error}>{error}</li>))} </ul>
</div>
}
<div className='col-md-12 no-side-padding'>
<form>
<div>
<TextField
required
id="username"
label="Username"
variant="outlined"
onChange={this.onFieldChange}
fullWidth
/>
</div>
<div style={{marginTop: '10px'}}>
<TextField
required
id="password"
label="Password"
variant="outlined"
type="password"
onChange={this.onFieldChange}
fullWidth
/>
</div>
<div style={{marginTop: '20px', textAlign: 'center', marginBottom: '20px'}}>
<Button onClick={this.handleSubmit} type='submit' color='primary' variant='contained'>Sign In</Button>
</div>
</form>
</div>
</Paper>
</div>
<div className='col-md-4' />
</div>
)
}
}
export default Login;