Passed
Push — master ( 4762c7...2b838c )
by Guangyu
08:55
created

src/components/MyEMS/auth/ChangePasswordForm.js   A

Complexity

Total Complexity 4
Complexity/F 0

Size

Lines of Code 129
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 111
mnd 4
bc 4
fnc 0
dl 0
loc 129
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import React, { useEffect, useState } from 'react';
2
import PropTypes from 'prop-types';
3
import { toast } from 'react-toastify';
4
import { Button, 
5
  Card, 
6
  CardBody, 
7
  Form,
8
  Spinner } from 'reactstrap';
9
import FalconCardHeader from '../../common/FalconCardHeader';
10
import FormGroupInput from '../../common/FormGroupInput';
11
import { getCookieValue, createCookie } from '../../../helpers/utils';
12
import withRedirect from '../../../hoc/withRedirect';
13
import { withTranslation } from 'react-i18next';
14
import { APIBaseURL } from '../../../config';
15
16
17
const ChangePasswordForm = ({ setRedirect, setRedirectUrl, layout, t }) => {
18
  useEffect(() => {
19
    let is_logged_in = getCookieValue('is_logged_in');
20
    let user_name = getCookieValue('user_name');
21
    let user_display_name = getCookieValue('user_display_name');
22
    let user_uuid = getCookieValue('user_uuid');
23
    let token = getCookieValue('token');
24
    if (is_logged_in === null || !is_logged_in) {
25
      setRedirectUrl(`/authentication/basic/login`);
26
      setRedirect(true);
27
    } else {
28
      //update expires time of cookies
29
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
30
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
31
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
32
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
33
      createCookie('token', token, 1000 * 60 * 60 * 8);
34
    }
35
  });
36
  const [oldPassword, setOldPassword] = useState('');
37
  const [newPassword, setNewPassword] = useState('');
38
  const [confirmPassword, setConfirmPassword] = useState('');
39
  const [isDisabled, setIsDisabled] = useState(true);
40
41
  useEffect(() => {
42
    if (oldPassword === '' || newPassword === '' || confirmPassword === '') return setIsDisabled(true);
43
44
    setIsDisabled(newPassword !== confirmPassword);
45
  }, [oldPassword, newPassword, confirmPassword]);
46
47
  const handleSubmit = e => {
48
    e.preventDefault();
49
    let isResponseOK = false;
50
    fetch(APIBaseURL + '/users/changepassword', {
51
      method: 'PUT',
52
      body: JSON.stringify({
53
        "data": {
54
          "old_password": oldPassword, "new_password": newPassword
55
        }
56
      }),
57
      headers: {
58
        "Content-Type": "application/json",
59
        "User-UUID": getCookieValue('user_uuid'),
60
        "Token": getCookieValue('token')
61
      }
62
    }).then(response => {
63
      console.log(response);
64
      if (response.ok) {
65
        isResponseOK = true;
66
      }
67
      return response.json();
68
    }).then(json => {
69
      console.log(isResponseOK);
70
      if (isResponseOK) {
71
        toast.success(t('Password has been changed!'));
72
        setRedirect(true);
73
      } else {
74
        toast.error(json.description)
75
      }
76
    }).catch(err => {
77
      console.log(err);
78
    });
79
  };
80
81
  useEffect(() => {
82
    setRedirectUrl(`/`);
83
  }, [setRedirectUrl, layout]);
84
85
  return (
86
    <Card className="mb-3">
87
      <FalconCardHeader title={t('Change Password')} light={false} />
88
      <CardBody className="bg-light">
89
        <Form onSubmit={handleSubmit}>
90
          <FormGroupInput
91
            id="old-password"
92
            label={t('Old Password')}
93
            value={oldPassword}
94
            onChange={({ target }) => setOldPassword(target.value)}
95
            type="password"
96
          />
97
          <FormGroupInput
98
            id="new-password"
99
            label={t('New Password')}
100
            value={newPassword}
101
            onChange={({ target }) => setNewPassword(target.value)}
102
            type="password"
103
          />
104
          <FormGroupInput
105
            id="confirm-password"
106
            label={t('Confirm Password')}
107
            value={confirmPassword}
108
            onChange={({ target }) => setConfirmPassword(target.value)}
109
            type="password"
110
          />
111
          <Button color="primary" block disabled={isDisabled}>
112
            {t('Update Password')}
113
          </Button>
114
        </Form>
115
      </CardBody>
116
    </Card>
117
  );
118
};
119
120
ChangePasswordForm.propTypes = {
121
  setRedirect: PropTypes.func.isRequired,
122
  setRedirectUrl: PropTypes.func.isRequired,
123
  layout: PropTypes.string
124
};
125
126
ChangePasswordForm.defaultProps = { layout: 'basic' };
127
128
export default withTranslation()(withRedirect(ChangePasswordForm));
129