connect reset password to login view (#4489)

This commit is contained in:
Jeremy Letto 2021-12-07 21:57:12 -06:00 committed by GitHub
parent 811ee54c76
commit 1f15445c69
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
31 changed files with 893 additions and 445 deletions

View file

@ -7100,6 +7100,11 @@
"@babel/runtime": "^7.10.0"
}
},
"final-form-set-field-touched": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/final-form-set-field-touched/-/final-form-set-field-touched-1.0.1.tgz",
"integrity": "sha512-yvE5AAs9U3OgJQ9YF8NhSF0I0mJEECvOpkaXNqovloxji5Q6gOZ0DCIAyLAKHluGSpsXKUGORyBm8Hq0beZIqQ=="
},
"finalhandler": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz",
@ -13005,6 +13010,14 @@
"@babel/runtime": "^7.15.4"
}
},
"react-final-form-listeners": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/react-final-form-listeners/-/react-final-form-listeners-1.0.3.tgz",
"integrity": "sha512-OrdCNxSS4JQS/EXD+R530kZKFqaPfa+WcXPgVro/h4BpaBDF/Ja+BtHyCzDezCIb5rWaGGdOJIj+tN2YdtvrXg==",
"requires": {
"@babel/runtime": "^7.12.5"
}
},
"react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",

View file

@ -9,6 +9,7 @@
"crypto-js": "^4.1.1",
"dexie": "^3.0.3",
"final-form": "^4.20.4",
"final-form-set-field-touched": "^1.0.1",
"jquery": "^3.6.0",
"lodash": "^4.17.21",
"prop-types": "^15.7.2",
@ -16,6 +17,7 @@
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-final-form": "^6.5.7",
"react-final-form-listeners": "^1.0.3",
"react-redux": "^7.2.6",
"react-router-dom": "^5.3.0",
"react-scripts": "4.0.3",

View file

@ -2,8 +2,8 @@ import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';
const CheckboxField = ({ input, label }) => {
const { value, onChange } = input;
const CheckboxField = (props) => {
const { input: { value, onChange }, label, ...args } = props;
// @TODO this isnt unchecking properly
return (
@ -12,9 +12,10 @@ const CheckboxField = ({ input, label }) => {
label={label}
control={
<Checkbox
{ ...args }
className="checkbox-field__box"
checked={!!value}
onChange={onChange}
onChange={(e, checked) => onChange(checked)}
color="primary"
/>
}

View file

@ -17,7 +17,7 @@ const useStyles = makeStyles(theme => ({
},
}));
const InputField = ({ input, label, name, autoComplete, type, meta: { touched, error, warning } }) => {
const InputField = ({ input, meta: { touched, error, warning }, ...args }) => {
const classes = useStyles();
return (
@ -38,15 +38,12 @@ const InputField = ({ input, label, name, autoComplete, type, meta: { touched, e
) }
<TextField
{ ...input }
{ ...args }
className="rounded"
variant="outlined"
margin="dense"
fullWidth={true}
label={label}
name={name}
type={type}
autoComplete={autoComplete}
{ ...input }
/>
</div>
);

View file

@ -29,7 +29,9 @@ const useStyles = makeStyles(theme => ({
},
}));
const KnownHosts = ({ input: { onChange }, meta: { touched, error, warning } }) => {
const KnownHosts = (props) => {
const { input: { onChange }, meta, disabled } = props;
const { touched, error, warning } = meta;
const classes = useStyles();
const [hostsState, setHostsState] = useState({
@ -169,6 +171,7 @@ const KnownHosts = ({ input: { onChange }, meta: { touched, error, warning } })
value={hostsState.selectedHost}
fullWidth={true}
onChange={e => selectHost(e.target.value)}
disabled={disabled}
>
<Button value={hostsState.selectedHost} onClick={openAddKnownHostDialog}>
<span>Add new host</span>

View file

@ -1,6 +1,7 @@
// Common components
export { default as Card } from './Card/Card';
export { default as CardDetails } from './CardDetails/CardDetails';
export { default as CountryDropdown } from './CountryDropdown/CountryDropdown';
export { default as Header } from './Header/Header';
export { default as InputField } from './InputField/InputField';
export { default as InputAction } from './InputAction/InputAction';
@ -16,7 +17,3 @@ export { default as ScrollToBottomOnChanges } from './ScrollToBottomOnChanges/Sc
// Guards
export { default as AuthGuard } from './Guard/AuthGuard';
export { default as ModGuard } from './Guard/ModGuard';
// Dialogs
export { default as RequestPasswordResetDialog } from './RequestPasswordResetDialog/RequestPasswordResetDialog';
export { default as ResetPasswordDialog } from './ResetPasswordDialog/ResetPasswordDialog';

View file

@ -9,7 +9,7 @@ import Typography from '@material-ui/core/Typography';
import { AuthenticationService } from 'api';
import { RequestPasswordResetDialog, ResetPasswordDialog } from 'components';
import { RegistrationDialog, RequestPasswordResetDialog, ResetPasswordDialog } from 'dialogs';
import { LoginForm } from 'forms';
import { useReduxEffect } from 'hooks';
import { Images } from 'images';
@ -63,8 +63,10 @@ const Login = ({ state, description }: LoginProps) => {
const [hostIdToRemember, setHostIdToRemember] = useState(null);
const [dialogState, setDialogState] = useState({
passwordResetRequestDialog: false,
resetPasswordDialog: false
resetPasswordDialog: false,
registrationDialog: false,
});
const [userToResetPassword, setUserToResetPassword] = useState(null);
useReduxEffect(() => {
closeRequestPasswordResetDialog();
@ -88,11 +90,7 @@ const Login = ({ state, description }: LoginProps) => {
return !isConnected && description?.length;
};
const createAccount = () => {
console.log('Login.createAccount->openForgotPasswordDialog');
};
const onSubmit = useCallback((loginForm) => {
const onSubmitLogin = useCallback((loginForm) => {
const {
userName,
password,
@ -133,16 +131,43 @@ const Login = ({ state, description }: LoginProps) => {
});
};
const handleRequestPasswordResetDialogSubmit = async ({ user, email, host, port }) => {
const handleRegistrationDialogSubmit = (form) => {
const { userName, password, email, country, realName, selectedHost } = form;
AuthenticationService.register({
...getHostPort(selectedHost),
userName,
password,
email,
country,
realName,
});
};
const handleRequestPasswordResetDialogSubmit = (form) => {
const { userName, email, selectedHost } = form;
const { host, port } = getHostPort(selectedHost);
if (email) {
AuthenticationService.resetPasswordChallenge({ user, email, host, port } as any);
AuthenticationService.resetPasswordChallenge({ userName, email, host, port } as any);
} else {
AuthenticationService.resetPasswordRequest({ user, host, port } as any);
setUserToResetPassword(userName);
AuthenticationService.resetPasswordRequest({ userName, host, port } as any);
}
};
const handleResetPasswordDialogSubmit = async ({ user, token, newPassword, passwordAgain, host, port }) => {
AuthenticationService.resetPassword({ user, token, newPassword, host, port } as any);
const handleResetPasswordDialogSubmit = ({ userName, token, newPassword, selectedHost }) => {
const { host, port } = getHostPort(selectedHost);
AuthenticationService.resetPassword({ userName, token, newPassword, host, port } as any);
};
const skipTokenRequest = (userName) => {
setUserToResetPassword(userName);
setDialogState(s => ({ ...s,
passwordResetRequestDialog: false,
resetPasswordDialog: true,
}));
};
const closeRequestPasswordResetDialog = () => {
@ -161,6 +186,14 @@ const Login = ({ state, description }: LoginProps) => {
setDialogState(s => ({ ...s, resetPasswordDialog: true }));
}
const closeRegistrationDialog = () => {
setDialogState(s => ({ ...s, registrationDialog: false }));
}
const openRegistrationDialog = () => {
setDialogState(s => ({ ...s, registrationDialog: true }));
}
return (
<div className={'login overflow-scroll ' + classes.root}>
{ isConnected && <Redirect from="*" to={RouteEnum.SERVER} />}
@ -175,7 +208,7 @@ const Login = ({ state, description }: LoginProps) => {
<Typography variant="h1">Login</Typography>
<Typography variant="subtitle1">A cross-platform virtual tabletop for multiplayer card games.</Typography>
<div className="login-form">
<LoginForm onSubmit={onSubmit} />
<LoginForm onSubmit={onSubmitLogin} onResetPassword={openRequestPasswordResetDialog} />
</div>
{
@ -189,7 +222,7 @@ const Login = ({ state, description }: LoginProps) => {
<div className="login-footer">
<div className="login-footer_register">
<span>Not registered yet?</span>
<Button color="primary" onClick={createAccount}>Create an account</Button>
<Button color="primary" onClick={openRegistrationDialog}>Create an account</Button>
</div>
<Typography variant="subtitle2" className="login-footer__copyright">
Cockatrice is an open source project. { new Date().getUTCFullYear() }
@ -236,16 +269,24 @@ const Login = ({ state, description }: LoginProps) => {
</Paper>
</div>
<RegistrationDialog
isOpen={dialogState.registrationDialog}
onSubmit={handleRegistrationDialogSubmit}
handleClose={closeRegistrationDialog}
/>
<RequestPasswordResetDialog
isOpen={dialogState.passwordResetRequestDialog}
onSubmit={handleRequestPasswordResetDialogSubmit}
handleClose={closeRequestPasswordResetDialog}
skipTokenRequest={skipTokenRequest}
/>
<ResetPasswordDialog
isOpen={dialogState.resetPasswordDialog}
onSubmit={handleResetPasswordDialogSubmit}
handleClose={closeResetPasswordDialog}
userName={userToResetPassword}
/>
</div>
);

View file

@ -3,3 +3,8 @@
justify-content: space-between;
align-items: center;
}
.dialog-content {
width: 700px;
max-width: 100%;
}

View file

@ -10,13 +10,13 @@ import { RegisterForm } from 'forms';
import './RegistrationDialog.css';
const RegistrationDialog = ({ classes, handleClose, isOpen }: any) => {
const RegistrationDialog = ({ classes, handleClose, isOpen, onSubmit }: any) => {
const handleOnClose = () => {
handleClose();
}
return (
<Dialog onClose={handleOnClose} open={isOpen}>
<Dialog className="RegistrationDialog" onClose={handleOnClose} open={isOpen} maxWidth='xl'>
<DialogTitle disableTypography className="dialog-title">
<Typography variant="h6">Create New Account</Typography>
@ -26,8 +26,8 @@ const RegistrationDialog = ({ classes, handleClose, isOpen }: any) => {
</IconButton>
) : null}
</DialogTitle>
<DialogContent>
<RegisterForm onSubmit={handleOnClose}></RegisterForm>
<DialogContent className="dialog-content">
<RegisterForm onSubmit={onSubmit}></RegisterForm>
</DialogContent>
</Dialog>
);

View file

@ -10,7 +10,7 @@ import { RequestPasswordResetForm } from 'forms';
import './RequestPasswordResetDialog.css';
const RequestPasswordResetDialog = ({ classes, handleClose, isOpen, onSubmit }: any) => {
const RequestPasswordResetDialog = ({ classes, handleClose, isOpen, onSubmit, skipTokenRequest }: any) => {
const handleOnClose = () => {
handleClose();
}
@ -27,7 +27,7 @@ const RequestPasswordResetDialog = ({ classes, handleClose, isOpen, onSubmit }:
) : null}
</DialogTitle>
<DialogContent>
<RequestPasswordResetForm onSubmit={onSubmit}></RequestPasswordResetForm>
<RequestPasswordResetForm onSubmit={onSubmit} skipTokenRequest={skipTokenRequest}></RequestPasswordResetForm>
</DialogContent>
</Dialog>
);

View file

@ -10,7 +10,7 @@ import { ResetPasswordForm } from 'forms';
import './ResetPasswordDialog.css';
const ResetPasswordDialog = ({ classes, handleClose, isOpen, onSubmit }: any) => {
const ResetPasswordDialog = ({ classes, handleClose, isOpen, onSubmit, userName }: any) => {
const handleOnClose = () => {
handleClose();
}
@ -27,7 +27,7 @@ const ResetPasswordDialog = ({ classes, handleClose, isOpen, onSubmit }: any) =>
) : null}
</DialogTitle>
<DialogContent>
<ResetPasswordForm onSubmit={onSubmit}/>
<ResetPasswordForm onSubmit={onSubmit} userName={userName}/>
</DialogContent>
</Dialog>
);

View file

@ -1,3 +1,5 @@
export { default as CardImportDialog } from './CardImportDialog/CardImportDialog';
export { default as KnownHostDialog } from './KnownHostDialog/KnownHostDialog';
export { default as RegistrationDialog } from './RegistrationDialog/RegistrationDialog';
export { default as RequestPasswordResetDialog } from './RequestPasswordResetDialog/RequestPasswordResetDialog';
export { default as ResetPasswordDialog } from './ResetPasswordDialog/ResetPasswordDialog';

View file

@ -10,9 +10,29 @@ import { InputField } from 'components';
import './KnownHostForm.css';
function KnownHostForm({ host, onRemove, onSubmit }) {
const KnownHostForm = ({ host, onRemove, onSubmit }) => {
const [confirmDelete, setConfirmDelete] = useState(false);
const validate = values => {
const errors: any = {};
if (!values.name) {
errors.name = 'Required'
}
if (!values.host) {
errors.host = 'Required'
}
if (!values.port) {
errors.port = 'Required'
}
if (Object.keys(errors).length) {
return errors;
}
};
return (
<Form
initialValues={{
@ -22,25 +42,7 @@ function KnownHostForm({ host, onRemove, onSubmit }) {
port: host?.port,
}}
onSubmit={onSubmit}
validate={values => {
const errors: any = {};
if (!values.name) {
errors.name = 'Required'
}
if (!values.host) {
errors.host = 'Required'
}
if (!values.port) {
errors.port = 'Required'
}
if (Object.keys(errors).length) {
return errors;
}
}}
validate={validate}
>
{({ handleSubmit }) => (
<form className="KnownHostForm" onSubmit={handleSubmit}>
@ -74,7 +76,7 @@ function KnownHostForm({ host, onRemove, onSubmit }) {
) }
</Form>
);
}
};
const mapStateToProps = () => ({

View file

@ -1,7 +1,8 @@
// eslint-disable-next-line
import React, { Component, useCallback, useEffect, useState, useRef } from 'react';
import { connect } from 'react-redux';
import { Form, Field, reduxForm, change, FormSubmitHandler } from 'redux-form'
import { Form, Field, useField } from 'react-final-form';
import { OnChange } from 'react-final-form-listeners';
import Button from '@material-ui/core/Button';
@ -16,151 +17,142 @@ import './LoginForm.css';
const PASSWORD_LABEL = 'Password';
const STORED_PASSWORD_LABEL = '* SAVED *';
const LoginForm: any = ({ dispatch, form, submit, handleSubmit }: LoginFormProps) => {
const password: any = useRef();
const LoginForm = ({ onSubmit, onResetPassword }: LoginFormProps) => {
const [host, setHost] = useState(null);
const [remember, setRemember] = useState(false);
const [passwordLabel, setPasswordLabel] = useState(PASSWORD_LABEL);
const [hasStoredPassword, useStoredPassword] = useState(false);
const [autoConnect, setAutoConnect] = useAutoConnect();
const [autoConnect, setAutoConnect] = useAutoConnect(() => {
dispatch(change(form, 'autoConnect', autoConnect));
if (autoConnect && !remember) {
setRemember(true);
}
});
useEffect(() => {
SettingDTO.get(APP_USER).then((userSetting: SettingDTO) => {
if (userSetting?.autoConnect && !AuthenticationService.connectionAttemptMade()) {
HostDTO.getAll().then(hosts => {
let lastSelectedHost = hosts.find(({ lastSelected }) => lastSelected);
if (lastSelectedHost?.remember && lastSelectedHost?.hashedPassword) {
dispatch(change(form, 'selectedHost', lastSelectedHost));
dispatch(change(form, 'userName', lastSelectedHost.userName));
dispatch(change(form, 'remember', true));
setPasswordLabel(STORED_PASSWORD_LABEL);
dispatch(submit);
}
});
}
});
}, [submit, dispatch, form]);
useEffect(() => {
dispatch(change(form, 'remember', remember));
if (!remember) {
setAutoConnect(false);
}
if (!remember) {
useStoredPassword(false);
setPasswordLabel(PASSWORD_LABEL);
} else if (host?.hashedPassword) {
useStoredPassword(true);
setPasswordLabel(STORED_PASSWORD_LABEL);
}
}, [remember, dispatch, form]);
useEffect(() => {
if (!host) {
return
}
dispatch(change(form, 'userName', host.userName));
dispatch(change(form, 'password', ''));
setRemember(host.remember);
setAutoConnect(host.remember && autoConnect);
if (host.remember && host.hashedPassword) {
// TODO: check if this causes a double render (maybe try combined state)
// try deriving useStoredPassword
useStoredPassword(true);
setPasswordLabel(STORED_PASSWORD_LABEL);
} else {
useStoredPassword(false);
setPasswordLabel(PASSWORD_LABEL);
}
}, [host, dispatch, form]);
const onRememberChange = event => setRemember(event.target.checked);
const onAutoConnectChange = event => setAutoConnect(event.target.checked);
const onHostChange = h => setHost(h);
const forgotPassword = () => {
console.log('Show recover password dialog, then AuthService.forgotPasswordRequest');
};
return (
<Form className='loginForm' onSubmit={handleSubmit}>
<div className='loginForm-items'>
<div className='loginForm-item'>
<Field label='Username' name='userName' component={InputField} autoComplete='off' />
</div>
<div className='loginForm-item'>
<Field
label={passwordLabel}
ref={password}
onFocus={() => setPasswordLabel(PASSWORD_LABEL)}
onBlur={() => !password.current.value && hasStoredPassword && setPasswordLabel(STORED_PASSWORD_LABEL)}
name='password'
type='password'
component={InputField}
autoComplete='new-password'
/>
</div>
<div className='loginForm-actions'>
<Field label='Save Password' name='remember' component={CheckboxField} onChange={onRememberChange} />
<Button color='primary' onClick={forgotPassword}>Forgot Password</Button>
</div>
<div className='loginForm-item'>
<Field name='selectedHost' component={KnownHosts} onChange={onHostChange} />
</div>
<div className='loginForm-actions'>
<Field label='Auto Connect' name='autoConnect' component={CheckboxField} onChange={onAutoConnectChange} />
</div>
</div>
<Button className='loginForm-submit rounded tall' color='primary' variant='contained' type='submit'>
Login
</Button>
</Form>
);
};
const propsMap = {
form: FormKey.LOGIN,
validate: values => {
const validate = values => {
const errors: any = {};
if (!values.user) {
errors.user = 'Required';
if (!values.userName) {
errors.userName = 'Required';
}
if (!values.password && !values.selectedHost?.hashedPassword) {
errors.password = 'Required';
}
if (!values.selectedHost) {
errors.selectedHost = 'Required';
}
return errors;
}
const useStoredPassword = (remember) => remember && host.hashedPassword;
const togglePasswordLabel = (useStoredLabel) => {
setPasswordLabel(useStoredLabel ? STORED_PASSWORD_LABEL : PASSWORD_LABEL);
};
return (
<Form onSubmit={onSubmit} validate={validate}>
{({ handleSubmit, form }) => {
const { values } = form.getState();
useEffect(() => {
SettingDTO.get(APP_USER).then((userSetting: SettingDTO) => {
if (userSetting?.autoConnect && !AuthenticationService.connectionAttemptMade()) {
HostDTO.getAll().then(hosts => {
let lastSelectedHost = hosts.find(({ lastSelected }) => lastSelected);
if (lastSelectedHost?.remember && lastSelectedHost?.hashedPassword) {
togglePasswordLabel(true);
form.change('selectedHost', lastSelectedHost);
form.change('userName', lastSelectedHost.userName);
form.change('remember', true);
form.submit();
}
});
}
});
}, []);
useEffect(() => {
if (!host) {
return;
}
form.change('userName', host.userName);
form.change('password', '');
onRememberChange(host.remember);
onAutoConnectChange(host.remember && autoConnect);
togglePasswordLabel(useStoredPassword(host.remember));
}, [host]);
const onUserNameChange = (userName) => {
const fieldChanged = host.userName?.toLowerCase() !== values.userName?.toLowerCase();
if (useStoredPassword(values.remember) && fieldChanged) {
setHost(({ hashedPassword, ...s }) => ({ ...s, userName }));
}
}
const onRememberChange = (checked) => {
form.change('remember', checked);
if (!checked && values.autoConnect) {
onAutoConnectChange(false);
}
togglePasswordLabel(useStoredPassword(checked));
}
const onAutoConnectChange = (checked) => {
setAutoConnect(checked);
form.change('autoConnect', checked);
if (checked && !values.remember) {
form.change('remember', true);
}
}
return (
<form className='loginForm' onSubmit={handleSubmit}>
<div className='loginForm-items'>
<div className='loginForm-item'>
<Field label='Username' name='userName' component={InputField} autoComplete='off' />
<OnChange name="userName">{onUserNameChange}</OnChange>
</div>
<div className='loginForm-item'>
<Field
label={passwordLabel}
onFocus={() => setPasswordLabel(PASSWORD_LABEL)}
onBlur={() => togglePasswordLabel(useStoredPassword(values.remember))}
name='password'
type='password'
component={InputField}
autoComplete='new-password'
/>
</div>
<div className='loginForm-actions'>
<Field label='Save Password' name='remember' component={CheckboxField} />
<OnChange name="remember">{onRememberChange}</OnChange>
<Button color='primary' onClick={onResetPassword}>Forgot Password</Button>
</div>
<div className='loginForm-item'>
<Field name='selectedHost' component={KnownHosts} />
<OnChange name="selectedHost">{setHost}</OnChange>
</div>
<div className='loginForm-actions'>
<Field label='Auto Connect' name='autoConnect' component={CheckboxField} />
<OnChange name="autoConnect">{onAutoConnectChange}</OnChange>
</div>
</div>
<Button className='loginForm-submit rounded tall' color='primary' variant='contained' type='submit'>
Login
</Button>
</form>
)
}}
</Form>
);
};
interface LoginFormProps {
form: string;
dispatch: Function;
submit: Function;
handleSubmit: FormSubmitHandler;
onSubmit: any;
onResetPassword: any;
}
const mapStateToProps = (state) => ({
});
export default connect(mapStateToProps)(reduxForm(propsMap)(LoginForm));
export default LoginForm;

View file

@ -1,21 +1,18 @@
.registerForm {
.RegisterForm {
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
}
.RegisterForm-column {
width: 48%;
}
.RegisterForm-item {
margin-bottom: 20px;
}
.RegisterForm-submit {
width: 100%;
}
.registerForm-submit {
width: 100%;
/*padding is off, something in material-theme is causing it*/
}
.row {
display: flex;
flex-direction: row;
width: 100%;
justify-content: space-between;
}
.column {
width: 48%;
flex: 0 1 auto;
align-self: auto;
}

View file

@ -1,67 +1,159 @@
// eslint-disable-next-line
import React, { Component } from 'react';
import React, { Component, useState } from 'react';
import { connect } from 'react-redux';
import { Form, Field, reduxForm, change } from 'redux-form'
import { Form, Field } from 'react-final-form';
import { OnChange } from 'react-final-form-listeners';
import setFieldTouched from 'final-form-set-field-touched'
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { InputField, KnownHosts } from 'components';
import { useReduxEffect } from 'hooks';
import { ServerTypes } from 'store';
import { FormKey } from 'types';
import './RegisterForm.css';
const RegisterForm = (props) => {
const { dispatch, handleSubmit } = props;
const RegisterForm = ({ onSubmit }: RegisterFormProps) => {
const [emailRequired, setEmailRequired] = useState(false);
const [error, setError] = useState(null);
const [emailError, setEmailError] = useState(null);
const [passwordError, setPasswordError] = useState(null);
const [userNameError, setUserNameError] = useState(null);
const onHostChange: any = ({ host, port }) => {
dispatch(change(FormKey.REGISTER, 'host', host));
dispatch(change(FormKey.REGISTER, 'port', port));
const onHostChange = (host) => setEmailRequired(false);
const onEmailChange = () => emailError && setEmailError(null);
const onPasswordChange = () => passwordError && setPasswordError(null);
const onUserNameChange = () => userNameError && setUserNameError(null);
useReduxEffect(() => {
setEmailRequired(true);
}, ServerTypes.REGISTRATION_REQUIRES_EMAIL);
useReduxEffect(({ error }) => {
setError(error);
}, ServerTypes.REGISTRATION_FAILED);
useReduxEffect(({ error }) => {
setEmailError(error);
}, ServerTypes.REGISTRATION_EMAIL_ERROR);
useReduxEffect(({ error }) => {
setPasswordError(error);
}, ServerTypes.REGISTRATION_PASSWORD_ERROR);
useReduxEffect(({ error }) => {
setUserNameError(error);
}, ServerTypes.REGISTRATION_USERNAME_ERROR);
const handleOnSubmit = form => {
setError(null);
onSubmit(form);
}
const validate = values => {
const errors: any = {};
if (!values.userName) {
errors.userName = 'Required';
} else if (userNameError) {
errors.userName = userNameError;
}
if (!values.password) {
errors.password = 'Required';
} else if (passwordError) {
errors.password = passwordError;
}
if (!values.passwordConfirm) {
errors.passwordConfirm = 'Required';
} else if (values.password !== values.passwordConfirm) {
errors.passwordConfirm = 'Passwords don\'t match'
}
if (!values.selectedHost) {
errors.selectedHost = 'Required';
}
if (emailRequired && !values.email) {
errors.email = 'Required';
} else if (emailError) {
errors.email = emailError;
}
return errors;
}
return (
<Form className="registerForm row" onSubmit={handleSubmit} autoComplete="off">
<div className="leftRegisterForm column" >
<div className="registerForm-item">
<Field name="selectedHost" component={KnownHosts} onChange={onHostChange} />
{ /* Padding is off */ }
</div>
<div className="registerForm-item">
<Field label="Country" name="country" component={InputField} />
</div>
<div className="registerForm-item">
<Field label="Real Name" name="realName" component={InputField} />
</div>
<div className="registerForm-item">
<Field label="Email" name="email" type="email" component={InputField} />
</div>
</div>
<div className="rightRegisterForm column">
<div className="registerForm-item">
<Field label="Player Name" name="user" component={InputField} />
</div>
<div className="registerForm-item">
<Field label="Password" name="pass" type="password" component={InputField} />
</div>
<div className="registerForm-item">
<Field label="Password (again)" name="passwordConfirm" type="password" component={InputField} />
</div>
<Button className="registerForm-submit tall" color="primary" variant="contained" type="submit">
Register
</Button>
</div>
<Form onSubmit={handleOnSubmit} validate={validate} mutators={{ setFieldTouched }}>
{({ handleSubmit, form, ...args }) => {
const { values } = form.getState();
if (emailRequired) {
// Allow form render to complete
setTimeout(() => form.mutators.setFieldTouched('email', true))
}
return (
<>
<form className="RegisterForm" onSubmit={handleSubmit} autoComplete="off">
<div className="RegisterForm-column">
<div className="RegisterForm-item">
<Field label="Player Name" name="userName" component={InputField} />
<OnChange name="userName">{onUserNameChange}</OnChange>
</div>
<div className="RegisterForm-item">
<Field label="Password" name="password" type="password" component={InputField} autoComplete='new-password' />
<OnChange name="password">{onPasswordChange}</OnChange>
</div>
<div className="RegisterForm-item">
<Field
label="Confirm Password"
name="passwordConfirm"
type="password"
component={InputField}
autoComplete='new-password'
/>
</div>
<div className="RegisterForm-item">
<Field name="selectedHost" component={KnownHosts} />
<OnChange name="selectedHost">{onHostChange}</OnChange>
</div>
</div>
<div className="RegisterForm-column" >
<div className="RegisterForm-item">
<Field label="Real Name" name="realName" component={InputField} autoComplete='off' />
</div>
<div className="RegisterForm-item">
<Field label="Email" name="email" type="email" component={InputField} />
<OnChange name="email">{onEmailChange}</OnChange>
</div>
<div className="RegisterForm-item">
<Field label="Country" name="country" component={InputField} />
</div>
<Button className="RegisterForm-submit tall" color="primary" variant="contained" type="submit">
Register
</Button>
</div>
</form>
{ error && (
<div className="RegisterForm-item">
<Typography color="error">{error}</Typography>
</div>
)}
</>
);
}}
</Form >
);
};
const propsMap = {
form: FormKey.REGISTER,
};
interface RegisterFormProps {
onSubmit: any;
}
const mapStateToProps = () => ({
initialValues: {
}
});
export default connect(mapStateToProps)(reduxForm(propsMap)(RegisterForm));
export default RegisterForm;

View file

@ -1,13 +1,6 @@
.RequestPasswordResetForm {
width: 100%;
}
.RequestPasswordResetForm-MFA-Message {
margin-top: -20px;
}
.RequestPasswordResetForm-Error {
margin-bottom: 10px;
padding-bottom: 15px;
}
.RequestPasswordResetForm-item {
@ -26,3 +19,7 @@
.RequestPasswordResetForm-submit {
width: 100%;
}
.selectedHost {
margin-top: 40px;
}

View file

@ -1,9 +1,11 @@
// eslint-disable-next-line
import React, { useState } from "react";
import { connect } from 'react-redux';
import { Form, Field, reduxForm, change } from 'redux-form'
import { Form, Field } from 'react-final-form';
import { OnChange } from 'react-final-form-listeners';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { InputField, KnownHosts } from 'components';
import { FormKey } from 'types';
@ -12,16 +14,10 @@ import './RequestPasswordResetForm.css';
import { useReduxEffect } from 'hooks';
import { ServerTypes } from 'store';
const RequestPasswordResetForm = (props) => {
const { dispatch, handleSubmit } = props;
const RequestPasswordResetForm = ({ onSubmit, skipTokenRequest }) => {
const [errorMessage, setErrorMessage] = useState(false);
const [isMFA, setIsMFA] = useState(false);
const onHostChange: any = ({ host, port }) => {
dispatch(change(FormKey.RESET_PASSWORD_REQUEST, 'host', host));
dispatch(change(FormKey.RESET_PASSWORD_REQUEST, 'port', port));
}
useReduxEffect(() => {
setErrorMessage(true);
}, ServerTypes.RESET_PASSWORD_FAILED, []);
@ -30,63 +26,73 @@ const RequestPasswordResetForm = (props) => {
setIsMFA(true);
}, ServerTypes.RESET_PASSWORD_CHALLENGE, []);
const onSubmit = (event) => {
const handleOnSubmit = (form) => {
setErrorMessage(false);
handleSubmit(event);
onSubmit(form);
}
const validate = values => {
const errors: any = {};
if (!values.userName) {
errors.userName = 'Required';
}
if (isMFA && !values.email) {
errors.email = 'Required';
}
if (!values.selectedHost) {
errors.selectedHost = 'Required';
}
return errors;
};
return (
<Form className="RequestPasswordResetForm" onSubmit={onSubmit}>
<div className="RequestPasswordResetForm-items">
{errorMessage ? (
<div className="RequestPasswordResetForm-Error">Request Password Reset Failed, please try again</div>
) : null}
<div className="RequestPasswordResetForm-item">
<Field label="Username" name="user" component={InputField} autoComplete="username" />
</div>
{isMFA ? (
<div className="RequestPasswordResetForm-item">
<div className="RequestPasswordResetForm-MFA-Message">Server has multi-factor authentication enabled</div>
<Field label="Email" name="email" component={InputField} autoComplete="email" />
</div>
) : null}
<div className="RequestPasswordResetForm-item">
<Field name='selectedHost' component={KnownHosts} onChange={onHostChange} />
</div>
</div>
<Button className="RequestPasswordResetForm-submit rounded tall" color="primary" variant="contained" type="submit">
Request Reset Token
</Button>
<Form onSubmit={handleOnSubmit} validate={validate}>
{({ handleSubmit, form }) => {
const onHostChange: any = ({ userName }) => {
form.change('userName', userName);
setIsMFA(false);
}
return (
<form className="RequestPasswordResetForm" onSubmit={handleSubmit}>
<div className="RequestPasswordResetForm-items">
<div className="RequestPasswordResetForm-item">
<Field label="Username" name="userName" component={InputField} autoComplete="username" disabled={isMFA} />
</div>
{isMFA ? (
<div className="RequestPasswordResetForm-item">
<Field label="Email" name="email" component={InputField} autoComplete="email" />
<div>Server has multi-factor authentication enabled</div>
</div>
) : null}
<div className="RequestPasswordResetForm-item selectedHost">
<Field name='selectedHost' component={KnownHosts} disabled={isMFA} />
<OnChange name="selectedHost">{onHostChange}</OnChange>
</div>
{errorMessage && (
<div className="RequestPasswordResetForm-item">
<Typography color="error">Request password reset failed</Typography>
</div>
)}
</div>
<Button className="RequestPasswordResetForm-submit rounded tall" color="primary" variant="contained" type="submit">
Request Reset Token
</Button>
<div>
<Button color="primary" onClick={() => skipTokenRequest(form.getState().values.userName)}>
I already have a reset token
</Button>
</div>
</form>
);
}}
</Form>
);
};
const propsMap = {
form: FormKey.RESET_PASSWORD_REQUEST,
validate: values => {
const errors: any = {};
if (!values.user) {
errors.user = 'Required';
}
if (!values.host) {
errors.host = 'Required';
}
if (!values.port) {
errors.port = 'Required';
}
return errors;
}
};
const mapStateToProps = () => ({
initialValues: {
// host: "mtg.tetrarch.co/servatrice",
// port: "443"
// host: "server.cockatrice.us",
// port: "4748"
}
});
export default connect(mapStateToProps)(reduxForm(propsMap)(RequestPasswordResetForm));
export default RequestPasswordResetForm;

View file

@ -1,5 +1,6 @@
.ResetPasswordForm {
width: 100%;
padding-bottom: 15px;
}
.ResetPasswordForm-item {

View file

@ -1,9 +1,11 @@
// eslint-disable-next-line
import React, {useState} from "react";
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { Form, Field, reduxForm, change } from 'redux-form'
import { Form, Field } from 'react-final-form'
import { OnChange } from 'react-final-form-listeners'
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { InputField, KnownHosts } from 'components';
import { FormKey } from 'types';
@ -12,58 +14,18 @@ import './ResetPasswordForm.css';
import { useReduxEffect } from '../../hooks';
import { ServerTypes } from '../../store';
const ResetPasswordForm = (props) => {
const { dispatch, handleSubmit } = props;
const ResetPasswordForm = ({ onSubmit, userName }) => {
const [errorMessage, setErrorMessage] = useState(false);
const onHostChange: any = ({ host, port }) => {
dispatch(change(FormKey.RESET_PASSWORD, 'host', host));
dispatch(change(FormKey.RESET_PASSWORD, 'port', port));
}
useReduxEffect(() => {
setErrorMessage(true);
}, ServerTypes.RESET_PASSWORD_FAILED, []);
return (
<Form className="ResetPasswordForm" onSubmit={handleSubmit}>
<div className="ResetPasswordForm-items">
{errorMessage ? (
<div><h3>Password Reset Failed, please try again</h3></div>
) : null}
<div className="ResetPasswordForm-item">
<Field label="Username" name="user" component={InputField} autoComplete="username" />
</div>
<div className="ResetPasswordForm-item">
<Field label="Token" name="token" component={InputField} />
</div>
<div className="ResetPasswordForm-item">
<Field label="Password" name="newPassword" component={InputField} />
</div>
<div className="ResetPasswordForm-item">
<Field label="Password Again" name="passwordAgain" component={InputField} />
</div>
<div className="ResetPasswordForm-item">
<Field name='selectedHost' component={KnownHosts} onChange={onHostChange} />
</div>
</div>
<Button className="ResetPasswordForm-submit rounded tall" color="primary" variant="contained" type="submit">
Change Password
</Button>
</Form>
);
};
const propsMap = {
form: FormKey.RESET_PASSWORD,
validate: values => {
const validate = values => {
const errors: any = {};
if (!values.user) {
errors.user = 'Required';
if (!values.userName) {
errors.userName = 'Required';
}
if (!values.token) {
errors.token = 'Required';
@ -76,24 +38,47 @@ const propsMap = {
} else if (values.newPassword !== values.passwordAgain) {
errors.passwordAgain = 'Passwords don\'t match'
}
if (!values.host) {
errors.host = 'Required';
}
if (!values.port) {
errors.port = 'Required';
if (!values.selectedHost) {
errors.selectedHost = 'Required';
}
return errors;
}
};
return (
<Form onSubmit={onSubmit} validate={validate} initialValues={{ userName }}>
{({ handleSubmit, form }) => (
<form className='ResetPasswordForm' onSubmit={handleSubmit}>
<div className='ResetPasswordForm-items'>
<div className='ResetPasswordForm-item'>
<Field label='Username' name='userName' component={InputField} autoComplete='username' disabled={!!userName} />
</div>
<div className='ResetPasswordForm-item'>
<Field label='Token' name='token' component={InputField} />
</div>
<div className='ResetPasswordForm-item'>
<Field label='Password' name='newPassword' type='password' component={InputField} autoComplete='new-password' />
</div>
<div className='ResetPasswordForm-item'>
<Field label='Password Again' name='passwordAgain' type='password' component={InputField} autoComplete='new-password' />
</div>
<div className='ResetPasswordForm-item'>
<Field name='selectedHost' component={KnownHosts} disabled />
</div>
{errorMessage && (
<div className='ResetPasswordForm-item'>
<Typography color="error">Password reset failed</Typography>
</div>
)}
</div>
<Button className='ResetPasswordForm-submit rounded tall' color='primary' variant='contained' type='submit'>
Reset Password
</Button>
</form>
)}
</Form>
);
};
const mapStateToProps = () => ({
initialValues: {
// host: "mtg.tetrarch.co/servatrice",
// port: "443"
// host: "server.cockatrice.us",
// port: "4748"
}
});
export default connect(mapStateToProps)(reduxForm(propsMap)(ResetPasswordForm));
export default ResetPasswordForm;

View file

@ -6,7 +6,7 @@ import { APP_USER } from 'types';
type OnChange = () => void;
export function useAutoConnect(onChange: OnChange) {
export function useAutoConnect() {
const [setting, setSetting] = useState(undefined);
const [autoConnect, setAutoConnect] = useState(undefined);
@ -31,8 +31,6 @@ export function useAutoConnect(onChange: OnChange) {
if (setting) {
setting.autoConnect = autoConnect;
setting.save();
onChange();
}
}, [setting, autoConnect]);

View file

@ -72,18 +72,37 @@ export const Actions = {
logs
}),
clearLogs: () => ({
type: Types.CLEAR_LOGS
type: Types.CLEAR_LOGS,
}),
registrationRequiresEmail: () => ({
type: Types.REGISTRATION_REQUIRES_EMAIL,
}),
registrationFailed: (error) => ({
type: Types.REGISTRATION_FAILED,
error
}),
registrationEmailError: (error) => ({
type: Types.REGISTRATION_EMAIL_ERROR,
error
}),
registrationPasswordError: (error) => ({
type: Types.REGISTRATION_PASSWORD_ERROR,
error
}),
registrationUserNameError: (error) => ({
type: Types.REGISTRATION_USERNAME_ERROR,
error
}),
resetPassword: () => ({
type: Types.RESET_PASSWORD_REQUESTED
type: Types.RESET_PASSWORD_REQUESTED,
}),
resetPasswordFailed: () => ({
type: Types.RESET_PASSWORD_FAILED
type: Types.RESET_PASSWORD_FAILED,
}),
resetPasswordChallenge: () => ({
type: Types.RESET_PASSWORD_CHALLENGE
type: Types.RESET_PASSWORD_CHALLENGE,
}),
resetPasswordSuccess: () => ({
type: Types.RESET_PASSWORD_SUCCESS
type: Types.RESET_PASSWORD_SUCCESS,
})
}

View file

@ -65,6 +65,21 @@ export const Dispatch = {
serverMessage: message => {
store.dispatch(Actions.serverMessage(message));
},
registrationRequiresEmail: () => {
store.dispatch(Actions.registrationRequiresEmail());
},
registrationFailed: (error) => {
store.dispatch(Actions.registrationFailed(error));
},
registrationEmailError: (error) => {
store.dispatch(Actions.registrationEmailError(error));
},
registrationPasswordError: (error) => {
store.dispatch(Actions.registrationPasswordError(error));
},
registrationUserNameError: (error) => {
store.dispatch(Actions.registrationUserNameError(error));
},
resetPassword: () => {
store.dispatch(Actions.resetPassword());
},

View file

@ -17,6 +17,11 @@ export const Types = {
USER_LEFT: '[Server] User Left',
VIEW_LOGS: '[Server] View Logs',
CLEAR_LOGS: '[Server] Clear Logs',
REGISTRATION_REQUIRES_EMAIL: '[Server] Registration Requires Email',
REGISTRATION_FAILED: '[Server] Registration Failed',
REGISTRATION_EMAIL_ERROR: '[Server] Registration Email Error',
REGISTRATION_PASSWORD_ERROR: '[Server] Registration Password Error',
REGISTRATION_USERNAME_ERROR: '[Server] Registration Username Error',
RESET_PASSWORD_REQUESTED: '[Server] Reset Password Requested',
RESET_PASSWORD_FAILED: '[Server] Reset Password Failed',
RESET_PASSWORD_CHALLENGE: '[Server] Reset Password Challenge',

View file

@ -20,6 +20,8 @@ export interface WebSocketConnectOptions {
hashedPassword?: string;
newPassword?: string;
email?: string;
realName?: string;
country?: string;
autojoinrooms?: boolean;
keepalive?: number;
clientid?: string;

View file

@ -38,6 +38,8 @@ export class WebClient {
hashedPassword: '',
newPassword: '',
email: '',
realName: '',
country: '',
clientid: null,
reason: null,
autojoinrooms: true,

View file

@ -299,39 +299,300 @@ describe('SessionCommands', () => {
sendSessionCommandSpy.mockImplementation((_, callback) => callback(response));
})
it('should login user if registration accepted without email verification', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'accountAwaitingActivation').mockImplementation(() => {});
describe('RespRegistrationAccepted', () => {
it('should call SessionCommands.login()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
SessionCommands.register();
SessionCommands.register();
expect(SessionCommands.login).toHaveBeenCalled();
expect(SessionCommands.login).toHaveBeenCalled();
expect(SessionPersistence.accountAwaitingActivation).not.toHaveBeenCalled();
})
});
it('should prompt user if registration accepted with email verification', () => {
describe('RespRegistrationAcceptedNeedsActivation', () => {
const RespRegistrationAcceptedNeedsActivation = 'RespRegistrationAcceptedNeedsActivation';
response.responseCode = RespRegistrationAcceptedNeedsActivation;
webClient.protobuf.controller.Response.ResponseCode.RespRegistrationAcceptedNeedsActivation =
RespRegistrationAcceptedNeedsActivation;
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'accountAwaitingActivation').mockImplementation(() => {});
beforeEach(() => {
response.responseCode = RespRegistrationAcceptedNeedsActivation;
webClient.protobuf.controller.Response.ResponseCode.RespRegistrationAcceptedNeedsActivation =
RespRegistrationAcceptedNeedsActivation;
});
SessionCommands.register();
it('should call SessionPersistence.accountAwaitingActivation()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'accountAwaitingActivation').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.accountAwaitingActivation).toHaveBeenCalled();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.accountAwaitingActivation).toHaveBeenCalled();
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
it('should disconnect user if registration fails due to registration being disabled', () => {
describe('RespUserAlreadyExists', () => {
const RespUserAlreadyExists = 'RespUserAlreadyExists';
beforeEach(() => {
response.responseCode = RespUserAlreadyExists;
webClient.protobuf.controller.Response.ResponseCode.RespUserAlreadyExists =
RespUserAlreadyExists;
});
it('should call SessionPersistence.registrationUserNameError()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationUserNameError').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationUserNameError).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespUsernameInvalid', () => {
const RespUsernameInvalid = 'RespUsernameInvalid';
beforeEach(() => {
response.responseCode = RespUsernameInvalid;
webClient.protobuf.controller.Response.ResponseCode.RespUsernameInvalid =
RespUsernameInvalid;
});
it('should call SessionPersistence.registrationUserNameError()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationUserNameError').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationUserNameError).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespPasswordTooShort', () => {
const RespPasswordTooShort = 'RespPasswordTooShort';
beforeEach(() => {
response.responseCode = RespPasswordTooShort;
webClient.protobuf.controller.Response.ResponseCode.RespPasswordTooShort =
RespPasswordTooShort;
});
it('should call SessionPersistence.registrationPasswordError()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationPasswordError').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationPasswordError).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespEmailRequiredToRegister', () => {
const RespEmailRequiredToRegister = 'RespEmailRequiredToRegister';
beforeEach(() => {
response.responseCode = RespEmailRequiredToRegister;
webClient.protobuf.controller.Response.ResponseCode.RespEmailRequiredToRegister =
RespEmailRequiredToRegister;
});
it('should call SessionPersistence.registrationRequiresEmail()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationRequiresEmail').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationRequiresEmail).toHaveBeenCalled();
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespEmailBlackListed', () => {
const RespEmailBlackListed = 'RespEmailBlackListed';
beforeEach(() => {
response.responseCode = RespEmailBlackListed;
webClient.protobuf.controller.Response.ResponseCode.RespEmailBlackListed =
RespEmailBlackListed;
});
it('should call SessionPersistence.registrationEmailError()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationEmailError').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationEmailError).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespTooManyRequests', () => {
const RespTooManyRequests = 'RespTooManyRequests';
beforeEach(() => {
response.responseCode = RespTooManyRequests;
webClient.protobuf.controller.Response.ResponseCode.RespTooManyRequests =
RespTooManyRequests;
});
it('should call SessionPersistence.registrationEmailError()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationEmailError').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationEmailError).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespRegistrationDisabled', () => {
const RespRegistrationDisabled = 'RespRegistrationDisabled';
response.responseCode = RespRegistrationDisabled;
webClient.protobuf.controller.Response.ResponseCode.RespRegistrationDisabled = RespRegistrationDisabled;
SessionCommands.register();
beforeEach(() => {
response.responseCode = RespRegistrationDisabled;
webClient.protobuf.controller.Response.ResponseCode.RespRegistrationDisabled =
RespRegistrationDisabled;
});
expect(SessionCommands.updateStatus).toHaveBeenCalledWith(StatusEnum.DISCONNECTED, expect.any(String));
it('should call SessionPersistence.registrationFailed()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationFailed').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationFailed).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespUserIsBanned', () => {
const RespUserIsBanned = 'RespUserIsBanned';
beforeEach(() => {
response.responseCode = RespUserIsBanned;
webClient.protobuf.controller.Response.ResponseCode.RespUserIsBanned =
RespUserIsBanned;
});
it('should call SessionPersistence.registrationFailed()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationFailed').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationFailed).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('RespRegistrationFailed', () => {
const RespRegistrationFailed = 'RespRegistrationFailed';
beforeEach(() => {
response.responseCode = RespRegistrationFailed;
webClient.protobuf.controller.Response.ResponseCode.RespRegistrationFailed =
RespRegistrationFailed;
});
it('should call SessionPersistence.registrationFailed()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationFailed').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationFailed).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
describe('UnknownFailureReason', () => {
const UnknownFailureReason = 'UnknownFailureReason';
beforeEach(() => {
response.responseCode = UnknownFailureReason;
webClient.protobuf.controller.Response.ResponseCode.UnknownFailureReason =
UnknownFailureReason;
});
it('should call SessionPersistence.registrationFailed()', () => {
jest.spyOn(SessionCommands, 'login').mockImplementation(() => {});
jest.spyOn(SessionPersistence, 'registrationFailed').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.login).not.toHaveBeenCalled();
expect(SessionPersistence.registrationFailed).toHaveBeenCalledWith(expect.any(String));
});
it('should disconnect', () => {
jest.spyOn(SessionCommands, 'disconnect').mockImplementation(() => {});
SessionCommands.register();
expect(SessionCommands.disconnect).toHaveBeenCalled();
});
});
});
});

View file

@ -179,48 +179,41 @@ export class SessionCommands {
return;
}
let error;
switch (raw.responseCode) {
case webClient.protobuf.controller.Response.ResponseCode.RespRegistrationAcceptedNeedsActivation:
SessionPersistence.accountAwaitingActivation();
break;
case webClient.protobuf.controller.Response.ResponseCode.RespRegistrationDisabled:
error = 'Registration is currently disabled';
break;
case webClient.protobuf.controller.Response.ResponseCode.RespUserAlreadyExists:
error = 'There is already an existing user with this username';
break;
case webClient.protobuf.controller.Response.ResponseCode.RespEmailRequiredToRegister:
error = 'A valid email address is required to register';
break;
case webClient.protobuf.controller.Response.ResponseCode.RespEmailBlackListed:
error = 'The email address provider used has been blocked from use';
break;
case webClient.protobuf.controller.Response.ResponseCode.RespTooManyRequests:
error = 'This email address already has the maximum number of accounts you can register';
break;
case webClient.protobuf.controller.Response.ResponseCode.RespPasswordTooShort:
error = 'Your password was too short';
break;
case webClient.protobuf.controller.Response.ResponseCode.RespUserIsBanned:
error = NormalizeService.normalizeBannedUserError(raw.reasonStr, raw.endTime);
SessionPersistence.registrationUserNameError('Username is taken');
break;
case webClient.protobuf.controller.Response.ResponseCode.RespUsernameInvalid:
console.error('ResponseCode.RespUsernameInvalid', raw.reasonStr);
error = 'Invalid username';
SessionPersistence.registrationUserNameError('Invalid username');
break;
case webClient.protobuf.controller.Response.ResponseCode.RespPasswordTooShort:
SessionPersistence.registrationPasswordError('Your password was too short');
break;
case webClient.protobuf.controller.Response.ResponseCode.RespEmailRequiredToRegister:
SessionPersistence.registrationRequiresEmail();
break;
case webClient.protobuf.controller.Response.ResponseCode.RespEmailBlackListed:
SessionPersistence.registrationEmailError('This email provider has been blocked');
break;
case webClient.protobuf.controller.Response.ResponseCode.RespTooManyRequests:
SessionPersistence.registrationEmailError('Max accounts reached for this email');
break;
case webClient.protobuf.controller.Response.ResponseCode.RespRegistrationDisabled:
SessionPersistence.registrationFailed('Registration is currently disabled');
break;
case webClient.protobuf.controller.Response.ResponseCode.RespUserIsBanned:
SessionPersistence.registrationFailed(NormalizeService.normalizeBannedUserError(raw.reasonStr, raw.endTime));
break;
case webClient.protobuf.controller.Response.ResponseCode.RespRegistrationFailed:
default:
console.error('ResponseCode Type', raw.responseCode);
error = 'Registration failed due to a server issue';
SessionPersistence.registrationFailed('Registration failed due to a server issue');
break;
}
if (error) {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, `Registration Failed: ${error}`);
}
SessionCommands.disconnect();
});
};
@ -272,14 +265,14 @@ export class SessionCommands {
const resp = raw['.Response_ForgotPasswordRequest.ext'];
if (resp.challengeEmail) {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, 'Requesting MFA information');
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPasswordChallenge();
} else {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, 'Password reset in progress');
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPassword();
}
} else {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, 'Password reset failed, please try again');
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPasswordFailed();
}
@ -305,10 +298,10 @@ export class SessionCommands {
webClient.protobuf.sendSessionCommand(sc, raw => {
if (raw.responseCode === webClient.protobuf.controller.Response.ResponseCode.RespOk) {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, 'Password reset in progress');
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPassword();
} else {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, 'Password reset failed, please try again');
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPasswordFailed();
}
@ -335,10 +328,10 @@ export class SessionCommands {
webClient.protobuf.sendSessionCommand(sc, raw => {
if (raw.responseCode === webClient.protobuf.controller.Response.ResponseCode.RespOk) {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, 'Password successfully updated');
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPasswordSuccess();
} else {
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, 'Password update failed, please try again');
SessionCommands.updateStatus(StatusEnum.DISCONNECTED, null);
SessionPersistence.resetPasswordFailed();
}

View file

@ -85,6 +85,26 @@ export class SessionPersistence {
console.log('Account activation failed, show an action here');
}
static registrationRequiresEmail() {
ServerDispatch.registrationRequiresEmail();
}
static registrationFailed(error: string) {
ServerDispatch.registrationFailed(error);
}
static registrationEmailError(error: string) {
ServerDispatch.registrationEmailError(error);
}
static registrationPasswordError(error: string) {
ServerDispatch.registrationPasswordError(error);
}
static registrationUserNameError(error: string) {
ServerDispatch.registrationUserNameError(error);
}
static resetPasswordChallenge() {
ServerDispatch.resetPasswordChallenge();
}