Fix up authentication flows to use formik correctly

This commit is contained in:
Dane Everitt 2020-03-28 15:42:53 -07:00
parent cb945b1f13
commit 7244cdbf5d
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
5 changed files with 233 additions and 222 deletions

View file

@ -4,25 +4,24 @@ import requestPasswordResetEmail from '@/api/auth/requestPasswordResetEmail';
import { httpErrorToHuman } from '@/api/http';
import LoginFormContainer from '@/components/auth/LoginFormContainer';
import { Actions, useStoreActions } from 'easy-peasy';
import FlashMessageRender from '@/components/FlashMessageRender';
import { ApplicationStore } from '@/state';
import Field from '@/components/elements/Field';
import { Formik, FormikHelpers } from 'formik';
import { object, string } from 'yup';
interface Values {
email: string;
}
export default () => {
const [ isSubmitting, setSubmitting ] = React.useState(false);
const [ email, setEmail ] = React.useState('');
const { clearFlashes, addFlash } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const handleFieldUpdate = (e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value);
const handleSubmission = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const handleSubmission = ({ email }: Values, { setSubmitting, resetForm }: FormikHelpers<Values>) => {
setSubmitting(true);
clearFlashes();
requestPasswordResetEmail(email)
.then(response => {
setEmail('');
resetForm();
addFlash({ type: 'success', title: 'Success', message: response });
})
.catch(error => {
@ -33,29 +32,31 @@ export default () => {
};
return (
<div>
<h2 className={'text-center text-neutral-100 font-medium py-4'}>
Request Password Reset
</h2>
<FlashMessageRender/>
<LoginFormContainer onSubmit={handleSubmission}>
<label htmlFor={'email'}>Email</label>
<input
id={'email'}
<Formik
onSubmit={handleSubmission}
initialValues={{ email: '' }}
validationSchema={object().shape({
email: string().email('A valid email address must be provided to continue.')
.required('A valid email address must be provided to continue.'),
})}
>
{({ isSubmitting }) => (
<LoginFormContainer
title={'Request Password Reset'}
className={'w-full flex'}
>
<Field
light={true}
label={'Email'}
description={'Enter your account email address to receive instructions on resetting your password.'}
name={'email'}
type={'email'}
required={true}
className={'input'}
value={email}
onChange={handleFieldUpdate}
autoFocus={true}
/>
<p className={'input-help'}>
Enter your account email address to receive instructions on resetting your password.
</p>
<div className={'mt-6'}>
<button
type={'submit'}
className={'btn btn-primary btn-jumbo flex justify-center'}
disabled={isSubmitting || email.length < 5}
disabled={isSubmitting}
>
{isSubmitting ?
<div className={'spinner-circle spinner-sm spinner-white'}></div>
@ -66,6 +67,7 @@ export default () => {
</div>
<div className={'mt-6 text-center'}>
<Link
type={'button'}
to={'/auth/login'}
className={'text-xs text-neutral-500 tracking-wide uppercase no-underline hover:text-neutral-700'}
>
@ -73,6 +75,7 @@ export default () => {
</Link>
</div>
</LoginFormContainer>
</div>
)}
</Formik>
);
};

View file

@ -2,7 +2,6 @@ import React, { useRef } from 'react';
import { Link, RouteComponentProps } from 'react-router-dom';
import login, { LoginData } from '@/api/auth/login';
import LoginFormContainer from '@/components/auth/LoginFormContainer';
import FlashMessageRender from '@/components/FlashMessageRender';
import { ActionCreator, Actions, useStoreActions, useStoreState } from 'easy-peasy';
import { ApplicationStore } from '@/state';
import { FormikProps, withFormik } from 'formik';
@ -12,33 +11,12 @@ import { httpErrorToHuman } from '@/api/http';
import { FlashMessage } from '@/state/flashes';
import ReCAPTCHA from 'react-google-recaptcha';
import Spinner from '@/components/elements/Spinner';
import styled from 'styled-components';
import { breakpoint } from 'styled-components-breakpoint';
type OwnProps = RouteComponentProps & {
clearFlashes: ActionCreator<void>;
addFlash: ActionCreator<FlashMessage>;
}
const Container = styled.div`
${breakpoint('sm')`
${tw`w-4/5 mx-auto`}
`};
${breakpoint('md')`
${tw`p-10`}
`};
${breakpoint('lg')`
${tw`w-3/5`}
`};
${breakpoint('xl')`
${tw`w-full`}
max-width: 660px;
`};
`;
const LoginContainer = ({ isSubmitting, setFieldValue, values, submitForm, handleSubmit }: OwnProps & FormikProps<LoginData>) => {
const ref = useRef<ReCAPTCHA | null>(null);
const { enabled: recaptchaEnabled, siteKey } = useStoreState<ApplicationStore, any>(state => state.settings.data!.recaptcha);
@ -56,12 +34,8 @@ const LoginContainer = ({ isSubmitting, setFieldValue, values, submitForm, handl
return (
<React.Fragment>
{ref.current && ref.current.render()}
<h2 className={'text-center text-neutral-100 font-medium py-4'}>
Login to Continue
</h2>
<Container>
<FlashMessageRender className={'mb-2 px-1'}/>
<LoginFormContainer
title={'Login to Continue'}
className={'w-full flex'}
onSubmit={submit}
>
@ -115,7 +89,6 @@ const LoginContainer = ({ isSubmitting, setFieldValue, values, submitForm, handl
</Link>
</div>
</LoginFormContainer>
</Container>
</React.Fragment>
);
};

View file

@ -1,11 +1,40 @@
import React, { forwardRef } from 'react';
import { Form } from 'formik';
import styled from 'styled-components';
import { breakpoint } from 'styled-components-breakpoint';
import FlashMessageRender from '@/components/FlashMessageRender';
type Props = React.DetailedHTMLProps<React.FormHTMLAttributes<HTMLFormElement>, HTMLFormElement>;
type Props = React.DetailedHTMLProps<React.FormHTMLAttributes<HTMLFormElement>, HTMLFormElement> & {
title?: string;
}
export default forwardRef<any, Props>(({ ...props }, ref) => (
<Form {...props}>
<div className={'md:flex w-full bg-white shadow-lg rounded-lg p-6 mx-1'}>
const Container = styled.div`
${breakpoint('sm')`
${tw`w-4/5 mx-auto`}
`};
${breakpoint('md')`
${tw`p-10`}
`};
${breakpoint('lg')`
${tw`w-3/5`}
`};
${breakpoint('xl')`
${tw`w-full`}
max-width: 700px;
`};
`;
export default forwardRef<HTMLFormElement, Props>(({ title, ...props }, ref) => (
<Container>
{title && <h2 className={'text-center text-neutral-100 font-medium py-4'}>
{title}
</h2>}
<FlashMessageRender className={'mb-2 px-1'}/>
<Form {...props} ref={ref}>
<div className={'md:flex w-full bg-white shadow-lg rounded-lg p-6 md:pl-0 mx-1'}>
<div className={'flex-none select-none mb-6 md:mb-0 self-center'}>
<img src={'/assets/pterodactyl.svg'} className={'block w-48 md:w-64 mx-auto'}/>
</div>
@ -14,4 +43,5 @@ export default forwardRef<any, Props>(({ ...props }, ref) => (
</div>
</div>
</Form>
</Container>
));

View file

@ -5,91 +5,94 @@ import { Link } from 'react-router-dom';
import performPasswordReset from '@/api/auth/performPasswordReset';
import { httpErrorToHuman } from '@/api/http';
import LoginFormContainer from '@/components/auth/LoginFormContainer';
import FlashMessageRender from '@/components/FlashMessageRender';
import { Actions, useStoreActions } from 'easy-peasy';
import { ApplicationStore } from '@/state';
import Spinner from '@/components/elements/Spinner';
import { Formik, FormikHelpers } from 'formik';
import { object, ref, string } from 'yup';
import Field from '@/components/elements/Field';
type Props = Readonly<RouteComponentProps<{ token: string }> & {}>;
export default (props: Props) => {
const [ isLoading, setIsLoading ] = useState(false);
interface Values {
password: string;
passwordConfirmation: string;
}
export default ({ match, history, location }: Props) => {
const [ email, setEmail ] = useState('');
const [ password, setPassword ] = useState('');
const [ passwordConfirm, setPasswordConfirm ] = useState('');
const { clearFlashes, addFlash } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const parsed = parse(props.location.search);
const parsed = parse(location.search);
if (email.length === 0 && parsed.email) {
setEmail(parsed.email as string);
}
const canSubmit = () => password && email && password.length >= 8 && password === passwordConfirm;
const submit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!password || !email || !passwordConfirm) {
return;
}
setIsLoading(true);
const submit = ({ password, passwordConfirmation }: Values, { setSubmitting }: FormikHelpers<Values>) => {
clearFlashes();
performPasswordReset(email, {
token: props.match.params.token, password, passwordConfirmation: passwordConfirm,
})
performPasswordReset(email, { token: match.params.token, password, passwordConfirmation })
.then(() => {
addFlash({ type: 'success', message: 'Your password has been reset, please login to continue.' });
props.history.push('/auth/login');
// @ts-ignore
window.location = '/';
return;
})
.catch(error => {
console.error(error);
setSubmitting(false);
addFlash({ type: 'error', title: 'Error', message: httpErrorToHuman(error) });
})
.then(() => setIsLoading(false));
});
};
return (
<Formik
onSubmit={submit}
initialValues={{
password: '',
passwordConfirmation: '',
}}
validationSchema={object().shape({
password: string().required('A new password is required.')
.min(8, 'Your new password should be at least 8 characters in length.'),
passwordConfirmation: string()
.required('Your new password does not match.')
.oneOf([ref('password'), null], 'Your new password does not match.'),
})}
>
{({ isSubmitting }) => (
<LoginFormContainer
title={'Reset Password'}
className={'w-full flex'}
>
<div>
<h2 className={'text-center text-neutral-100 font-medium py-4'}>
Reset Password
</h2>
<FlashMessageRender/>
<LoginFormContainer onSubmit={submit}>
<label>Email</label>
<input className={'input'} value={email} disabled={true}/>
<div className={'mt-6'}>
<label htmlFor={'new_password'}>New Password</label>
<input
id={'new_password'}
className={'input'}
type={'password'}
required={true}
onChange={e => setPassword(e.target.value)}
/>
<p className={'input-help'}>
Passwords must be at least 8 characters in length.
</p>
</div>
<div className={'mt-6'}>
<label htmlFor={'new_password_confirm'}>Confirm New Password</label>
<input
id={'new_password_confirm'}
className={'input'}
<Field
light={true}
label={'New Password'}
name={'password'}
type={'password'}
description={'Passwords must be at least 8 characters in length.'}
/>
</div>
<div className={'mt-6'}>
<Field
light={true}
label={'Confirm New Password'}
name={'passwordConfirmation'}
type={'password'}
required={true}
onChange={e => setPasswordConfirm(e.target.value)}
/>
</div>
<div className={'mt-6'}>
<button
type={'submit'}
className={'btn btn-primary btn-jumbo'}
disabled={isLoading || !canSubmit()}
disabled={isSubmitting}
>
{isLoading ?
{isSubmitting ?
<Spinner size={'tiny'} className={'mx-auto'}/>
:
'Reset Password'
@ -105,6 +108,7 @@ export default (props: Props) => {
</Link>
</div>
</LoginFormContainer>
</div>
)}
</Formik>
);
};

View file

@ -4,6 +4,7 @@ import classNames from 'classnames';
interface OwnProps {
name: string;
light?: boolean;
label?: string;
description?: string;
validate?: (value: any) => undefined | string | Promise<any>;
@ -11,19 +12,19 @@ interface OwnProps {
type Props = OwnProps & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'name'>;
const Field = ({ id, name, label, description, validate, className, ...props }: Props) => (
const Field = ({ id, name, light = false, label, description, validate, className, ...props }: Props) => (
<FormikField name={name} validate={validate}>
{
({ field, form: { errors, touched } }: FieldProps) => (
<React.Fragment>
{label &&
<label htmlFor={id} className={'input-dark-label'}>{label}</label>
<label htmlFor={id} className={light ? undefined : 'input-dark-label'}>{label}</label>
}
<input
id={id}
{...field}
{...props}
className={classNames((className || 'input-dark'), {
className={classNames((className || (light ? 'input' : 'input-dark')), {
error: touched[field.name] && errors[field.name],
})}
/>