Validation improve pattern for derived data

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski 2020-09-21 14:35:35 +01:00
parent 8ec7e7c714
commit ed0e188b4f
2 changed files with 34 additions and 34 deletions

View file

@ -40,11 +40,7 @@ interface IProps {
onValidate(result: IValidationResult);
}
interface IState {
complexity: zxcvbn.ZXCVBNResult;
}
class PassphraseField extends PureComponent<IProps, IState> {
class PassphraseField extends PureComponent<IProps> {
static defaultProps = {
label: _td("Password"),
labelEnterPassword: _td("Enter password"),
@ -52,14 +48,16 @@ class PassphraseField extends PureComponent<IProps, IState> {
labelAllowedButUnsafe: _td("Password is allowed, but unsafe"),
};
state = { complexity: null };
public readonly validate = withValidation<this>({
description: function() {
const complexity = this.state.complexity;
public readonly validate = withValidation<this, zxcvbn.ZXCVBNResult>({
description: function(complexity) {
const score = complexity ? complexity.score : 0;
return <progress className="mx_PassphraseField_progress" max={4} value={score} />;
},
deriveData: async ({ value }) => {
if (!value) return null;
const { scorePassword } = await import('../../../utils/PasswordScorer');
return scorePassword(value);
},
rules: [
{
key: "required",
@ -68,28 +66,24 @@ class PassphraseField extends PureComponent<IProps, IState> {
},
{
key: "complexity",
test: async function({ value }) {
test: async function({ value }, complexity) {
if (!value) {
return false;
}
const { scorePassword } = await import('../../../utils/PasswordScorer');
const complexity = scorePassword(value);
this.setState({ complexity });
const safe = complexity.score >= this.props.minScore;
const allowUnsafe = SdkConfig.get()["dangerously_allow_unsafe_and_insecure_passwords"];
return allowUnsafe || safe;
},
valid: function() {
valid: function(complexity) {
// Unsafe passwords that are valid are only possible through a
// configuration flag. We'll print some helper text to signal
// to the user that their password is allowed, but unsafe.
if (this.state.complexity.score >= this.props.minScore) {
if (complexity.score >= this.props.minScore) {
return _t(this.props.labelStrongPassword);
}
return _t(this.props.labelAllowedButUnsafe);
},
invalid: function() {
const complexity = this.state.complexity;
invalid: function(complexity) {
if (!complexity) {
return null;
}