import { useState } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; import { Button, Grid, TextField, Typography } from '@material-ui/core'; 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 'component/common/DividerText/DividerText'; import ConditionallyRender from 'component/common/ConditionallyRender'; import PasswordField from 'component/common/PasswordField/PasswordField'; import { useAuthApi } from 'hooks/api/actions/useAuthApi/useAuthApi'; import { useAuthUser } from 'hooks/api/getters/useAuth/useAuthUser'; import { LOGIN_BUTTON, LOGIN_EMAIL_ID, LOGIN_PASSWORD_ID } from 'testIds'; const HostedAuth = ({ authDetails, redirect }) => { const commonStyles = useCommonStyles(); const styles = useStyles(); const { refetchUser } = useAuthUser(); const history = useHistory(); const params = useQueryParams(); const { passwordAuth } = useAuthApi(); const [username, setUsername] = useState(params.get('email') || ''); const [password, setPassword] = useState(''); const [errors, setErrors] = useState({ usernameError: '', passwordError: '', }); 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; } try { await passwordAuth(authDetails.path, username, password); refetchUser(); history.push(redirect); } 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" data-test={LOGIN_EMAIL_ID} /> setPassword(evt.target.value)} name="password" value={password} error={!!passwordError} helperText={passwordError} data-test={LOGIN_PASSWORD_ID} />
} /> ); }; HostedAuth.propTypes = { authDetails: PropTypes.object.isRequired, redirect: PropTypes.string.isRequired, }; export default HostedAuth;