accounts-frontend/packages/app/services/authFlow/PasswordState.ts

96 lines
2.5 KiB
TypeScript
Raw Normal View History

import logger from 'app/services/logger';
import { getCredentials } from 'app/components/auth/reducer';
import {
getActiveAccount,
getAvailableAccounts,
} from 'app/components/accounts/reducer';
2016-03-02 02:06:14 +05:30
import AbstractState from './AbstractState';
import ChooseAccountState from './ChooseAccountState';
2016-03-02 02:06:14 +05:30
import CompleteState from './CompleteState';
import ForgotPasswordState from './ForgotPasswordState';
import LoginState from './LoginState';
2017-08-23 00:09:08 +05:30
import MfaState from './MfaState';
2019-12-07 16:58:52 +05:30
import { AuthContext } from './AuthFlow';
2016-03-02 02:06:14 +05:30
export default class PasswordState extends AbstractState {
enter(context: AuthContext) {
2019-12-29 21:56:51 +05:30
const { login, isTotpRequired } = getCredentials(context.getState());
2016-03-02 02:06:14 +05:30
2019-12-29 21:56:51 +05:30
if (isTotpRequired) {
context.setState(new MfaState());
} else if (login) {
context.navigate('/password');
} else {
context.setState(new CompleteState());
2016-03-02 02:06:14 +05:30
}
}
2016-03-02 02:06:14 +05:30
resolve(
context: AuthContext,
{
password,
rememberMe,
}: {
2019-12-07 16:58:52 +05:30
password: string;
rememberMe: boolean;
},
) {
const { login, returnUrl } = getCredentials(context.getState());
2016-03-02 02:06:14 +05:30
return context
.run('login', {
password,
rememberMe,
login,
})
.then(() => {
const { isTotpRequired } = getCredentials(context.getState());
if (isTotpRequired) {
return context.setState(new MfaState());
}
if (returnUrl) {
context.navigate(returnUrl);
return;
}
2016-03-02 02:06:14 +05:30
return context.setState(new CompleteState());
})
.catch((err = {}) => err.errors || logger.warn('Error logging in', err));
}
2016-03-02 02:06:14 +05:30
reject(context: AuthContext) {
context.setState(new ForgotPasswordState());
}
goBack(context: AuthContext) {
const state = context.getState();
const { isRelogin } = getCredentials(state);
if (isRelogin) {
const availableAccounts = getAvailableAccounts(state);
const accountToRemove = getActiveAccount(state);
if (availableAccounts.length === 1 || !accountToRemove) {
context.run('logout');
context.run('setLogin', null);
context.setState(new LoginState());
} else {
const accountToReplace = availableAccounts.find(
({ id }) => id !== accountToRemove.id,
);
context.run('activateAccount', accountToReplace);
context.run('removeAccount', accountToRemove);
context.setState(new ChooseAccountState());
}
} else {
context.run('setLogin', null);
context.setState(new LoginState());
2016-03-02 02:06:14 +05:30
}
}
2016-03-02 02:06:14 +05:30
}