Node/Express Cannot GET /api/auth/register - node.js

I'm having trouble with my server routes, I had the server on heroku but now have it local to debug,
On browser inspection i get
404 (Not Found)
in browser window
Cannot GET /api/auth/register
My server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var logger = require('morgan');
var bodyParser = require('body-parser');
var databaseConfig = require('./config/database');
var router = require('./app/routes');
//CORS middleware
var allowCrossDomain = function(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.sendStatus(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
mongoose.connect(databaseConfig.url);
app.listen(process.env.PORT || 8080);
console.log("App listening on port 8080");
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
router(app);
My routes.js
var AuthenticationController = require('./controllers/authentication'),
ExerciseController = require('./controllers/exercises'),
express = require('express'),
passportService = require('../config/passport'),
passport = require('passport');
var requireAuth = passport.authenticate('jwt', {session: false}),
requireLogin = passport.authenticate('local', {session: false});
module.exports = function(app){
var apiRoutes = express.Router(),
authRoutes = express.Router(),
exerciseRoutes = express.Router();
// Auth Routes
apiRoutes.use('/auth', authRoutes);
//authRoutes.post('/register', AuthenticationController.register);
authRoutes.post('/register', function(req, res){
AuthenticationController.registerUser
});
authRoutes.post('/login', requireLogin, AuthenticationController.login);
authRoutes.get('/protected', requireAuth, function(req, res){
res.sendStatus({ content: 'Success'});
});
// Exercise Routes
apiRoutes.use('/exercises', exerciseRoutes);
exerciseRoutes.get('/', requireAuth, AuthenticationController.roleAuthorization(['client','trainer','admin']), ExerciseController.getExercises);
exerciseRoutes.post('/', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.createExercise);
exerciseRoutes.delete('/:exercise_id', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.deleteExercise);
// Set up routes
app.use('/api', apiRoutes);
}
And my Controller Authentication.js :
var jwt = require('jsonwebtoken');
var User = require('../models/user');
var authConfig = require('../../config/auth');
function generateToken(user){
return jwt.sign(user, authConfig.secret, {
expiresIn: 10080
});
}
function setUserInfo(request){
return {
_id: request._id,
email: request.email,
role: request.role,
trainer: request.trainer,
programs: request.programs
};
}
exports.login = function(req, res, next){
var userInfo = setUserInfo(req.user);
console.log(userInfo)
res.status(200).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
});
}
exports.registerUser = function(req, res, next){
var email = req.body.email;
var password = req.body.password;
var role = req.body.role;
var trainer = req.body.trainer;
var programs= req.body.programs;
if(!email){
return res.status(422).send({error: 'You must enter an email address'});
}
if(!password){
return res.status(422).send({error: 'You must enter a password'});
}
User.findOne({email: email}, function(err, existingUser){
if(err){
return next(err);
}
if(existingUser){
return res.status(422).send({error: 'That email address is already in use'});
}
var user = new User({
email: email,
password: password,
role: role,
trainer: trainer,
programs: programs
});
user.save(function(err, user){
if(err){
return next(err);
}
var userInfo = setUserInfo(user);
res.status(201).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
})
});
});
}
exports.roleAuthorization = function(roles){
return function(req, res, next){
var user = req.user;
User.findById(user._id, function(err, foundUser){
if(err){
res.status(422).json({error: 'No user found.'});
return next(err);
}
if(roles.indexOf(foundUser.role) > -1){
return next();
}
res.status(401).json({error: 'You are not authorized to view this content'});
return next('Unauthorized');
});
}
}
I dont have much experience with express/node so im not sure where im going wrong, could be something simple im just not able to see, anyways any help is greatly appreciated , not sure if you need more info, this is going to be the back end for an ionic 2 app

Related

passport.authenticate (local strategy) not able to take req body username and password and returned message (“Missing Credentials')

many hours spent on reading books, passport.org and similar issues in stackoverflow. However, still had no clue why login failed using passport to authenticate with simple local strategy of username and password. passport.autheticate came back stating with info="missing credential" and user='false".
before stepping into passport.authenticate, confirmed that req.body had the right user info of username and password from Angular.
Besides, user registration using passport worked, however, using same username and password was not able to log in.
Below pls find code and thanks for any help in advance.
App.js (code associated with user registration and login)
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var authenticate = require('./lib-general/authenticate');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var User = require('./model/user');
var app = express();
const util = require('util');
var debug = require('debug')('http'),
http = require('http'),
name ='pIn3-server';
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use( bodyParser.urlencoded({ extended: true }) );
app.use(session({
name: 'session-id',
secret: config.secretKey,
saveUninitialized: false,
resave: false,
store: new FileStore()
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/', usersRouter);
authenticate.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../model/user');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');
passport.use(new LocalStrategy(User.authenticate(),{passReqToCallback : true}));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
console.log("before getToken");
exports.getToken = function(user) {
return jwt.sign(user, config.secretKey,
{expiresIn: 3600});
};
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
console.log("after jwtFromRequest - extract JWT");
console.log(opts.jwtFromRequest);
opts.secretOrKey = config.secretKey;
console.log("after secretOrKey");
console.log(opts.secretOrKey);
exports.jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload, done) => {
console.log("JWT payload: ", jwt_payload);
User.findOne({_id: jwt_payload._id}, (err, user) => {
if (err) {
return done(err, false);
}
else if (user) {
return done(null, user);
}
else {
return done(null, false);
}
});
}));
exports.verifyUser = passport.authenticate('jwt', {session: false});
Users.js (user router)
var express = require('express');
const bodyParser = require('body-parser');
var User = require('../model/user');
var passport = require('passport');
var authenticateMy = require('../lib-general/authenticate'); // use my to distinguish from passport authenticate
var LocalStrategy = require('passport-local').Strategy;
var cors = require('./cors');
var userRouter = express.Router();
userRouter.use(bodyParser.json());
const mongoose = require('mongoose');
const mongooseClient = require('mongoose'); /* this is important */
console.log("step into router users");
/*ensure if it from right port of whitelist in cors:3000, 3443, 4200 */
userRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } )
/* Get users listing. */
userRouter.get('/',cors.cors,function(req,res,next){
res.send('respond with a resource')
});
userRouter.post('/signup', cors.corsWithOptions,(req, res, next) => {
console.log('2.0.0.1 - at register',req.body);
let newUser = new User( {
_id: new mongoose.Types.ObjectId(),
username: req.body.username,
password: req.body.password,
firstName: req.body.firstName,
lastName: req.body.lastName,
role: req.body.role,
remember: req.body.remember }); // from book
User.register(newUser, req.body.password, (err, user) => {
if(err) {
console.log('2.0.0.2 - at register',err,user);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
}
else {
console.log('2.0.1 - at register',req.body);
user.save((err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
return ;
}
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Registration Successful!'});
});
});
}
});
});
userRouter.post('/login', cors.corsWithOptions, (req, res, next) => {
console.log('2.0.4 - at login',req.body);
passport.authenticate('local', (err, user , info) => {
console.log('2.0.5 - at login', user, info);
if (err)
return next(err);
if (!user) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: info});
}
req.logIn(user, (err) => {
if (err) {
console.log('2.0.6 - at req.login',user);
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: 'Could not log in user!'});
}
var token = authenticateMy.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Login Successful!', token: token});
});
}) (req, res, next);
});
userRouter.get('/logout', (req, res) => {
console.log('in userRouter logout code')
if (req.session) {
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
}
else {
console.log('in userRouter log out ')
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});

Node.js passport not authenticating at login

I am trying to implement a simple user login and signup page for my application.
The signup page works and everything is getting stored in mongodb correctly. However, when I try to login it it does not seem to work. It is supposed to redirect to my root page but it will not do that. It always redirect back to /users/login
I've been going through a tutorial online so I do not understand why this isn't working. Here are the relevant files files.
user.js file
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
let User = require('../models/user');
// Load register form
router.get('/register', function(req, res) {
res.render('register', {
title : 'Register',
errors : req.flash('success')
});
});
// Submit register form
router.post('/register', function(req, res) {
// Get the fields from the form
const firstname = req.body.firstname;
const lastname = req.body.lastname;
const email = req.body.email;
const pass = req.body.pass;
const pass2 = req.body.pass2;
// Verify body is not empty.
req.checkBody('firstname', 'First name is required').notEmpty();
req.checkBody('lastname', 'Last name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('pass', 'Password is required').notEmpty();
req.checkBody('pass2', 'Passwords do not match.').equals(req.body.pass);
// Check for errors
let errors = req.validationErrors();
if (errors) {
res.render('register', {
errors:errors
});
} else {
// Create new user object
let newUser = new User({
firstname:firstname,
lastname:lastname,
email:email,
pass:pass
});
// Hash the password for security.
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.pass, salt, function(err, hash) {
if (err) {
console.log(err);
}
newUser.pass = hash;
newUser.save(function(err) {
if (err) {
console.log(err);
return;
} else {
console.log("Successful creation.")
req.flash('success', 'Account creation successful!');
res.redirect('/users/login');
}
});
});
})
}
});
// Load login form
router.get('/login', function(req, res){
res.render('login');
});
// Submit login form
router.post('/login', function(req, res, next) {
passport.authenticate('local', {
successRedirect: '..',
failureRedirect: '/users/login',
failureFlash: true
})(req, res, next);
});
module.exports = router;
passport.js file
const LocalStrategy = require('passport-local').Strategy;
const passport = require('passport');
const User = require('../models/user');
const config = require('../config/database');
const bcrypt = require('bcryptjs');
// User Authentication
module.exports = function(passport){
console.log("Made it intro str");
passport.use(new LocalStrategy(function(email, pass, done){
// Match username
let query = {email:email};
User.findOne(query, function(error, user){
if (error){
console.log("error");
return done(error);
}
if (!user) {
console.log("No user found");
return done(null, false, {message: 'No user found.'});
}
bcrypt.compare(pass, user.pass, function(error, isMatch) {
if (error) {
console.log("error2");
return done(error);
}
if (isMatch) {
console.log("Matching password");
return done(null, user);
} else {
console.log("Wrong password");
return done(null, false, {message: 'Invalid password.'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}
App.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const session = require('express-session');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressValidator = require('express-validator');
const config = require('./config/database');
const flash = require('connect-flash');
const passport = require('passport');
/* Connect to Database */
mongoose.connect(config.database, { useNewUrlParser: true });
let db = mongoose.connection;
// Check connection.
db.once('open', function(){
console.log('Connected to MongoDB.');
})
// Check DB error.
db.on('error', function(error){
console.log(error);
});
/* Initialize app */
var app = express();
/* Bring in models for database */
let User = require('./models/user');
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Load the view engines
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Set public folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressValidator());
// Keep users session
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Express Validator Middleware
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Passport config
require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
// Load homepage
app.get('/', function(req, res) {
res.render('index', {
title: 'Index',
})
})
// Define routes
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/user');
app.use('/', indexRouter);
app.use('/users', usersRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
;
module.exports = app;
I believe the issue is in your passport.js file... By default, LocalStrategy expects to find credentials in parameters named username and password. You need to change that... something like so:
const localOptions = { usernameField: 'email', passwordField: 'pass' };
passport.use(new LocalStrategy(localOptions, function (email, pass, done) {
// Match username
let query = { email: email };
User.findOne(query, function (error, user) {
// etc etc...
});
}));
Link to the docs (at the bottom of the page...): http://www.passportjs.org/docs/username-password/

How to generate token using passport.js while signing in locally and not with any other social media channel?

I am trying to generate token while logging in locally. Let's say I am normal user and want to sign in. Will token get generated while signing in? and how? Need guidance. Thanks
As I am using mongodb I require my users schema model in my routes code.Here is my routes code user.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/schema');
var Verify = require('./verify');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
When you look at the code you will notice a verify variable.It is nothing but verification that is user is registered or not.If user registered then user will allow for login.After login user will get a successfull response along with token.So here is my veirfy code verify.js
var User=require('../models/schema');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, {
expiresIn: 3600
});
};
exports.verifyOrdinaryUser = function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secretKey, function (err, decoded) {
if (err) {
var err = new Error('You are not authenticated!');
err.status = 401;
return next(err);
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
var err = new Error('No token provided!');
err.status = 403;
return next(err);
}
};
If you observe the code there is a variable like config this is nothing but connection to my mongodb.Here is the code config.js
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/conFusion'
}
And the user schema is here schema.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{
type:String,
required:true,
unique:true
},
email:{
type:String,
required:true,
unique:true
},
phone:{
type:Number,
required:true,
unique:true
},
password:{
type:String
}
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
And finally server code app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var User = require('./models/schema');
app.use(passport.initialize());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000,function(){
console.log("Server Listening on 3000");
});
module.exports = app;
project structure must be as per my code
+app.js
+config.js
+routes(directory)
++user.js
++verify.js
+models(directory)
++schema.js
run the code node app.js
When you want to register use http://localhost:3000/users/register
and for login use http://localhost:3000/users/login

How can I do Passport Authentication on multiple users?

Here I have multiple users like Parent,Trainer,Provider.I wrote individual schemas, routes and verify codes for registration and login and for storing, collections also different for each.when I make to run the application it is properly running.And after that I opened the postman tool I registered as" parent" the response is "Registration Successfull" and login as parent I am getting token so that I can perform the functions what a Parent can do in my project.And after that I logout as parent.Next, when I try to registered as Trainer/Provider the response is "Unauthorized". But the fields what I am giving at time of registration are stored in respective collections in database.When I give same values what a parent gave at the time of registration to trainer registration and provider registration then the response is "Registration Successfull" when I give different values other than what a parent gave it shows me "Unauthorized".So, I want to know why this issue arises? And how can I fix this problem?
Here is my schema code
<!-- trainer schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var trainerUser= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
trainerUser.plugin(passportLocalMongoose);
module.exports = mongoose.model('trainerUser', trainerUser);
<!-- parent schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
email:String,
password: String,
phonenumber:Number
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('parentlog', User);
<!-- provider schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
Here is my routes code for each module
//trainer route
<!-- trainer route -->
var express = require('express');
var router = express.Router();
var passport = require('passport');
var trainerUser = require('../models/traineruser');
var Verify = require('./trainerverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
trainerUser.register(new trainerUser({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//parent route
const AuthenticationController = require('../controllers/authentication');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/puser');
var Verify = require('./parentverify');
var mongoose=require('mongoose');
const requireLogin = passport.authenticate('local', { session: false });
router.route('/')
.get(function(req, res) {
User.find({},function(err,users){
if(err) {
return res.status(403).json({
err: 'You are not authorized to perform this operation!'
});
} else {
res.json(users);
}
});
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email:req.body.email,phonenumber:req.body.phonenumber }),
req.body.password, function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', requireLogin, AuthenticationController.login);
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//provider route
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user');
var Verify= require('./userverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
and app.js code is here
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
<!-- we're connected! -->
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var trainerusers = require('./routes/trainerusers');
var pusers = require('./routes/pusers');
var contacts=require('./routes/contactRouter');
var student=require('./routes/studentRouter');
var batch=require('./routes/batchRouter');
var venue=require('./routes/venueRouter');
var trainerrouter = require('./routes/trainerrouter.js');
var report=require('./routes/reportRouter');
var attendance=require('./routes/attendanceRouter');
var app = express();
<!-- view engine setup -->
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
<!-- uncomment after placing your favicon in /public-->
<!-- app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));-->
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
<!-- passport config -->
var User = require('./models/user');
var trainerUser = require('./models/traineruser');
var Puser = require('./models/puser');
app.use(passport.initialize());
passport.use(new LocalStrategy(Puser.authenticate(),trainerUser.authenticate(),User.authenticate()));
passport.serializeUser(Puser.serializeUser(),trainerUser.serializeUser(),User.serializeUser());
passport.deserializeUser(Puser.deserializeUser(),trainerUser.deserializeUser(),User.deserializeUser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/trainerusers', trainerusers);
app.use('/pusers', pusers);
app.use('/contacts',contacts);
app.use('/student',student);
app.use('/batch',batch);
app.use('/venue',venue);
app.use('/report',report);
app.use('/trainer',trainerrouter);
app.use('/attendance',attendance);
<!-- catch 404 and forward to error handler -->
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
<!-- error handlers -->
<!-- development error handler -->
<!-- will print stacktrace -->
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
<!-- production error handler -->
<!-- no stacktraces leaked to user -->
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app;

NodeJS: Passport authentication not working

I am using passport local for authentication and the login credentials don't get authenticated. I just get redirected to the failureRedirect. I don't even get the flash error.
Here is my login route:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var flash = require('connect-flash');
router.get('/', function(req, res, next) {
if(req.user){
return res.redirect('/profile');
}
var vm = {
title: 'Login',
error: req.flash('error')
};
res.render('login', { title: 'Place an order' });
});
router.post('/',
passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/profile',
failureFlash: 'Invalid credentials'
}));
module.exports = router;
This is app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var expressSession = require('express-session');
var flash = require('connect-flash');
var config = require('./config');
var routes = require('./routes/index');
var signup = require('./routes/signup');
var login = require('./routes/login');
var profile = require('./routes/profile');
var restrict = require('./auth/restrict');
var passportConfig = require('./auth/passport-config');
passportConfig();
mongoose.connect(config.mongoUri);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({
secret: 'themsec',
saveUninitialized: false,
resave: false
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.use('/signup', signup);
app.use('/login', login);
//app.use(restrict);
app.use('/profile', profile);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Passport-config:
module.exports = function(){
var passport = require('passport');
var passportLocal = require('passport-local');
var userService = require('../services/user-service');
passport.use(new passportLocal.Strategy({username: 'email'},function(email, password, next){
userService.findUser(email, function(err, user){
if(err){
return next(err);
}
if(!user || user.password!= password){
return next(null, null);
}
next(null, user);
});
}));
passport.serializeUser(function(user, next){
next(null, user.email);
});
passport.deserializeUser(function(email, next){
userService.findUser(email, function(err, user){
next(err, user);
});
});
};
User services:
var User = require('../models/user').User;
exports.addUser = function(user, next){
var newUser = new User({
firstName: user.firstName,
lastName: user.lastName,
email:user.email.toLowerCase(),
password: user.password,
});
newUser.save(function(err){
if(err)
return next(err)
next(null);
});
};
exports.findUser = function(email, next){
User.findOne({email:email.toLowerCase()}, function(err, user){
next(err, user)
});
};
User model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userService = require('../services/user-service');
var userSchema = new Schema({
firstName: {type: String, required: true},
lastName: String,
email: {type: String, required: true},
password: {type: String, required: true},
created: {type: Date, default: Date.now}
});
userSchema.path('email').validate(function(value, next){
userService.findUser(value, function(err, user){
if(err){
console.log(err);
return false;
}
next(!user)
});
}, 'That email is already in use');
var User = mongoose.model('User', userSchema);
module.exports = {
User:User
};
Someone please help me, I am turning mad with frustration. I am new to Node.
Edit: I have removed the code that would lead to an infinite loop if the user logged-in, however, I still cannot login.

Resources