• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 914712491

pending completion
914712491

Pull #3798

gitlab-ci

mzedel
refac: refactored signup page to make better use of form capabilities

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3798: MEN-3530 - refactored forms

4359 of 6322 branches covered (68.95%)

92 of 99 new or added lines in 11 files covered. (92.93%)

1715 existing lines in 159 files now uncovered.

8203 of 9941 relevant lines covered (82.52%)

150.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.62
/src/js/components/common/forms/passwordinput.js
1
// Copyright 2016 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useState } from 'react';
15
import { Controller, useFormContext, useWatch } from 'react-hook-form';
16

17
import { CheckCircle as CheckIcon, Visibility as VisibilityIcon, VisibilityOff as VisibilityOffIcon } from '@mui/icons-material';
18
import { Button, FormControl, FormHelperText, IconButton, Input, InputAdornment, InputLabel } from '@mui/material';
19

20
import copy from 'copy-to-clipboard';
21
import generator from 'generate-password';
22

23
import { TIMEOUTS } from '../../../constants/appConstants';
24
import { toggle } from '../../../helpers';
25
import { runValidations } from './form';
26

27
const PasswordGenerateButtons = ({ clearPass, edit, generatePass }) => (
14✔
28
  <div className="pass-buttons">
23✔
29
    <Button color="primary" onClick={generatePass}>
30
      Generate
31
    </Button>
32
    {edit ? <Button onClick={clearPass}>Cancel</Button> : null}
23!
33
  </div>
34
);
35

36
const SCORE_THRESHOLD = 3;
14✔
37

38
const PasswordGenerationControls = ({ score, feedback }) => (
14✔
39
  <>
365✔
40
    <div className="help-text" id="pass-strength">
41
      Strength: <meter max={4} min={0} value={score} high={3.9} optimum={4} low={2.5} />
42
      {score > SCORE_THRESHOLD ? <CheckIcon className="fadeIn green" style={{ height: 18, marginTop: -3, marginBottom: -3 }} /> : null}
365✔
43
    </div>
44
    {!!feedback.length && (
473✔
45
      <p className="help-text">
46
        {feedback.map((message, index) => (
47
          <React.Fragment key={`feedback-${index}`}>
114✔
48
            <span>{message}</span>
49
            <br />
50
          </React.Fragment>
51
        ))}
52
      </p>
53
    )}
54
  </>
55
);
56

57
export const PasswordInput = ({
14✔
58
  autocomplete,
59
  className,
60
  control,
61
  create,
62
  defaultValue,
63
  disabled,
64
  edit,
65
  generate,
66
  id,
67
  InputLabelProps = {},
936✔
68
  label,
69
  onClear,
70
  placeholder,
71
  required,
72
  validations = ''
285✔
73
}) => {
74
  const [score, setScore] = useState('');
937✔
75
  const [visible, setVisible] = useState(false);
937✔
76
  const [copied, setCopied] = useState(false);
937✔
77
  const [feedback, setFeedback] = useState([]);
937✔
78
  const [confirmationId] = useState(id.includes('current') ? '' : ['password', 'password_confirmation'].find(thing => thing !== id));
1,619✔
79
  const {
80
    clearErrors,
81
    formState: { errors },
82
    setError,
83
    setValue,
84
    trigger
85
  } = useFormContext();
937✔
86
  const confirmation = useWatch({ name: confirmationId });
937✔
87
  const errorKey = `${id}-error`;
937✔
88

89
  const clearPassClick = () => {
937✔
NEW
90
    setValue(id, '');
×
NEW
91
    onClear();
×
NEW
92
    setCopied(false);
×
93
  };
94

95
  const generatePassClick = () => {
937✔
96
    const password = generator.generate({ length: 16, numbers: true });
4✔
97
    setValue(id, password);
4✔
98
    setValue(`${id}_confirmation`, password);
4✔
99
    copy(password);
4✔
100
    setCopied(true);
4✔
101
    setVisible(true);
4✔
102
    setTimeout(() => setCopied(false), TIMEOUTS.fiveSeconds);
4✔
103
    trigger();
4✔
104
  };
105

106
  const validate = async (value = '') => {
937✔
107
    let { isValid, errortext } = runValidations({ id, required, validations, value });
254✔
108
    if (confirmation && value !== confirmation) {
254✔
109
      isValid = false;
60✔
110
      errortext = 'The passwords you provided do not match, please check again.';
60✔
111
    }
112
    if (isValid) {
254✔
113
      clearErrors(errorKey);
180✔
114
    } else {
115
      setError(errorKey, { type: 'validate', message: errortext });
74✔
116
    }
117
    if (!create) {
254✔
118
      return isValid;
138✔
119
    }
120
    const { default: zxcvbn } = await import(/* webpackChunkName: "zxcvbn" */ 'zxcvbn');
116✔
121
    const strength = zxcvbn(value);
116✔
122
    const score = strength.score;
116✔
123
    setFeedback(strength.feedback.suggestions || []);
116!
124
    setScore(score);
116✔
125
    return score > SCORE_THRESHOLD && isValid;
116✔
126
  };
127

128
  return (
937✔
129
    <div className={className}>
130
      <div className="password-wrapper">
131
        <Controller
132
          name={id}
133
          control={control}
134
          rules={{ required, validate }}
135
          render={({ field: { value, onChange, onBlur, ref }, fieldState: { error } }) => (
136
            <FormControl className={required ? 'required' : ''} error={Boolean(error?.message || errors[errorKey])} style={{ width: 400 }}>
1,075✔
137
              <InputLabel htmlFor={id} {...InputLabelProps}>
138
                {label}
139
              </InputLabel>
140
              <Input
141
                autoComplete={autocomplete}
142
                id={id}
143
                name={id}
144
                type={visible ? 'text' : 'password'}
1,075✔
145
                defaultValue={defaultValue}
146
                placeholder={placeholder}
147
                value={value ?? ''}
1,384✔
148
                disabled={disabled}
149
                inputRef={ref}
150
                required={required}
151
                onChange={({ target: { value } }) => {
152
                  setValue(id, value);
161✔
153
                  onChange(value);
161✔
154
                }}
155
                onBlur={onBlur}
156
                endAdornment={
157
                  <InputAdornment position="end">
NEW
158
                    <IconButton onClick={() => setVisible(toggle)} size="large">
×
159
                      {visible ? <VisibilityIcon /> : <VisibilityOffIcon />}
1,075✔
160
                    </IconButton>
161
                  </InputAdornment>
162
                }
163
              />
164
              <FormHelperText>{(errors[errorKey] || error)?.message}</FormHelperText>
1,988✔
165
            </FormControl>
166
          )}
167
        />
168
        {generate && !required && <PasswordGenerateButtons clearPass={clearPassClick} edit={edit} generatePass={generatePassClick} />}
961✔
169
      </div>
170
      {copied ? <div className="green fadeIn margin-bottom-small">Copied to clipboard</div> : null}
937✔
171
      {create && (
1,387✔
172
        <>
173
          <PasswordGenerationControls feedback={feedback} score={score} />
174
          {generate && required && <PasswordGenerateButtons clearPass={clearPassClick} edit={edit} generatePass={generatePassClick} />}
495✔
175
        </>
176
      )}
177
    </div>
178
  );
179
};
180

181
export default PasswordInput;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc