I'm new to NodeJS and I try to build a login/registration system. Registration works fine but I'm currently unable to login.
I find a example app using passport and nodejs, so based on this example I build the registration form and the login form.
http://blog.robertonodi.me/node-authentication-series-email-and-password/
When I try to login I get an 'Unknown authentication strategy "local" error'. Can anybody explain what I'm doing wrong?
My code
(edit: added some changes from answers/comments and filenames)
Express config (config/express.config.js)
app.use(session({
store: new MongoStore({
url: 'mongodb://' + config.url + ':' + config.port + '/' + config.name
}),
secret: 'secretkey',
key: 'skey.sid',
resave: false,
saveUninitialized: false,
cookie : {
maxAge: 604800000 //7 days in miliseconds
}
}));
app.use(passport.initialize());
app.use(passport.session());
require(path.join(__dirname, 'auth.config'))(passport); //Load passport config
app.use(function(req, res, next) {
req.resources = req.resources || {};
// res.locals.app = config.app;
res.locals.currentUser = req.user;
res.locals._t = function (value) { return value; };
res.locals._s = function (obj) { return JSON.stringify(obj); };
next();
})
Passport config (config/auth.config.js)
var path = require('path');
var passport=require('passport');
var User = require(path.join(__dirname, '..', 'models', 'user.model'));
module.exports = function(passport) {
passport.serializeUser(function(user, done){
done(null, false);
});
passport.deserializeUser(function(id, done){
console.log("deserializeUser called", id);
User.findById(id, function (err, user) {
done(err, user);
});
});
//load strategy files
require(path.join(__dirname, 'strategies', 'local-strategy'));
//TODO: Facebook
//TODO: Twitter
//TODO: Google
}
Local strategy (/config/strategies/local-strategy.js)
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports = function () {
console.log("LocalStrategy called");
passport.use(new LocalStrategy({
usernameField : 'username',
passwordField : 'password'
},
function(username, password, done) {
User.authenticate(username, password, function(err, user) {
if (err) {
return done(err);
}
if(!user) {
return done(null, false, {message: 'Invalid username or password'});
}
return done(null, user);
})
}))
}
Auth Controller (login only) (/controllers/auth.controller.js)
module.exports.loginUser = function(req,res, next) {
console.log("Auth.config", path.join(__dirname, 'strategies', 'local-strategy'))
passport.authenticate('local', function (err, user, info) {
if (err || !user) {
console.log("Error", info);
return res.status(400).send(info);
}
req.logIn(user, function(err) {
if (err) {
return next(err);
// return res.status(404).send("Username or password incorrect");
}
})
res.status(200).json(user);
})(req, res, next);
}
You forgot to import passport config file in your app.js.
import passport config after initializing passport.
app.use(passport.initialize());
app.use(passport.session());
// Add the line below, which you're missing:
require('./path/to/passport/config/file')(passport);
i have done like this and it worked
$npm install passport-local
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy; /* this should be after passport*/
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.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
this fix the error. need to use 'local' when you create a new LocalStrategy
passport.use('local', new LocalStrategy({
usernameField:'useName',
passwordField: 'password',
passReqToCallback: true
Related
I am trying to build the authentication system using PassportJs and Sequelize. I made the registration system by myself, using Sequelize. I want to use PassportJS only for Login.
It does not redirect me to the failureRedirect route, neither to the SuccessRedirect one, but when submitting the form it enters into an endless loop and in my console, the following message appears:
Executing (default): SELECT `id`, `username`, `lastName`, `password`, `email`, `phone`, `createdAt`, `updatedAt` FROM `user` AS `user` LIMIT 1;
My project is structured in: users_model.js , index.js and users.js (the controller).
The code I have in my index.js looks like this:
//===============Modules=============================
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var authentication= require('sequelize-authentication');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var passportlocal= require('passport-local');
var passportsession= require('passport-session');
var User = require('./models/users_model.js');
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.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return 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);
console.log(id);
});
});
var users= require('./controllers/users.js');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/users', users);
app.use('/events', events);
//-------------------------------------------Setup Session------------
app.use(session({
secret: "ceva",
resave:true,
saveUninitialized:true,
cookie:{},
duration: 45 * 60 * 1000,
activeDuration: 15 * 60 * 1000,
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
//------------------------------------------------Routes----------
app.get('/', function (req, res) {
res.send('Welcome!');
});
//-------------------------------------Server-------------------
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
In my controller, I made the registration system by myself, using Sequelize. In users.js, I have:
var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var passportlocal= require('passport-local');
var passportsession= require('passport-session');
var router = express.Router();
var User = require('../models/users_model.js');
//____________________Initialize Sequelize____________________
const Sequelize = require("sequelize");
const sequelize = new Sequelize('millesime_admin', 'root', '', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
//________________________________________
router.get('/',function(req,res){
res.send('USERS');
});
router.get('/register', function(req, res) {
res.render('registration', {title: "Register" });
});
router.post('/register', function(req, res) {
var email = req.body.email;
var password = req.body.password;
var username= req.body.username;
var lastname= req.body.lastname;
var phone= req.body.phone;
User.findAll().then(user => {
usersNumber = user.length;
x=usersNumber+1;
var y =usersNumber.toString();
var uid='ORD'+ y;
User.sync().then(function (){
return User.create({
id:uid,
email: email,
password:password,
username: username,
lastName: lastname,
phone: phone,
});
}).then(c => {
console.log("User Created", c.toJSON());
res.redirect('/users');
}).catch(e => console.error(e));
});
});
router.get('/login',function(req,res){
res.render('authentication');
});
//router.post('/login', function(req, res, next) {
// console.log(req.url); // '/login'
// console.log(req.body);
// I got these:{ username: 'username', password: 'parola' }
// passport.authenticate('local', function(err, user, info) {
// console.log("authenticate");
// console.log('error:',err);
// console.log('user:',user);
// console.log('info:',info);
// })(req, res, next);
//});
router.post('/login', passport.authenticate('local', {
successRedirect: '/events',
failureRedirect: '/users/register'
}));
router.get('/logout', function(req, res){
req.logout();
res.redirect('/users/login');
});
//__________________________________________
module.exports = router;
Main problem: not an infinite loop, but incorrect usage of Sequelize
This is not an infinite loop but just a hanging response from the server which would be ended with a timeout error.
When you do this:
passport.use(new LocalStrategy(
function(username, password, done) {
...
}
));
...passport and express wait for the done function to be called. Once it's done(), they go forward in the middleware chain and send the response to the client.
The done function is not called, because Sequelize seems to not support callback functions, but promises. So, the correct way to call Sequelize methods is:
User.findOne({ username: username }).then(user => {
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
done(null, user);
}).catch(err => done(err));
(de)Serializing the session user
Seems that there is no id field in the user instances, but userid. Therefore we have to do:
passport.serializeUser(function(user, done) {
done(null, user.userid);
});
passport.deserializeUser(function(id, done) {
User.findOne({ userid: id }).then(user => {
done(null, user);
console.log(id);
}).catch(err => done(err));
});
For reference, this commit fixes these issues.
I'm getting an error in Node.js when I try to login or signup.
I'm using connect-mongodb-session, but when I setup an store, it happen.
serializing user:
{ _id: 57cf316758531915c8a93dd7,
email: 'a',
password: '$2a$10$1.qkrnLWLiG6zFXHTII1pOsHs0sWdFrmfgaGO.6ZY4q/TwZ7E0RTG',
username: 'a',
followers: [],
following: [],
likes: [],
orders: [],
__v: 0 }
POST /login 302 793.072 ms - 46
_http_outgoing.js:344
throw new Error('Can\'t set headers after they are sent.');
^
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (C:\Users\Fabian Gutierrez\Documents\GitHub\maravillarte\node_modules\express\lib\response.js:718:10)
at ServerResponse.send (C:\Users\Fabian Gutierrez\Documents\GitHub\maravillarte\node_modules\express\lib\response.js:163:12)
at done (C:\Users\Fabian Gutierrez\Documents\GitHub\maravillarte\node_modules\express\lib\response.js:957:10)
at Immediate._onImmediate (C:\Users\Fabian Gutierrez\Documents\GitHub\maravillarte\node_modules\express-handlebars\lib\utils.js:26:13)
at processImmediate [as _immediateCallback] (timers.js:383:17)
Error: Can't set headers after they are sent.
I tried a lot of thing, but I don't understand what happens
this is my code, app.s:
var passport = require('passport');
var expressSession = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(expressSession);//session for stores sessions
//MONTAR EL STORE DE SESSIONS
var mystore = new MongoDBStore(dbConfig.store,function(error) {
if (error){
console.log(error)
}
});
app.use(expressSession({
cookie:{ maxAge: 1000 * 60 * 60 * 24 * 7 },
httpOnly: true,
store: mystore,
secret: 'mifuckingkey',
resave: true,
saveUninitialized: false,
unset: 'destroy'
}));
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Inicializar Passport
var initPassport = require('./lib/passport/init');
initPassport(passport);
var routes = require('./routes/index')(passport);
app.use('/', routes);
init.js
var login = require('./login');
var signup = require('./signup');
var User = require('../../models/user');
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user: ');console.log(user);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('deserializing user:',user);
done(err, user);
});
});
console.log("passport iniciado")
// Setting up Passport Strategies for Login and SignUp/Registration
login(passport);
signup(passport);
}
signup.js
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport){
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
// check in mongo if a user with username exists or not
User.findOne({ 'username' : username },
function(err, user) {
// In case of any error, return using the done method
if (err)
return done(err);
// Username does not exist, log the error and redirect back
if (!user){
console.log('User Not Found with username '+username);
return done(null, false, req.flash('message', 'User Not found.'));
}
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
}
// User and password both match, return user from done method
// which will be treated like success
return done(null, user);
}
);
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
}
}
signup.js
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport){
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
// check in mongo if a user with username exists or not
User.findOne({ 'username' : username },
function(err, user) {
// In case of any error, return using the done method
if (err)
return done(err);
// Username does not exist, log the error and redirect back
if (!user){
console.log('User Not Found with username '+username);
return done(null, false, req.flash('message', 'User Not found.'));
}
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
}
// User and password both match, return user from done method
// which will be treated like success
return done(null, user);
}
);
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
}
}
and part of router
router.get('/', function(req, res, next) {
res.render('home', { title: 'Maravillarte',user:req.user});
});
router.get('/vender', function(req, res, next) {
res.render('register', { title: 'Express',layout:'register' });
});
/*///////////////////////////////////////
INICIO DE SESSION
///////////////////////////////////////*/
router.post('/login', passport.authenticate('login', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true,
}));
router.get('/login', function(req, res, next) {
res.render('pages/login', { title: 'Maravillarte',user:req.user});
});
/*///////////////////////////////////////
REGISTRARSE
///////////////////////////////////////*/
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true
}));
in your init.js,
// Setting up Passport Strategies for Login and SignUp/Registration
login(passport);
signup(passport);
Both routes res.render send the response back to the client asynchronously. So, when second route tries to send the response with res.render response of the first route already been sent. That's why it throws error like can't set header after they are sent.
follow the given link below for the example.
I'm using passportjs for the authentication and session. I get the ussername from mysql and the input field from client side but when the done is called on verification, I get done is not a function.
The server.js :
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser');
// app.use(app.router);
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(express.static(__dirname+"/staticFolder"));
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'127.0.0.1',
user:'root',
password:'sdf',
database:'abc'
});
connection.connect(function(err){
if(err){
throw err;
}
});
passport.serializeUser(function(user,done){
console.log("serializeUser" + user);
done(null,user.body.username);
})
passport.deserializeUser(function(id, done) {
done(null, user);
});
passport.use(new LocalStrategy({
passReqToCallback : true
},function(username, password, done) {
connection.query("select * from employeedetails where empid = "+username.body.username,function(err,user,w){
if(err)
{
console.log(err+"fml $$$$$$$$$$");
return done(err);
}
if(username.body.password == user[0].password){
console.log(user[0].empid+" login");
return done(null,user[0].empid);
}
else{
return done(null,false,{message: 'Incorrect password'});
console.log(user[0].empid+" fml");
}
});
}));
app.get('/',function(request,response){
response.sendFile(__dirname+"/staticFolder/view/");
})
app.post('/saveEmployeeDetails',function(request,response){
response.end();
})
app.get('/login',function(request,response){ //the file sent when /login is requested
response.sendFile(__dirname+"/staticFolder/view/login.html");
})
app.post('/loginCheck',passport.authenticate('local', {
successRedirect : '/',
failureRedirect : '/login',
failureFlash : true //
}),
function(req, res) {
console.log("hello");
res.send("valid");
res.redirect('/');
});
Can you please refer to the below link which talks about the same error
https://github.com/jaredhanson/passport/issues/421
It says when you remove the (passReqToCallBack: true) options the error does not occur
In your passport.js config file, passport.use(new LocalStrategy) callback
function depending on which strategy you are using you will need a certain number of arguments.I just had to add "req"
as the first argument in mine.
passport.use(new LocalStrategy({
passReqToCallback: true
},
function (req, apikey, done) {
//ADD REQ UP HERE
process.nextTick(function () {
findByApiKey(apikey, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Unknown apikey : ' + apikey
});
}
return done(null, user);
})
});
}));
It would be an issue of missing parameters in the function.
Here is an example source code for passport-openidconnect strategy:
// Using 'passport-openidconnect' strategy
var OpenidConnectStrategy = require('passport-openidconnect');
var strategy = new OpenidConnectStrategy(
{
issuer: process.env.OAUTH_ISSUER,
authorizationURL: process.env.OAUTH_AUTHORIZATION_URL,
tokenURL: process.env.OAUTH_TOKEN_URL,
userInfoURL: process.env.OAUTH_USERINFO_URL,
clientID: process.env.OAUTH_CLIENT_ID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
callbackURL: process.env.OAUTH_CALLBACK_URL,
},
// Parameters in the function should be appropriate with the strategy
function (issuer, sub, profile, accessToken, refreshToken, done) {
return done(null, profile);
}
);
When I tried to log in from page, I got error return done(null, false, req.flash('loginMessage', 'User does not exist')); TypeError: req.flash is not a function.
Below are my server.js and passport.js configuration:
server.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var session = require('express-session');
var ejs = require('ejs');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
mongoose.connect('mongodb://localhost:mydb');
require('./config/passport')(passport);
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.set('views', __dirname+'/public/views');
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(session({secret:'learningpassport',
resave: true,
saveUnitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
require('./app/routes')(app,passport);
app.listen(3000);
config/passport.js:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../app/model/user');
module.exports = function(passport){
passport.serializeUser(function(user, done){
done(null,user.id);
});
passport.deserializeUser(function(id, done){
User.findById(id, function(err,user){
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
function(req,username, password, done){
process.nextTick(function(){
User.findOne({'local.username': username}, function(err, user){
if(err) return done(err);
if(user)
return done(null, false, req.flash('signupMessage','The username already exists' ));
else{
var newUser = new User();
newUser.local.username = username;
newUser.local.password = newUser.generateHash(password);
newUser.save(function(err){
if(err) throw done(err);
return done(null, newUser);
});
}
});
});
}));
passport.use('local-login', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallBack: true
},function(req,username, password, done){
process.nextTick(function(){
User.findOne({'local.username': username}, function(err,user){
if(err) return done(err);
if(!user){
console.log(req.flash);
return done(null, false, req.flash('loginMessage', 'User does not exist'));
}
if(!user.validPassword(password)){
return done(null,false, req.flash('loginMessage', 'Password is not correct'));
}
return done(null, user);
});
});
}));
};
I would really appreciate everyone's help!!!
loginservice.config.js
'use strict';
angular.module('loginservice').factory('lgservice',function($http){
var myservice = {
async: function(username, password){
var promise = $http.post('/login',{
username: username,
password: password
}).then(function(response){
return response;
});
return promise;
}
};
return myservice;
});
routes.js
module.exports = function(app,passport) {
app.get('/', function (req, res) {
console.log('/');
res.render('pages/login', {
message: req.flash('loginMessage')
});
});
app.get('/about', function (req, res) {
console.log('/about');
res.render('pages/about');
});
app.get('/signup', function (req, res) {
console.log('sign up');
res.render('pages/signup', {
message: req.flash('signupMessage')
});
});
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
app.get('/home', isLoggedIn, function (req, res) {
res.render('pages/home', {
user: req.user
});
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash: true
}));
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash: true
}));
};
funtion isLoggedIn(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.redirect('/');
}
You probably have to move app.use(flash()); up the middleware stack so that it is processed before passport.
you did a spelling mistake
passReqToCallback : true instead of passReqToCallBack: true
Try this.
passport.use('local-login', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallBack: true
}, function(username, password, done) {
process.nextTick(function() {
User.findOne({
'local.username': username
}, function(err, user) {
if (err) return done(err);
if (!user) {
console.log(req.flash);
return done(null, false, req.flash('loginMessage', 'User does not exist'));
}
if (!user.validPassword(password)) {
return done(null, false, req.flash('loginMessage', 'Password is not correct'));
}
return done(null, user);
});
});
}))(req,res,next);
Hope this Help.
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.