Как иметь sh два пароля одновременно, используя bcyrpt? - PullRequest
0 голосов
/ 17 марта 2020

Я пытаюсь получить страницу входа с двумя паролями. Только для одного пароля код работает отлично, но когда я добавляю другой пароль, он выдает ошибку «Параллельная ошибка сохранения».

[0] (node:16516) UnhandledPromiseRejectionWarning: ParallelSaveError: Can't save() the same
doc multiple times in parallel. Document: 5e703180c90fbc40848fcfca

[0] (node:16516) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated 
either by throwing inside of an async function without a catch block, or by rejecting a promise which 
was not handled with .catch(). (rejection id: 2)

[0] (node:16516) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the Node.js process with a non- 
zero exit code.

Это мой пользователь. js скрипт:

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const config = require('config');
const jwt = require('jsonwebtoken');
const User = require('../../models/User');

router.post('/', (req, res,) => {
const { name, email, password1, password2 } = req.body;

if(!name || !email || !password1 || !password2) {
return res.status(400).json({ msg: 'Please enter all fields' });
}

User.findOne({ email })
.then(user => {
  if(user) return res.status(400).json({ msg: 'User already exists' });

  const newUser = new User({
    name,
    email,
    password1,
    password2
  });

  // Hash
  bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password1, salt , (err, hash) => {
      if(err) throw err;
      newUser.password1 = hash;
      newUser.save()
        .then(user => {
          jwt.sign(
            { id: user.id },
            config.get('jwtSecret'),
            { expiresIn: 3600 },
            (err, token) => {
              if(err) throw err;
              res.json({
                token,
                user: {
                  id: user.id,
                  name: user.name,
                  email: user.email
                }
              });
            }
          )
        });
     })
  })


  // Create salt & hash
  bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password2, salt, (err, hash) => {
      if(err) throw err;
      newUser.password2 = hash;
      newUser.save()
        .then(user => {
          jwt.sign(
            { id: user.id },
            config.get('jwtSecret'),
            { expiresIn: 3600 },
            (err, token) => {
              if(err) throw err;
              res.json({
                token,
                user: {
                  id: user.id,
                  name: user.name,
                  email: user.email
                }
              });
            }
          )
        });
     })
   })
 })
});

module.exports = router;

и следующий код для аутентификации. js

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const config = require('config');
const jwt = require('jsonwebtoken');
const auth = require('../../middleware/auth');


// User Model
const User = require('../../models/User');

router.post('/', (req, res) => {
const { email, password1, password2 } = req.body;

// for validation
if(!email || !password1 || !password2) {
return res.status(400).json({ msg: 'Please enter all fields' });
}

// Check if user exists
User.findOne({ email })
.then(user => {
  if(!user) return res.status(400).json({ msg: 'User Does not exist' });

  // Validation of password
  bcrypt.compare(password1, user.password1)
    .then(isMatch => {
      if(!isMatch) return res.status(400).json({ msg: 'Invalid credentials' });

      jwt.sign(
        { id: user.id },
        config.get('jwtSecret'),
        { expiresIn: 3600 },
        (err, token) => {
          if(err) throw err;
          res.json({
            token,
            user: {
              id: user.id,
              name: user.name,
              email: user.email
            }
          });
        }
      )
    })
  bcrypt.compare(password2, user.password2)
    .then(isMatch => {
      if(!isMatch) return res.status(400).json({ msg: 'Invalid credentials' });

      jwt.sign(
        { id: user.id },
        config.get('jwtSecret'),
        { expiresIn: 3600 },
        (err, token) => {
          if(err) throw err;
          res.json({
            token,
            user: {
              id: user.id,
              name: user.name,
              email: user.email
            }
          });
        }
      )
    })
 }) 
})

router.get('/user', auth, (req, res) => {
User.findById(req.user.id)
.select('-password1, -password2')
.then(user => res.json(user));
});

module.exports = router;

I я получаю только password2 в качестве хешированного пароля.

password1:"ddd"
password2:"$2a$10$PQhBiDtelKoRspAFn7BW0OuI0pnAyDl.DQSag6bBvYdlirBZM/oAq"

что мне нужно сделать, чтобы удалить эти ошибки?

Ответы [ 2 ]

0 голосов
/ 17 марта 2020

Я думаю, что лучше написать метод шифрования пароля в модели . js и экспортировать его с пользователем в маршрут. js или как там его имя улучшенный и чистый код, чтобы вы могли использовать свой метод столько, сколько вам нужно.

0 голосов
/ 17 марта 2020

Я получил ответ на вышеуказанную проблему ... просто нужно изменить следующую часть в пользователе. js. не нужно создавать ha sh дважды.

 bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password1, salt , async (err, hash) => {
      bcrypt.hash(newUser.password2, salt, async (err, hash) => {
      if(err) throw err;
      newUser.password1 = hash;
      newUser.password2 = hash;
      await newUser.save()
      ...
      ...

то же самое нужно сделать в аутентификации. js скрипт.

 bcrypt.compare(password1, user.password1)
  bcrypt.compare(password2, user.password2)
    .then(isMatch => {
      if(!isMatch) return res.status(400).json({ msg: 'Invalid credentials' 
   });
      jwt.sign(
        { id: user.id },
        ...
        ...
...