NodeJS -Паспорт JS Предоставление определенного пароля - PullRequest
1 голос
/ 14 февраля 2020

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

 const mongoose = require('mongoose');
    const UserSchema = mongoose.Schema({
        password:{
            type: String,
            required: true
          }
    });
    const User = module.exports = mongoose.model('User', UserSchema);

В командной строке я создал коллекцию пользователей и вставил пароль: 'sifre'

Это мой пароль. js:

const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
const config = require('../config/database');
const bcrypt = require('bcryptjs');

module.exports = function(passport){
  // Local Strategy
  passport.use(new LocalStrategy(function(password){

    let query = {password:password};
    User.findOne(query, function(err, user){
      if(err) throw err;
      if(!user){
        return done(null, false, {message: 'No user found'});
      }


  /*Also I have tried:
    // Match Username
    let query = {username:username};
    User.findOne(query, function(err, user){
      if(err) throw err;
      if(!user){
        return done(null, false, {message: 'No user found'});
      } */


    /* to understand if it is about user name. Even I added username to models, db.collections 
and other code pages but I couldnt solve. Because again
 I couldnt reflect the models to db, I think.*/

      // Match Password
      bcrypt.compare(password, user.password, function(err, isMatch){
        if(err) throw err;
        if(isMatch){
          return done(null, user);
        } else {
          return done(null, false, {message: 'Wrong password'});
        }
      });
    });
  }));

  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });

  });
}

Также это мой пользователь. js:

    const express = require("express");
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');

let User = require('../models/user');

// Register Form
router.get('/login', function(req, res){
    const password = req.body.password;
    req.checkBody('password', 'Password is required').notEmpty();

    let errors = req.validationErrors();

    res.render('login');
  });

  router.post('/login', function(req, res, next){
    passport.authenticate('local', {
      successRedirect:'/',
      failureRedirect:'/users/login',
      failureFlash: true
    })(req, res, next);
  });

  // logout
  router.get('/logout', function(req, res){
    req.logout();
    req.flash('success', 'You are logged out');
    res.redirect('/login');
  });

  module.exports = router; 

А также это моя командная строка

db.createCollection('users');
...
db.users.insert{(password:'123'});
...

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

Редактировать:

          bcrypt.compare(password, user.password, function(err, isMatch){
        console.log("asd");
        if(err) throw err;
        if(isMatch){
          return done(null, user);
        } else {
          return done(null, false, {message: 'Wrong password'});
        }
      });
    });
  }));

Эта часть не работает. (Которая находится в паспорте . js)

Также я не могу ввести модуль (пользователь. js) o мой mongodb.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...