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

mendersoftware / mender-server / 1593965839

18 Dec 2024 10:58AM UTC coverage: 73.514% (+0.7%) from 72.829%
1593965839

Pull #253

gitlab-ci

mineralsfree
chore(gui): aligned tests with edit billing profile

Ticket: MEN-7466
Changelog: None

Signed-off-by: Mikita Pilinka <mikita.pilinka@northern.tech>
Pull Request #253: MEN-7466-feat: updated billing section in My Organization settings

4257 of 6185 branches covered (68.83%)

Branch coverage included in aggregate %.

53 of 87 new or added lines in 11 files covered. (60.92%)

43 existing lines in 11 files now uncovered.

40083 of 54130 relevant lines covered (74.05%)

22.98 hits per line

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

94.78
/frontend/src/js/common-ui/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, { useEffect, useRef, 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 { TIMEOUTS } from '@northern.tech/store/constants';
21
import { toggle } from '@northern.tech/utils/helpers';
22
import copy from 'copy-to-clipboard';
23
import generator from 'generate-password';
24

25
import { runValidations } from './form';
26

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

36
const SCORE_THRESHOLD = 3;
15✔
37

38
const PasswordGenerationControls = ({ score, feedback }) => (
15✔
39
  <>
450✔
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}
450✔
43
    </div>
44
    {!!feedback.length && (
566✔
45
      <p className="help-text">
46
        {feedback.map((message, index) => (
47
          <React.Fragment key={`feedback-${index}`}>
124✔
48
            <span>{message}</span>
49
            <br />
50
          </React.Fragment>
51
        ))}
52
      </p>
53
    )}
54
  </>
55
);
56

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

92
  useEffect(() => {
734✔
93
    if (confirmationId === 'password' && !message) {
52✔
94
      trigger(confirmationId);
9✔
95
    }
96
  }, [confirmationId, message, trigger]);
97

98
  useEffect(() => {
734✔
99
    return () => {
733✔
100
      clearTimeout(timer.current);
733✔
101
    };
102
  });
103

104
  const clearPassClick = () => {
734✔
105
    setValue(id, '');
×
106
    onClear();
×
107
    setCopied(false);
×
108
  };
109

110
  const generatePassClick = () => {
734✔
111
    const password = generator.generate({ length: 16, numbers: true });
6✔
112
    setValue(id, password);
6✔
113
    const form = getValues();
6✔
114
    if (form.hasOwnProperty(`${id}_confirmation`)) {
6✔
115
      setValue(`${id}_confirmation`, password);
1✔
116
    }
117
    copy(password);
6✔
118
    setCopied(true);
6✔
119
    setVisible(true);
6✔
120
    timer.current = setTimeout(() => setCopied(false), TIMEOUTS.fiveSeconds);
6✔
121
    trigger();
6✔
122
  };
123

124
  const validate = async (value = '') => {
734✔
125
    let { isValid, errortext } = runValidations({ id, required, validations, value });
295✔
126
    if (confirmation && value !== confirmation) {
295✔
127
      isValid = false;
60✔
128
      errortext = 'The passwords you provided do not match, please check again.';
60✔
129
    }
130
    if (isValid) {
295✔
131
      clearErrors(errorKey);
207✔
132
    } else {
133
      setError(errorKey, { type: 'validate', message: errortext });
88✔
134
    }
135
    if (!create || (!required && !value)) {
295✔
136
      return isValid;
114✔
137
    }
138
    const { default: zxcvbn } = await import(/* webpackChunkName: "zxcvbn" */ 'zxcvbn');
181✔
139
    const strength = zxcvbn(value);
181✔
140
    const score = strength.score;
181✔
141
    setFeedback(strength.feedback.suggestions || []);
181!
142
    setScore(score);
181✔
143
    return score > SCORE_THRESHOLD && isValid;
181✔
144
  };
145

146
  return (
734✔
147
    <div className={className}>
148
      <div className="password-wrapper">
149
        <Controller
150
          name={id}
151
          control={control}
152
          rules={{ required, validate }}
153
          render={({ field: { value, onChange, onBlur, ref }, fieldState: { error } }) => (
154
            <FormControl className={required ? 'required' : ''} error={Boolean((error || errors[errorKey])?.message)} style={{ width: 400 }}>
853✔
155
              <InputLabel htmlFor={id} {...InputLabelProps}>
156
                {label}
157
              </InputLabel>
158
              <Input
159
                autoComplete={autocomplete}
160
                id={id}
161
                name={id}
162
                type={visible ? 'text' : 'password'}
853✔
163
                defaultValue={defaultValue}
164
                placeholder={placeholder}
165
                value={value ?? ''}
1,090✔
166
                disabled={disabled}
167
                inputRef={ref}
168
                required={required}
169
                onChange={({ target: { value } }) => {
170
                  setValue(id, value);
182✔
171
                  onChange(value);
182✔
172
                }}
173
                onBlur={onBlur}
174
                endAdornment={
175
                  <InputAdornment position="end">
UNCOV
176
                    <IconButton onClick={() => setVisible(toggle)} size="large">
×
177
                      {visible ? <VisibilityIcon /> : <VisibilityOffIcon />}
853✔
178
                    </IconButton>
179
                  </InputAdornment>
180
                }
181
              />
182
              <FormHelperText>{(errors[errorKey] || error)?.message}</FormHelperText>
1,483✔
183
            </FormControl>
184
          )}
185
        />
186
        {generate && !required && <PasswordGenerateButtons disabled={disabled} clearPass={clearPassClick} edit={edit} generatePass={generatePassClick} />}
1,128✔
187
      </div>
188
      {copied ? <div className="green fadeIn margin-bottom-small">Copied to clipboard</div> : null}
734✔
189
      {create && (
1,184✔
190
        <>
191
          <PasswordGenerationControls feedback={feedback} score={score} />
192
          {generate && required && <PasswordGenerateButtons disabled={disabled} clearPass={clearPassClick} edit={edit} generatePass={generatePassClick} />}
671✔
193
        </>
194
      )}
195
    </div>
196
  );
197
};
198

199
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