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

View file

@ -2,7 +2,6 @@ import React, { useRef } from 'react';
import { Link, RouteComponentProps } from 'react-router-dom'; import { Link, RouteComponentProps } from 'react-router-dom';
import login, { LoginData } from '@/api/auth/login'; import login, { LoginData } from '@/api/auth/login';
import LoginFormContainer from '@/components/auth/LoginFormContainer'; import LoginFormContainer from '@/components/auth/LoginFormContainer';
import FlashMessageRender from '@/components/FlashMessageRender';
import { ActionCreator, Actions, useStoreActions, useStoreState } from 'easy-peasy'; import { ActionCreator, Actions, useStoreActions, useStoreState } from 'easy-peasy';
import { ApplicationStore } from '@/state'; import { ApplicationStore } from '@/state';
import { FormikProps, withFormik } from 'formik'; import { FormikProps, withFormik } from 'formik';
@ -12,33 +11,12 @@ import { httpErrorToHuman } from '@/api/http';
import { FlashMessage } from '@/state/flashes'; import { FlashMessage } from '@/state/flashes';
import ReCAPTCHA from 'react-google-recaptcha'; import ReCAPTCHA from 'react-google-recaptcha';
import Spinner from '@/components/elements/Spinner'; import Spinner from '@/components/elements/Spinner';
import styled from 'styled-components';
import { breakpoint } from 'styled-components-breakpoint';
type OwnProps = RouteComponentProps & { type OwnProps = RouteComponentProps & {
clearFlashes: ActionCreator<void>; clearFlashes: ActionCreator<void>;
addFlash: ActionCreator<FlashMessage>; 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 LoginContainer = ({ isSubmitting, setFieldValue, values, submitForm, handleSubmit }: OwnProps & FormikProps<LoginData>) => {
const ref = useRef<ReCAPTCHA | null>(null); const ref = useRef<ReCAPTCHA | null>(null);
const { enabled: recaptchaEnabled, siteKey } = useStoreState<ApplicationStore, any>(state => state.settings.data!.recaptcha); const { enabled: recaptchaEnabled, siteKey } = useStoreState<ApplicationStore, any>(state => state.settings.data!.recaptcha);
@ -56,66 +34,61 @@ const LoginContainer = ({ isSubmitting, setFieldValue, values, submitForm, handl
return ( return (
<React.Fragment> <React.Fragment>
{ref.current && ref.current.render()} {ref.current && ref.current.render()}
<h2 className={'text-center text-neutral-100 font-medium py-4'}> <LoginFormContainer
Login to Continue title={'Login to Continue'}
</h2> className={'w-full flex'}
<Container> onSubmit={submit}
<FlashMessageRender className={'mb-2 px-1'}/> >
<LoginFormContainer <label htmlFor={'username'}>Username or Email</label>
className={'w-full flex'} <Field
onSubmit={submit} type={'text'}
> id={'username'}
<label htmlFor={'username'}>Username or Email</label> name={'username'}
className={'input'}
/>
<div className={'mt-6'}>
<label htmlFor={'password'}>Password</label>
<Field <Field
type={'text'} type={'password'}
id={'username'} id={'password'}
name={'username'} name={'password'}
className={'input'} className={'input'}
/> />
<div className={'mt-6'}> </div>
<label htmlFor={'password'}>Password</label> <div className={'mt-6'}>
<Field <button
type={'password'} type={'submit'}
id={'password'} className={'btn btn-primary btn-jumbo'}
name={'password'} >
className={'input'} {isSubmitting ?
/> <Spinner size={'tiny'} className={'mx-auto'}/>
</div> :
<div className={'mt-6'}> 'Login'
<button }
type={'submit'} </button>
className={'btn btn-primary btn-jumbo'} </div>
> {recaptchaEnabled &&
{isSubmitting ? <ReCAPTCHA
<Spinner size={'tiny'} className={'mx-auto'}/> ref={ref}
: size={'invisible'}
'Login' sitekey={siteKey || '_invalid_key'}
} onChange={token => {
</button> ref.current && ref.current.reset();
</div> setFieldValue('recaptchaData', token);
{recaptchaEnabled && submitForm();
<ReCAPTCHA }}
ref={ref} onExpired={() => setFieldValue('recaptchaData', null)}
size={'invisible'} />
sitekey={siteKey || '_invalid_key'} }
onChange={token => { <div className={'mt-6 text-center'}>
ref.current && ref.current.reset(); <Link
setFieldValue('recaptchaData', token); to={'/auth/password'}
submitForm(); className={'text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600'}
}} >
onExpired={() => setFieldValue('recaptchaData', null)} Forgot password?
/> </Link>
} </div>
<div className={'mt-6 text-center'}> </LoginFormContainer>
<Link
to={'/auth/password'}
className={'text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600'}
>
Forgot password?
</Link>
</div>
</LoginFormContainer>
</Container>
</React.Fragment> </React.Fragment>
); );
}; };

View file

@ -1,17 +1,47 @@
import React, { forwardRef } from 'react'; import React, { forwardRef } from 'react';
import { Form } from 'formik'; 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) => ( const Container = styled.div`
<Form {...props}> ${breakpoint('sm')`
<div className={'md:flex w-full bg-white shadow-lg rounded-lg p-6 mx-1'}> ${tw`w-4/5 mx-auto`}
<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'}/>
${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>
<div className={'flex-1'}>
{props.children}
</div>
</div> </div>
<div className={'flex-1'}> </Form>
{props.children} </Container>
</div>
</div>
</Form>
)); ));

View file

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

View file

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