Изменить пароль редуктора в приложении реакции (ax ios + redux + jwt + bcrypt) - PullRequest
0 голосов
/ 05 февраля 2020

Я хочу сменить пароль, пока я в системе. Вот моя функция: authActions. js (без перехвата, потому что это будет реализовано, если что-то начнет работать)

// Change password
export const changePassword = (newPassword) => (dispatch, getState) => {
  // Headers
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  }

  axios.post(`/api/auth/user/changePassword/`, newPassword, tokenConfig(getState))
    .then(res => dispatch({
      type: CHANGE_PASSWORD,
      payload: res.data
    }))
}

// Setup config/headers and token
export const tokenConfig = getState => {
  // Get token from localstorage
  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      // "Accept": "application/json, multipart/form-data"
      "Content-type": "application/json"
    }
  }

  // If token, add to headers
  if (token) {
    config.headers['x-auth-token'] = token;
  }
  return config;
}

и authReducer . js:

...
const initialState = {
  token: localStorage.getItem('token'),
  isAuthenticated: false,
  user: null
};

export default function (state = initialState, action) {
  switch (action.type) {
...
case CHANGE_PASSWORD:
      return {
        ...state,
        token: null,
        user: action.payload,
        isAuthenticated: false,
        isLoading: false
      };
  default:
      return state;

  }
}

и router / api / auth. js

router.post('/user/changePassword/', (req, res) => {
  console.log(req.body);
  const { email, oldPassword, newPassword } = req.body
  // find if old password is valid
  User.findOne({ email })
    .then(user => {
      bcrypt.compare(oldPassword, user.password)
        .then(isMatch => {
          if (isMatch) {
            // change to new password
            user.password = newPassword
            user
              .save()
              .then(newUser => {
                res.status(200).send(newUser)
              })
              .catch(err => {
                const message = err.message
                res.status(500).json({
                  status: "change password failed",
                  msg: message
                })
              })
          } else {
            return res.status(401).send("Invalid old password")
          }
        })
    })
    .catch(err => {
      res.status(500).send(err)
    })
});

У меня есть console.log (req.body); в маршрутах просто чтобы проверить, работает ли что-нибудь, но это не работает (не дало мне никакого сообщения).

И компонент в конце (но это не источник проблемы):

import React, { useState, useEffect } from 'react';
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input,
  NavLink
} from 'reactstrap';
import { connect } from 'react-redux';
import { changePassword } from '../../actions/authActions';
import PropTypes from 'prop-types';

const ChangePassword = ({ auth }) => {

  const [modal, setModal] = useState(false);
  const [enterPassword, setEnterPassword] = useState({
    oldPassword: '',
    newPassword: ''
  });
  const [takeEmail, setTakeEmail] = useState(null);

  useEffect(() => {
    const createArray = () => {
      const { user } = auth;
      setTakeEmail({ email: user.email });
    };
    createArray();
  }, [auth.user]);

  const toggle = () => {
    setModal(!modal);
  };

  const onChange = e => {
    setEnterPassword({
      ...enterPassword,
      [e.target.name]: e.target.value
    });

  };

  const onSubmit = (event) => {
    event.preventDefault();
    const { email } = takeEmail;
    const { oldPassword, newPassword } = enterPassword;
    console.log(enterPassword);
    console.log(takeEmail);
    const newUser = {
      email,
      oldPassword,
      newPassword
    }


    // Add content via changePassword action
    changePassword(newUser);
    toggle();
  }


  return (
    <div>
      <NavLink onClick={toggle} href="#">
        Change Password
        </NavLink>

      <Modal
        isOpen={modal}
        toggle={toggle}
        className="open-modal"
      >
        <ModalHeader toggle={toggle}>Dodaj do listy ogłoszeń</ModalHeader>
        <ModalBody>
          <Form onSubmit={onSubmit}>
            <FormGroup>
              <Label for="oldPassword">Nagłówek</Label>
              <Input
                type="password"
                name="oldPassword"
                id="oldPassword"
                placeholder="Wprowadź stare hasło..."
                onChange={onChange}
              />

              <Label for="newPassword">Nagłówek</Label>
              <Input
                type="password"
                name="newPassword"
                id="newPassword"
                placeholder="Wprowadź stare hasło..."
                onChange={onChange}
              />
              <Button
                color="dark"
                style={{ marginTop: '2rem' }}
                block>
                Zmień hasło
                </Button>
            </FormGroup>
          </Form>
        </ModalBody>
      </Modal>
    </div>
  );
}


ChangePassword.propTypes = {
  isAuthenticated: PropTypes.bool,
  changePassword: PropTypes.func.isRequired
}

const mapStateToProps = state => ({
  auth: state.auth,
  isAuthenticated: state.auth.isAuthenticated
});

export default connect(mapStateToProps, { changePassword })(ChangePassword);
...