import React, { useState } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; import { Button, Grid, TextField, Typography, InputAdornment, IconButton, } from '@material-ui/core'; import { Visibility, VisibilityOff } from '@material-ui/icons'; import { useHistory } from 'react-router'; import { useCommonStyles } from '../../../common.styles'; import { useStyles } from './HostedAuth.styles'; import useQueryParams from '../../../hooks/useQueryParams'; import AuthOptions from '../common/AuthOptions/AuthOptions'; import DividerText from '../../common/DividerText/DividerText'; import ConditionallyRender from '../../common/ConditionallyRender'; import useUser from '../../../hooks/api/getters/useUser/useUser'; const HostedAuth = ({ authDetails, passwordLogin }) => { const commonStyles = useCommonStyles(); const styles = useStyles(); const { refetch } = useUser(); const history = useHistory(); const params = useQueryParams(); const [username, setUsername] = useState(params.get('email') || ''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [errors, setErrors] = useState({ usernameError: '', passwordError: '', }); const handleClickShowPassword = () => { setShowPassword(!showPassword); }; const handleMouseDownPassword = e => { e.preventDefault(); }; const handleSubmit = async evt => { evt.preventDefault(); if (!username) { setErrors(prev => ({ ...prev, usernameError: 'This is a required field', })); } if (!password) { setErrors(prev => ({ ...prev, passwordError: 'This is a required field', })); } if (!password || !username) { return; } const user = { username, password }; const path = evt.target.action; try { await passwordLogin(path, user); refetch(); history.push(`/`); } catch (error) { if (error.statusCode === 404 || error.statusCode === 400) { setErrors(prev => ({ ...prev, apiError: 'Invalid login details', })); setPassword(''); setUsername(''); } else { setErrors({ apiError: 'Unknown error while trying to authenticate.', }); } } }; const { usernameError, passwordError, apiError } = errors; const { options = [] } = authDetails; return ( <> 0} show={ <> } /> {apiError}
setUsername(evt.target.value)} value={username} error={!!usernameError} helperText={usernameError} variant="outlined" size="small" /> setPassword(evt.target.value)} name="password" type={showPassword ? 'text' : 'password'} value={password} error={!!passwordError} helperText={passwordError} variant="outlined" size="small" InputProps={{ style:{ paddingRight: 0 }, endAdornment: ( {showPassword ? ( ) : ( )} ), }} />
} /> ); }; HostedAuth.propTypes = { authDetails: PropTypes.object.isRequired, passwordLogin: PropTypes.func.isRequired, history: PropTypes.object.isRequired, }; export default HostedAuth;