无法使用本地护照登录

时间:2019-07-17 13:49:12

标签: node.js express mongoose

我正在尝试在身份验证上使用本地护照,但是代码未按预期执行。我希望用户通过身份验证后重定向到我的主页

我没有产生任何结果就尝试了文档中的代码

const express =  require('express');
const mongoose = require('mongoose');
const passport =  require('passport');
const LocalStrategy = require('passport-local').Strategy;
const app = express();
app.use(passport.initialize());
app.use(passport.session());

app.set('view engine', 'ejs')
// app.use(passport.initialize());

passport.serializeUser((user, cb) =>{
    cb(null, user.id)
});

passport.deserializeUser((id, cb) =>{
    User.findById(id, (err, user) =>{
        if(err){ return cb(err)}
        cb(null, user);
    });
});

const Schema = mongoose.Schema ;


const UserSchema = new Schema({
    username: String,
    password: String,
});
const User = mongoose.model('User', UserSchema);

passport.use(new LocalStrategy( 
    (username, password, done) =>{
        UserAll.findOne({username: username}, function(err, user){
            if(err){return done}
            if(!user){return done(nul, false)}
            if(user.password != password){
                return done(null, false);
            }
            return done(null, user);

        });
    }
));


app.get('/' , (req, res) =>{
    res.send('the home page');

});


app.get('/login', (req, res) =>{
    res.render('login');

});

app.post('/login', passport.authenticate('local', {failureRedirect: '/login'}), (req, res) =>{
    res.redirect('/');
    // console.log(req.body);
});


mongoose.connect('mongodb://localhost/PassportLocalTest', {useNewUrlParser: true });
mongoose.connection.once('open', () =>{
    console.log('connected');

}).once('error', (error) =>{
    console.log('connection error ', error);
});


app.listen(3000, () =>{
    console.log('listening to port 3000');`enter code here`
});

本地护照策略在身份验证过程后无法重定向用户

0 个答案:

没有答案