16212: Sets api token on login success, re-focus on login error.
[arvados-workbench2.git] / src / views-components / login-form / login-form.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { useState, useEffect, useRef } from 'react';
7 import { withStyles, WithStyles, StyleRulesCallback } from '@material-ui/core/styles';
8 import CircularProgress from '@material-ui/core/CircularProgress';
9 import { Button, Card, CardContent, TextField, CardActions } from '@material-ui/core';
10 import { green } from '@material-ui/core/colors';
11 import { AxiosPromise } from 'axios';
12 import { DispatchProp } from 'react-redux';
13 import { saveApiToken } from '~/store/auth/auth-action';
14 import { navigateToRootProject } from '~/store/navigation/navigation-action';
15
16 type CssRules = 'root' | 'loginBtn' | 'card' | 'wrapper' | 'progress';
17
18 const styles: StyleRulesCallback<CssRules> = theme => ({
19     root: {
20         display: 'flex',
21         flexWrap: 'wrap',
22         width: '100%',
23         margin: `${theme.spacing.unit} auto`
24     },
25     loginBtn: {
26         marginTop: theme.spacing.unit,
27         flexGrow: 1
28     },
29     card: {
30         marginTop: theme.spacing.unit,
31         width: '100%'
32     },
33     wrapper: {
34         margin: theme.spacing.unit,
35         position: 'relative',
36     },
37     progress: {
38         color: green[500],
39         position: 'absolute',
40         top: '50%',
41         left: '50%',
42         marginTop: -12,
43         marginLeft: -12,
44     },
45 });
46
47 type LoginFormProps = DispatchProp<any> & WithStyles<CssRules> & {
48     handleSubmit: (username: string, password: string) => AxiosPromise;
49 };
50
51 export const LoginForm = withStyles(styles)(
52     ({ handleSubmit, dispatch, classes }: LoginFormProps) => {
53         const userInput = useRef<HTMLInputElement>(null);
54         const [username, setUsername] = useState('');
55         const [password, setPassword] = useState('');
56         const [isButtonDisabled, setIsButtonDisabled] = useState(true);
57         const [isSubmitting, setSubmitting] = useState(false);
58         const [helperText, setHelperText] = useState('');
59         const [error, setError] = useState(false);
60
61         useEffect(() => {
62             setError(false);
63             setHelperText('');
64             if (username.trim() && password.trim()) {
65                 setIsButtonDisabled(false);
66             } else {
67                 setIsButtonDisabled(true);
68             }
69         }, [username, password]);
70
71         // This only runs once after render.
72         useEffect(() => {
73             setFocus();
74         }, []);
75
76         const setFocus = () => {
77             userInput.current!.focus();
78         };
79
80         const handleLogin = () => {
81             setError(false);
82             setHelperText('');
83             setSubmitting(true);
84             handleSubmit(username, password)
85             .then((response) => {
86                 setSubmitting(false);
87                 const apiToken = response.data.token;
88                 if (apiToken) {
89                     dispatch<any>(saveApiToken(apiToken)).finally(
90                         () => dispatch(navigateToRootProject));
91                 } else {
92                     setError(true);
93                     setHelperText(response.data.message || 'Please try again');
94                     setFocus();
95                 }
96             })
97             .catch((err) => {
98                 setError(true);
99                 setSubmitting(false);
100                 setHelperText(`${err.response && err.response.data && err.response.data.errors[0] || 'Error logging in: '+err}`);
101                 setFocus();
102             });
103         };
104
105         const handleKeyPress = (e: any) => {
106             if (e.keyCode === 13 || e.which === 13) {
107                 if (!isButtonDisabled) {
108                     handleLogin();
109                 }
110             }
111         };
112
113         return (
114             <React.Fragment>
115             <form className={classes.root} noValidate autoComplete="off">
116                 <Card className={classes.card}>
117                     <div className={classes.wrapper}>
118                     <CardContent>
119                         <TextField
120                             inputRef={userInput}
121                             disabled={isSubmitting}
122                             error={error} fullWidth id="username" type="email"
123                             label="Username" margin="normal"
124                             onChange={(e) => setUsername(e.target.value)}
125                             onKeyPress={(e) => handleKeyPress(e)}
126                         />
127                         <TextField
128                             disabled={isSubmitting}
129                             error={error} fullWidth id="password" type="password"
130                             label="Password" margin="normal"
131                             helperText={helperText}
132                             onChange={(e) => setPassword(e.target.value)}
133                             onKeyPress={(e) => handleKeyPress(e)}
134                         />
135                     </CardContent>
136                     <CardActions>
137                         <Button variant="contained" size="large" color="primary"
138                             className={classes.loginBtn} onClick={() => handleLogin()}
139                             disabled={isSubmitting || isButtonDisabled}>
140                             Log in
141                         </Button>
142                     </CardActions>
143                     { isSubmitting && <CircularProgress color='secondary' className={classes.progress} />}
144                     </div>
145                 </Card>
146             </form>
147             </React.Fragment>
148         );
149     });