I am new to nodejs. I have been trying to create a simple login and register system using mongodb and express. I have created the entire app but with one error:
var express = require('express')
, passport = require('passport')
, util = require('util')
, LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
//var flash = require('connect-flash');
var monk = require('monk');
var db = monk('localhost:27017/loginsystem');
var collection = db.get('messagescollection');
function findById(id, fn) {
var collection = db.get('messagescollection');
collection.findOne({ _id: id }).on('success', function (doc) {
fn(null, doc);
});
}
function findByUsername(username, fn) {
collection.findOne({ username: username }).on('success', function(doc) {
return fn(null, doc);
});
return fn(null, null);
}
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(function(req,res,next){
req.db = db;
next();
});
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat'
hours
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
console.log("user",user);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
console.log(id,"id");
findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
}
));
app.use(express.static(__dirname + '/public'));
app.get('/account', ensureAuthenticated, function(req, res){
res.send(req.user);
});
app.get('/login', function(req, res){
res.redirect("/login.html") //redirect back to homepage
});
app.get('/register', function(req, res) {
res.redirect("/register.html") //redirect back to homepage
})
app.post('/login', passport.authenticate('local', { failureRedirect: '/login'}), function(req, res) {
console.log("success",req.user);
res.redirect('/account');
});
app.post('/register', function(req, res) {
console.log(req.body);
// Submit to the DB
collection.insert({
"username" : req.body.username,
"email" : req.body.email,
"password" : req.body.password
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
//res.redirect('/account');
}
});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.listen(9000);
function ensureAuthenticated(req, res, next) {
console.log("req.user",req.user,req.session);
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
}
When I register, the user is added to the database. And it is redirected to /login but when I login then I get this error:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/response.js:700:10)
at ServerResponse.res.location (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/response.js:814:8)
at ServerResponse.redirect (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/response.js:853:8)
at /home/mareebsiddiqui/SummerOfCode/loginsystem/app.js:130:7
at Layer.handle [as handle_request] (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/router/layer.js:82:5)
at next (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/router/route.js:110:13)
at complete (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/passport/lib/middleware/authenticate.js:243:13)
at /home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/passport/lib/middleware/authenticate.js:250:15
at pass (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/passport/lib/authenticator.js:427:14)
How could I resolve this issue? Thanks.
EDIT: I know that there are many questions with the same title but there problems are different. This error is caused by many different situations and my situation is different from others. I have a problem of redirects whereas other questions have problems of ending a response.
You should use return response.<method>. For example, return response.redirect().
Also, response.end() might be helpful.
Related
I am currently creating a small user authentication app using Node + Express + Passport. When the user logs in, they are rerouted automatically to the index page "/" and a session should be established with passports authentication. For some reason when trying to console.log(req.user), it is returning "undefined".
The authentication with passport seems to be working properly with the post route
app.post("/login", passport.authenticate("local", {
successRedirect: "/home",
failureRedirect: "/login"
}), (req, res) => {
})
But the session is not being established with the user model. I'd like to eventually store the userId in the session. Here is a look at my current set up with user model and passport implementation on the server file.
const mongoose = require("mongoose");
const passportLocalMongoose = require('passport-local-mongoose');
const userSchema = mongoose.Schema({
username: String,
email: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
const user = mongoose.model("User", userSchema);
module.exports = user;
-----------------------------------------------------------------------------------------
const express = require("express"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
session = require("express-session"),
User = require("./models/user"),
passport = require('passport'),
LocalStragety = require('passport-local'),
app = express();
mongoose.connect("mongodb://localhost/shopping_cart_app", { useNewUrlParser: true })
.then(console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/views'));
app.use(session({
secret: "secret",
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStragety(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.post("/login", passport.authenticate("local", {
successRedirect: "/home",
failureRedirect: "/login"
}), (req, res) => {
})
I've tried looking into Passports config a bit more but on the documentation provided, it states that once passport.authenticate runs, a session with the user is established. Any tips would be greatly appreciate.
Thanks
I know this may seem simple, but have you tried req.body.user?
The req.body contains the data submitted by the user. The documentation suggest that you use a body parser to populate the information because it's undefined by default. However, instead of using the app object I use express router without parsing.
const express = require("express");
const router = express.Router();
router.post("/login", passport.authenticate("local", {
successRedirect: "/home",
failureRedirect: "/login"
}), (req, res) => {
console.log(req.body.user);
})
for more information: req.body
Try this one, In my project, it is working.
LocalStrategy
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var admins = mongoose.model('admins');
var bCrypt = require('bcrypt-nodejs');
var flash = require('connect-flash');
var moment = require('moment');
// User
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(obj, done) {
console.log("deserializing " + obj);
done(null, obj);
});
passport.use('adminlogin',new LocalStrategy(
function(username, password, done) {
admins.findOne({ 'email' : username },
function(err, user) {
//console.log(username);
if (err)
return done(err);
if (!user){
//console.log('Username '+username+' does not Exist. Pleasr try again.');
return done(null, false, { message: 'Incorrect Username/Password. Please try again.' });
}
if (!isValidPasswordAdmin(user, password)){
//console.log('Invalid Password');
return done(null, false, { message: 'Incorrect Password. Please try again.' });
}
return done(null, user);
}
);
})
);
var isValidPassword = function(user, app_pin){
return bCrypt.compareSync(app_pin, user.app_pin);
}
var isValidPasswordAdmin = function(user, password){
return bCrypt.compareSync(password, user.password);
}
module.exports = passport;
Login Route
router.post('/login', function (req, res, next) {
admins.find({}, function (err, user) {
if (err) {
console.log('internal database error');
req.flash('error', 'Database Error');
res.redirect('/admins');
} else {
passport.authenticate('adminlogin', function (err, user, info) {
if (err) {
console.log(err);
req.flash('error', 'Database Error');
res.redirect('/admins');
} else if (!user) {
req.flash('error', info.message);
res.redirect('/admins');
} else {
req.logIn(user, function (err) {
if (err) {
req.flash('error', 'Database Error');
res.redirect('/admins');
} else {
res.redirect('/admins/home');
}
});
}
})(req, res, next);
}
});
});
I'm a hobbyist coder, and I can usually solve errors with lots of searches, but this one I can't get it right.
when I hit my logout route it throws an error: Cast to ObjectId failed for value "logout" at path "_id" for model "Spot"
I tried mongoose version 4.7.2, it's not working. I can't imagine why is it associating my logout route with the spot model at all.
my app.js
var express = require("express"),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
passportFacebook = require("passport-facebook").Strategy,
User = require("./models/user.js"),
Spot = require("./models/spot.js");
mongoose.connect("mongodb://localhost/biketrialspots", { useNewUrlParser: true });
var app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));
app.use(require("express-session")({
secret: "some secret",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});
passport.use(new passportFacebook({
clientID: "some id",
clientSecret: "some secret",
callbackURL: "somewebsite/auth/facebook/callback",
profileFields: ['id', 'displayName', 'picture.type(large)']
}, function(accessToken, refreshToken, profile, done) {
User.findOrCreate(profile, function(err, user) {
if (err)
{ return done(err); }
done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.get("/", function(req, res){
Spot.find({}, function(err, spots){
if(err){
console.log(err);
} else{
res.render("index", {spots:spots});
}
});
});
app.get("/new", ensureAuthenticated, function(req, res){
res.render("new");
});
app.post("/", function(req, res){
Spot.create(req.body.spot, function(err, result){
if(err){
console.log(err);
} else{
res.redirect("/");
}
});
});
app.get("/:id", function(req, res){
Spot.findById(req.params.id, function(err, spot){
if(err){
console.log(err);
} else{
res.render("spot", {spot: spot});
}
});
});
// Redirect the user to Facebook for authentication. When complete,
// Facebook will redirect the user back to the application at
// /auth/facebook/callback
app.get('/auth/facebook', passport.authenticate('facebook'));
// Facebook will redirect the user to this URL after approval. Finish the
// authentication process by attempting to obtain an access token. If
// access was granted, the user will be logged in. Otherwise,
// authentication has failed.
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/',
failureRedirect: '/login' }));
app.get("/logout", function(req, res){
req.user.logout();
res.redirect('/');
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
return res.redirect('/');
}
app.listen(process.env.PORT, process.env.IP, function(req, res){
console.log("APP HAS STARTED!!!!!");
});
user model
var mongoose = require("mongoose");
var userSchema = new mongoose.Schema({
facebookID:Number,
username:String,
photo:String
});
userSchema.statics.findOrCreate = function findOrCreate(profile, cb){
var userObj = new this();
this.findOne({facebookID : profile.id},function(err,result){
if(!result){
userObj.facebookID = profile.id;
userObj.username = profile.displayName;
userObj.photo = profile.photos[0].value;
userObj.save(cb);
} else{
cb(err,result);
}
});
};
module.exports = mongoose.model("User", userSchema);
Thank you
Because app.get("/:id", ...) is written before app.get("/logout", ...) in your code, I guess the request handler of /:id would be called when you get /logout. Then, req.params.id becomes "logout" and the error is thrown by Spot.findById().
How about trying to write app.get("/logout", ...) before app.get("/:id", ...)?
I am trying to use passport authentication with a local strategy but the authentication fails every time and doesn't move on to the local strategy.
I have added a couple console logs to see where the code is derailed but nothing at all is logged.
users.js(router)
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var multer=require('multer');
var passport=require('passport');
var LocalStrategy=require('passport-local').Strategy;
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register',{
'title':'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login',{
'title':'Login'
});
});
passport.use(new LocalStrategy(
function(username,password,done){
console.log('words');
User.getUserByUsername(username,function(err,user){
if (err) throw err;
if(!user){
console.log('Unknown user');
return done(null,false);
}
});
}
));
router.post('/login',passport.authenticate('local',{failureRedirect:'/users/register'}),function(req,res){
console.log('Authentication succesful');
req.flash('success','You are logged in');
res.redirect('/');
});
module.exports = router;
Did you set the session and added passport to the router? I don't know if setting the initialize and session method in two different spots will work.
This is how I made it work: All set in in a router
let express = require('express');
let session = require('express-session');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let router = express.Router();
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({username: username}, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
user.comparePassword(password, function (err, isMatch) {
if (err) { return done(err); }
if(!isMatch){
return done(null, false, { message: 'Incorrect password.' });
} else {
return done(null, user);
}
});
});
}
));
passport.serializeUser(function(user, done) {
done(null, {email: user.email, roles : user.roles});
});
passport.deserializeUser(function(session, done) {
User.findOne({email: session.email}, function(err, user) {
done(err, user);
});
});
router.use(session({ secret: 'my super secret',name: 'my-id', resave: false, saveUninitialized: false }));
router.use(passport.initialize());
router.use(passport.session());
Furthermore if this ever goes into production you need a different session handler than express-session like MongoStore or Redis
The routes
/* GET home page. */
router.get('/', require('connect-ensure-login').ensureLoggedIn('login'), function (req, res, next) {
if (req.user) {
res.render('index');
} else {
res.redirect('/login');
}
});
router.get('/login', function (req, res, next) {
res.render('login');
});
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}));
router.get('/logout', function (req, res) {
req.logout();
res.render('logout');
});
I'm a newbie in node.js and I'm trying to redirect all the routes after localhost:4000/ if it is not logged in. And it gives me error with "Too many redirects"...
my code that using app.get in app.js
app.get('*', loggedInCheck);
and below code is loggedInCheck function that I've written,
function loggedInCheck(req, res, next) {
if (req.isAuthenticated()){
res.redirect('/status');
}else{
console.log("Please Log in to access to this webpage");
res.redirect('/login');
}
}
However, it keeps giving me an error as "Too many redirects" and doesn't go through login page because it is not authenticated yet.
What is my problem here? and how can I fix this....?
Can anybody help me out here??
Just in case, I'll put my whole code from app.js
app.js
var io = require('socket.io');
var express = require('express');
var app = express();
var redis = require('redis');
var sys = require('util');
var fs = require('fs');
//Added for connecting login session
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//Connecting Database (MongoDB)
mongoose.connect("my private mongoDB address");
var db = mongoose.connection;
db.once("open",function () {
console.log("DB connected!");
});
db.on("error",function (err) {
console.log("DB ERROR :", err);
});
//Setting bcrypt for password.
var bcrypt = require("bcrypt-nodejs");
//Setting userSchema for MongoDB.
var userSchema = mongoose.Schema({
email: {type:String, required:true, unique:true},
password: {type:String, required:true},
createdAt: {type:Date, default:Date.now}
});
userSchema.pre("save", function (next){
var user = this;
if(!user.isModified("password")){
return next();
} else {
user.password = bcrypt.hashSync(user.password);
return next();
}
});
//setting bcrypt for password.
userSchema.methods.authenticate = function (password) {
var user = this;
return bcrypt.compareSync(password,user.password);
};
//Setting User as userSchema.
var User = mongoose.model('user',userSchema);
io = io.listen(server);
//Setting middleware for login format.
app.set("view engine", 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(flash());
app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
//Initializing passport.
passport.serializeUser(function(user, done) {
//console.log('serializeUser()', user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
//console.log('deserializeUser()', user);
User.findById(id, function(err, user) {
done(err, user);
});
});
var global_username = ''; //Global variable for username to put in the address
//Initializing passport-local strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
User.findOne({ 'email' : email }, function(err, user) {
if (err) return done(err);
if (!user){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'No user found.'));
}
if (!user.authenticate(password)){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'Password does not Match.'));
}
var email_address = req.body.email;
var username = email_address.substring(0, email_address.lastIndexOf("#"));
global_username = username;
return done(null, user);
});
}
)
);
//Check whether it is logged in or not.
//If it is not logged in(Session is out), it goes to login page
//If it is logged in(Session is still on), it goes directly to status.html
app.get('*', loggedInCheck);
app.get('/login', function (req,res) {
res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
});
//Accessing to MongoDB to check to login or not
app.post('/login',
function (req,res,next){
next();
}, passport.authenticate('local-login', {
successRedirect : '/status',
failureRedirect : '/login',
failureFlash : true
})
);
//Logging out
app.get('/logout', function(req, res) {
req.logout();
console.log("Logging out the account!");
res.redirect('/login');
});
//Creating new account
app.get('/users/new', function(req,res){
res.render('users/new', {
formData: req.flash('formData')[0],
emailError: req.flash('emailError')[0],
passwordError: req.flash('passwordError')[0]
}
);
});
//If creating an account is successed, then goes back to login page.
app.post('/users', checkUserRegValidation, function(req,res,next){
User.create(req.body.user, function (err,user) {
if(err) return res.json({success:false, message:err});
res.redirect('/login');
});
});
//Calling status.html
app.get('/status', isLoggedIn, function(req, res){
res.redirect('/status.html?channel=' + global_username);
});
//Calling Topology_view html
app.get('/topology', isLoggedIn, function(req, res){
console.log("Accessing to topology_view");
res.redirect('topology.html?channel=' + global_username);
});
//functions
//Check whether session is still on or not.
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()){
console.log("Authenticated");
return next();
}else{
console.log("Unauthorized Attempt");
res.redirect('/login');
}
}
//Initial checking whether session is on or not.
function loggedInCheck(req, res, next) {
if (req.isAuthenticated()){
res.redirect('/status');
}else{
console.log("Please Log in to access to this webpage");
res.redirect('/login');
}
}
//Checking whether email is already in the database or not in sign up.
//If email is already in the database, it gives error message.
function checkUserRegValidation(req, res, next) {
var isValid = true;
async.waterfall(
[function(callback) {
User.findOne({email: req.body.user.email, _id: {$ne: mongoose.Types.ObjectId(req.params.id)}},
function(err,user){
if(user){
isValid = false;
req.flash("emailError","- This email is already resistered.");
}
callback(null, isValid);
}
);
}], function(err, isValid) {
if(err) return res.json({success:"false", message:err});
if(isValid){
return next();
} else {
req.flash("formData",req.body.user);
res.redirect("back");
}
}
);
}
//handler function is for topology.html.
function handler(req,res){
fs.readFile(__dirname + '/public/topology.html', function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading topology.html');
}
res.writeHead(200);
console.log("Listening on port 3000");
res.end(data);
});
fs.readFile(__dirname + '/public/style.css', function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading topology.html');
}
res.writeHead(200);
console.log("Listening on port 3000");
res.end(data);
});
}
io.sockets.addListener('connection', function(socket){
console.log("connceted : " + socket.id);
var subscriber = redis.createClient(6379, 'localhost');
subscriber.psubscribe("*");
subscriber.on("pmessage", function(pattern, channel, message) {
//console.log(message);
socket.emit(channel, message);
});
socket.on('disconnect', function () {
console.log("disconnceted : " + socket.id);
subscriber.quit();
});
socket.on('close', function() {
console.log("close");
subscriber.quit();
});
});
server.listen(4000);
Your issue is in your loggedInCheck function. No matter what route you are on, you are checking if the user is authenticated otherwise redirect to login. So, even if your trying to get to the login page, it's gonna try and redirect again, and again forever.
app.get('*', loggedInCheck);
Isn't a good way todo it. You should have some sort of function that makes sure your not trying to go to a zone that is okay for non-users. Maybe something like this:
app.get('*', function(req, res, next){
if(req.url != '/login'){
loggedInCheck(req, res, next);
}else{
next();
}
});
I am trying to use passport local auth with sequelize . When I submit login form, the request/respond cycle never end and there is no error message in the terminal .
Here are all of my codes:
app.js
var Sequelize = require('sequelize'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('./models/users');
........ and other imports.....
//route import , model injection
var auth = require('./routes/auth')(User);
.......................
app.use(session({
store: new RedisStore(),
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
console.log(user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id).then(function(user){
done(null, user);
}).catch(function(e){
done(e, false);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({where: {username: username}}).then(function(err, user) {
if (err) { return done(err); }
if (!user) {
console.log('Incorrect username.');
return done(null, false, { message: 'Incorrect username.' });
} else if (password != user.password) {
console.log('Incorrect password');
return done(null, false, { message: 'Incorrect password.' });
} else {
console.log('ok');
done(null, user);
}
});
}
));
and routes/auth.js :
var express = require('express'),
passport = require('passport');
var routes = function(User) {
var router = express.Router();
// routes for registration
router.route('/register')
.get(function(req, res) {
res.render('register');
})
.post(function(req, res) {
User.count().then(function(number) {
if (number >= 1) {
res.redirect('/auth/login');
} else {
User.create({
username: req.body.username,
password: req.body.password
});
res.redirect('/auth/login');
}
});
});
//routes for login
router.route('/login')
.get(function(req, res) {
res.render('login');
})
.post(function(req, res) {
passport.authenticate('local', { successRedirect: '/dashboard',
failureRedirect: '/auth/login' });
});
return router;
};
module.exports = routes;
Why does the request/response cycle never end?
Your current middleware definition for './login' POST is incorrect and does not send a response, which is why it doesn't end (until it times out).
Instead of calling passport.authenticate in a middleware function, the result of calling passport.authenticate should be used as middleware itself. I suggest the following:
router.route('/login')
.get(function(req, res) {
res.render('login');
})
.post(passport.authenticate('local', { successRedirect: '/dashboard',
failureRedirect: '/auth/login' });
);
See http://passportjs.org/docs/authenticate for an example.
Race condition in registration code
You didn't ask about this, but there is a race condition in your middleware for './register' POST.
User.create returns a promise for saving the created user. Until that promise is resolved there is no guarantee that the user exists in the backing datastore. However, immediately after calling create, your code redirects to the login endpoint which would query the database for that user.
Here is some code that avoids this problem:
User.create({ ... })
.then(function() {
res.redirect('/auth/login');
})
.catch(function(err) {
// Handle rejected promise here
})
The catch is included because it is always good practice to handle rejected promises and thrown exceptions.