[Nodejs] Không chạy khi dùng Passport - Local để login User
Mấy bác giúp em với.
EM làm theo hướng dẫn dùng Passportjs nhưng bị lỗi không thực thi khi gán lệnh:
passport.use(new LocalStrategy(User.authenticate()));
Nếu không có lệnh trên thì em REGISTER User được, nhưng có thì nó đăng kí được nhưng không Redirect sang URL.
App.js
var express = require('express'),
mongoose = require('mongoose'),
passport = require('passport'),
bodyParser = require('body-parser'),
LocalStrategy = require('passport-local'),
passportLocalMongoose = require('passport-local-mongoose'),
User = require('./models/user');
User.createStrategy();
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/anhlaai1');
var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(require('express-session')({
secret: "Rusty is the best and cutest dog in my love.",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);
app.get('/', function(req, res){
res.render("Home");
});
app.get('/login', function(req, res){
res.render('login');
})
app.get('/secret', function(req, res){
res.send('This is SECRET PAGE');
})
app.get('/register', function(req, res){
res.render('register');
})
app.post('/register', function(req, res){
req.body.username
req.body.password
User.register(new User({username: req.body.username}), req.body.password, function(err, user){
if(err){
console.log(err);
res.redirect('/register');
}
passport.authenticate("local")(req, res, function(){
res.redirect('/secret');
});
});
});
app.post('/login', passport.authenticate("local", {
successRedirect: "/secret",
failureRedirect: "/login"
}), function(req, res){
});
app.listen(3000, function(){
console.log('Server Started!!!')
})
User.js:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var userSchema = new mongoose.Schema({
username: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", userSchema)
Khi nó quay vòng vòng 1 hồi lâu thì hiện Error (Trong khi User tạo MỚI)
{ [UserExistsError: A user with the given username is already registered]
name: ‘UserExistsError’,
message: ‘A user with the given username is already registered’ }
FIXED: (CLOSURES)
passport.serializeUser(User.serializeUser() );
passport.deserializeUser(User.deserializeUser() );