Passportjs Local authetication is not working properly - javascript

After implementing using passport-local not able to open profile page
I'm getting this below error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
passport-local-strategy.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
passport.use(new LocalStrategy({
usernameField: 'email'
},
function(email, password, done){
User.findOne({email: email}, function(err, user){
if(err){
console.log('Error in finding user --> Passport');
return done(err);
}
if(!user || user.password!=password){
console.log("Invalid username/password");
return done(null, false);
}
return done(null, user);
});
}
));
// serialize user function
passport.serializeUser(function(user, done){
done(null, user.id);
});
//deserialize the user fn
passport.deserializeUser(function(id, done){
User.findById(id, function(err, user){
if(err){
console.log("Error in finding user --> passport");
return done(err);
}
return done(null, user);
});
});
// check if user is authenticated
passport.checkAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
return next();
}
// if the user is not signed in
return res.redirect('/users/sign-in');
}
passport.setAuthenticatedUser = function(req, res, next){
if(req.isAuthenticated()){
// req.user contains current signed in user data from the login page
res.locals.user = req.user;
}
next();
}
module.exports = passport;
users_controller.js
const User = require('../models/user')
module.exports.profile = function(req, res){
if(req.cookies.user_id){
User.findById(req.cookies.user_id, function(err, user){
if(user){
return res.render('profile',{
title:"Profile",
user:user
});
}
else{
return res.redirect('/users/sign-in')
}
})
}
else{
return res.redirect('/users/sign-in');
}
}
// render the sign up and in page
module.exports.signUp = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_up', {
title: "Codeial | Sign Up"
})
}
module.exports.signIn = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_in', {
title: "Codeial | Sign In"
})
}
// get the sign up data
module.exports.create = function(req, res){
if(req.body.password != req.body.confirm_password){
return res.redirect('back')
}
User.findOne({email:req.body.email}, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
if(!user){
User.create(req.body, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
return res.redirect('/users/sign-in')
})
}
else{
return res.redirect('back')
}
})
}
module.exports.createSession = function(req, res){
return res.redirect('/');
}
users.js
const express = require('express')
const router = express.Router();
const passport = require('passport');
const usersController = require('../controllers/users_controller');
router.get('/profile',passport.checkAuthenticated,usersController.profile)
router.get('/sign-up', usersController.signUp);
router.get('/sign-in', usersController.signIn);
// in above all codes after get('/sign-up') means when we type the keyword sign-up in the browser we need to render the folllowing page which is userController.signUp
// we are using users_controller.js file by importing
router.post('/create', usersController.create);
router.post('/create-session',passport.authenticate(
'local',
{failureRedirect: '/users/sign-in'},
),usersController.createSession);
// above line post create-session is forms action in user_sign_in.ejs file - when we submit the data of the form the post method is invoked
module.exports = router;
mongoose.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/codeial_development')
const db = mongoose.connection;
db.on('error', console.error.bind(console, "Error connecting to MongoDb"));
db.once('open', function(){
console.log('connected to the database :: MongoDB ')
})
module.exports = db;
index.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 8000;
const expressLayouts = require('express-ejs-layouts');
const db = require('./config/mongoose')
const session = require('express-session');
const passport = require('passport');
const passportLocal = require('./config/passport-local-strategy')
const MongoStore = require('connect-mongodb-session')(session)
app.use(express.urlencoded());
/* is a method inbuilt in express to recognize the incoming
Request Object as strings or arrays. This method is called as a
middleware in your application using the code*/
app.use(cookieParser());
app.use(express.static('./assets'));
app.use(expressLayouts);
// extact style and scripts from subpages into the layout
app.set('layout extractStyles', true)
app.set('layout extractScripts', true)
app.set('view engine', 'ejs');
app.set('views','./views')
app.use(session({
name: 'codeial',
secret:'blahsomeone',
saveUninitialized:false,
resave:false,
cookie:{
maxAge: (1000 * 60 * 100)
},
store: new MongoStore({
// mongooseConnection:db
mongoUrl: db._connectionString,
autoRemove: 'disabled'
}, function(err){
console.log(err || 'connect-mongo setup ok')
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setAuthenticatedUser);
// use express router
app.use('/', require('./routes'));
app.listen(port, function(err){
if(err){console.log(`Error running the server: ${err}`)};
console.log(`Server is running on port: ${port}`);
})
I'm not able to view profile page, its redirecting or getting this error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS

Related

req.isAuthenticated is not a function while using Express and passport

in the last few hours I setup a backend express server. It works just fine and now I tryed to implement an authorization with help of a tutorial.
The login works, but when I try to open /authrequired (so basically a future page which needs a logged in user to work) I get the error message: "TypeError: req.isAuthenticated is not a function"
Here is my index.js file:
const express = require('express');
const fs = require('fs');
const http = require('http');
const https = require('https');
const path = require('path');
const uuid = require('uuid').v4;
const session = require('express-session');
const FileStore = require('session-file-store')(session);
const bodyParser = require('body-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const users = [
{id: '2f24vvg', email: 'test#test.com', password: 'password'}
]
// configure passport.js to use the local strategy
passport.use(new LocalStrategy(
{ usernameField: 'email' },
(email, password, done) => {
console.log('Inside local strategy callback')
// here is where you make a call to the database
// to find the user based on their username or email address
// for now, we'll just pretend we found that it was users[0]
const user = users[0]
if(email === user.email && password === user.password) {
console.log('Local strategy returned true')
return done(null, user)
}
}
));
// tell passport how to serialize the user
passport.serializeUser((user, done) => {
console.log('Inside serializeUser callback. User id is save to the session file store here')
done(null, user.id);
});
passport.deserializeUser((id, done) => {
console.log('Inside deserializeUser callback')
console.log(`The user id passport saved in the session file store is: ${id}`)
const user = users[0].id === id ? users[0] : false;
done(null, user);
});
const app = express();
app.enable('trust proxy')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(session({
genid: (req) => {
console.log('Inside the session middleware')
console.log(req.sessionID)
return uuid() // use UUIDs for session IDs
},
store: new FileStore(),
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
app.use(passport.session());
app.post('/login', (req, res, next) => {
console.log('Inside POST /login callback')
passport.authenticate('local', (err, user, info) => {
console.log('Inside passport.authenticate() callback');
console.log(`req.session.passport: ${JSON.stringify(req.session.passport)}`)
console.log(`req.user: ${JSON.stringify(req.user)}`)
req.login(user, (err) => {
console.log('Inside req.login() callback')
console.log(`req.session.passport: ${JSON.stringify(req.session.passport)}`)
console.log(`req.user: ${JSON.stringify(req.user)}`)
return res.send('You were authenticated & logged in!\n');
})
})(req, res, next);
})
function isAuthenticated (req, res, next) {
if (req.session.user) next()
else next('route')
}
app.get('/authrequired', isAuthenticated, function (req, res) {
res.send('you hit the authentication endpoint\n')
})
app.use(express.static(path.resolve(__dirname, 'build')));
app.use(express.json());
// Redirect from http port to https
http.createServer(function (req, res) {
res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(80,433) + req.url });
console.log("http request, will go to >> ");
console.log("https://" + req.headers['host'].replace(80,433) + req.url );
res.end();
}).listen(80, () => console.info('Listening on port', 80))
//Start https server
https.createServer({
key: fs.readFileSync('./ssl/privkey.key'),
cert: fs.readFileSync('./ssl/cert.cer'),
keepAlive: true
}, app).listen(443, () => console.info('Listening on port', 443));
Anyone got a clue? I saw similar questions on stackoverflow, but nothing worked for me.
There is no such function isAuthenticated. That's why you get the error.
Try replace it with if(req.session.user) {
Or by the example in express-session
// middleware to test if authenticated
function isAuthenticated (req, res, next) {
if (req.session.user) next()
else next('route')
}
app.get('/', isAuthenticated, function (req, res) {
// this is only called when there is an authentication user due to isAuthenticated
res.send('hello, ' + escapeHtml(req.session.user) + '!' +
' Logout')
})
EDIT: You also need to use passport session middleware, by adding
app.use(passport.session());
Make sure it is coming after the session init.

how to make a page only accessible when logged in with express & ejs

Currently I'm working on a little project for a dummy login/register page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users.
I'm currently using this code for the app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var expressSession = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var AuthTokenStrategy = require('passport-auth-token').Strategy;
require('./models');
var User = mongoose.model('User')
mongoose.connect('mongodb://localhost:27017/my-data', { useNewUrlParser: true, useUnifiedTopology: true })
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
passport.use(new LocalStrategy({
usernameField: "key"
}, function(key, next) {
User.findOne({
key: key
}, function(err, user) {
if (err) return next(err);
if (!user) {
return next({message: 'Key incorrect'})
}
next(null, user);
})
}));
passport.serializeUser(function (user, next) {
next(null, user._id)
})
passport.deserializeUser(function (id, next){
User.findById(id, function (err, user) {
next(err, user);
});
});
app.use(passport.initialize());
app.use(passport.session());
app.use(expressSession({
secret: 'aksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnasaksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnas'
}))
app.get('/', function(req, res, next){
res.render('index', {title: 'MySite'})
});
app.get('/main', function(req, res, next){
res.render('main')
});
app.get('/login', function(req, res, next){
res.render('login')
});
app.post('/signup', function(req, res, next){
User.findOne({
key: req.body.key
}, function (err, user) {
if (err) return next(err)
if (user) return next({message: 'This client exists'})
let newUser = new User({
key: req.body.key
});
newUser.save(function(err) {
if (err) return next(err);
res.redirect('/main');
});
console.log(req.body)
});
});
app.post('/login', async (req, res, next) => {
const key = req.body.key;
//const ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
//console.log(ip);
if (!key) return res.status(401).json({ err: 'Key not provided' });
const User = mongoose.model('User');
const user = await User.findOne({ key }).exec();
if (!user) return res.status(401).json({ err: 'Invalid Key' });
res.redirect('/main');
});
// 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;
Try do add this middleware to protected route:
function isAuthenticated(req,res,next){
if(req.isAuthenticated()){ // will return true if user is logged in
next();
} else{
res.redirect("/login");
}
}
app.get('/protectedPath',isAuthenticated, function(req,res) {
//protected content
);

Username entries all come out as 'null' in mongodb nodejs

I'm getting started in node.js and trying to create a user authentication system for my web application. I am watching a tutorial on YouTube and have followed every step through. When it comes to actually registering my user. the username entry in the collecting comes out as null. I'm not sure why this is happening, and I'm a rookie to javascript and node js. I am using passport, express and mongodb modules.
this is the video i am watching 'https://www.youtube.com/watch?v=m2ZzRZemc98'
If anyone knows how to fix my issue, please respond
Thanks
This is my main app.js
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const MongoClient = require("mongodb").MongoClient;
const passport = require("passport");
const Strategy = require("passport-local").Strategy;
const session = require("express-session");
const flash = require("connect-flash");
const authUtils = require("./utils/auth");
const hbs = require("hbs");
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
const authRouter = require("./routes/auth");
var app = express();
//Connet to MongoDB database
MongoClient.connect("mongodb://localhost", (err, client) => {
if (err) {
throw err;
}
const db = client.db("user-profiles");
const users = db.collection("users");
app.locals.users = users;
});
//Passport streategy
passport.use(
new Strategy((username, passport, done) => {
app.locals.users.findOne({ username }, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != authUtils.hashPassword(password)) {
return done(null, false);
}
return done(null, user);
});
})
);
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, done) => {
done(null, { id });
});
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
hbs.registerPartials(path.join(__dirname, "views/partials"));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(
session({
secret: "session secret",
resave: false,
saveUninitialized: false
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.loggedIn = req.isAuthenticated();
next();
});
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/auth", authRouter);
// 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;
This is my auth.js
const router = express.Router();
const authUtils = require("../utils/auth");
const passport = require("passport");
router.get("/login", (req, res, next) => {
const messages = req.flash();
res.render("login", { messages });
});
router.post(
"/login",
passport.authenticate("local", {
failureRedirect: "/auth/login",
failureFlash: "Wrong username or password"
}),
(req, res, next) => {
res.redirect("/users");
}
);
router.get("/register", (req, res, next) => {
const messages = req.flash();
res.render("register", { messages });
});
router.post("/register", (req, res, next) => {
const registrationParams = req.body;
const users = req.app.locals.users;
const payload = {
username: registrationParams.username,
password: authUtils.hashPassword(registrationParams.password)
};
users.insertOne(payload, err => {
if (err) {
req.flash("error", "User account already exists");
} else {
req.flash("success", "User account was registered succesfully");
}
res.redirect("/auth/register");
});
});
router.get("/logout", (req, res, next) => {
req.session.destroy();
res.redirect("/");
});
module.exports = router;
I fixed my error, it was a mistake i made in the handlebars file, i put the input name as none the class of form-control and then named it again. Obviously the js looked at the first name and not the second name

Node js logout instruction isn't running in a serial way

eI'm using:
framework: express
template engine :handlebars
authentification: passport / passport-local
So login process goes well, but in logout i have a problem:
//routes/users.js
//logout
router.get("/logout",(req,res)=>{
req.logout();
req.flash("success_msg","You are logged out");
console.log(req.user);
res.render("users/login");
});
//views/users/login.js
{{user}}
//app.js:
// Setting Global variables:
app.use(function(req,res,next){
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
res.locals.user = req.user || null;
next();
});
So the probleme is that when i clic on logout, i'm redirected to login view but the user object still there(not null),and when I refresh the user is initialised to null,
So my problem why the user haven't been set to null before refirection ?
Full files codes :(app.js, routes/users.js, /config/passport.js)
* app.js
const express = require('express');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const flash = require('connect-flash');
const session = require('express-session');
//const path = require("path");
const passport = require('passport');
const app=express();
// load routes :
const ideas = require("./routes/ideas");
const users = require("./routes/users");
//---------------Mongoose Connect-----------------------
//Map global promise = get rid of warning
mongoose.Promise = global.Promise;
//Connect to mongoose
mongoose.connect('mongodb://localhost/vidjot-db',{
useMongoClient: true
})
.then(function(){
console.log("MongoDB connected ...");
})
.catch(err => console.log(err));
//----------------Middlewares set in Use-----------------
// Static folder Set:
//app.use(express.static(path.join(__dirname,'public')));
app.use(express.static('public'));
// Session middleware :
app.use(session({
secret: 'mySecret',
resave: true,
saveUninitialized: true,
//cookie: { secure: true }
}));
// passport middleware :
app.use(passport.initialize());
app.use(passport.session());
// handlebars middleware :
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
// body parser middleware :
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//methodOverride middleware:
app.use(methodOverride('_method'));
//Connect flash middleware:
app.use(flash());
//----------------My Own Middlewares-----------------
// Setting Global variables:
app.use(function(req,res,next){
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
console.log("res.locals.user");
res.locals.user = req.user || null;
next();
});
/* app.use(function(req,res,next){
console.log("3ale rou7i");
console.log(Date.now());
req.att_x="karim";
next();
}) */
app.use(function(req,res,next){
console.log("hani ne5dem");
next();
});
//-----------------Routes-----------------------------
// Index Route:
app.get("/",(req,res) => {
res.render('index');
//console.log("get callback");
});
// about Route:
app.get("/about",(req,res)=>{
res.render("about",{title:"about1"});
});
// Use routes :
app.use("/ideas",ideas);
app.use("/users",users);
//--------------------------------------------------
//call local-strategy:
require("./config/passport")(passport);
//--------------------------------------------------
const port=5000;
app.listen(port,()=>{
console.log(`server started on port ${port}`);
});
* routes/users.js:
const express = require("express");
const mongoose = require("mongoose");
const bcrypt = require('bcryptjs');
const passport = require("passport");
const router = express.Router();
//--------------------------------------------------
// Load User Model:
require('../models/User');
const User = mongoose.model('Users');
//--------------------------------------------------
//login form
router.get("/login",(req,res)=>{
res.render("users/login");
});
//handle login form:
router.post('/login',
passport.authenticate('local', {
successRedirect: '/ideas',
failureRedirect: '/users/login',
failureFlash:true,
})
);
//logout
router.get("/logout",(req,res)=>{
req.logout();
req.flash("success_msg","You are logged out");
console.log("routes users",req.user);
res.render("users/login");
});
//register form
router.get("/register",(req,res)=>{
res.render("users/register");
});
// handle register form
router.post("/register",(req,res)=>{
let errors=[];
if(req.body.password != req.body.password2)
errors.push({"text":"password do not match"});
if(req.body.password.length < 4)
errors.push({"text":"password must be at least 8 characters"});
if(errors.length > 0)
res.render("users/register",{
errors:errors,
name:req.body.name,
email:req.body.email,
});
else{
User.findOne({email:req.body.email})
.then(user=>{
if(user){
req.flash("error_msg","email already registred");
res.render("/users/login");
}else{
const newUser = new User({
name:req.body.name,
email:req.body.email,
password:req.body.password,
date:req.body.date,
});
bcrypt.hash(newUser.password, 10, function(err, hash) {
if (err) throw err;
newUser.password=hash;
newUser
.save()
.then(user=>{
req.flash("success_msg","You are registered, You can connect Now");
res.redirect("/users/login");
}).catch(err=>{
console.log(err);
return;
});
});
}
})
}
});
//--------------------------------------------------
module.exports = router;
* config/passport.js :
const mongoose = require('mongoose');
const bcrypt = require("bcryptjs");
const LocalStrategy = require("passport-local").Strategy;
const passport = require("passport");
//-------------------------------------------------------
// Load User Model:
require('../models/User');
const User = mongoose.model('Users');
//-------------------------------------------------------
module.exports=function(passport){
passport.use(
new LocalStrategy({usernameField:'email'},function(email, password, done){
User.findOne({'email':email},function(err, user) {
if (err)
return done(err);
if (!user)
return done(null, false,{message:"You are not registred"});
if (!bcrypt.compareSync(password,user.password) ){
return done(null, false,{message:"Missing email or password !"});
}
return done(null, user);
});
}));
passport.serializeUser(function(user, done) {
console.log("SERIALIZE");
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log("DESERIALIZE");
User.findById(id, function(err, user) {
done(err, user);
});
});
}
You have middleware that set res.locals based on a logged in user for every request.
Your res.render() template uses that res.locals data when rendering the page.
When you call req.logout(), nobody clears the res.locals that were already set when the user was still logged in so res.locals.user is now inaccurate.
So, when res.render() gets called after the logout, res.locals are still set as if the user is logged in and thus the page renders that way.
A simple solution is to clear the locals when you logout so they don't wrongly indicate the user is still logged in:
//routes/users.js
//logout
router.get("/logout",(req,res)=>{
req.logout();
// clear user before rendering to indicate logged out
res.locals.user = null;
req.flash("success_msg","You are logged out");
console.log(req.user);
res.render("users/login");
});

Login system using Passport.js is always executing “failureRedirect” (nodejs)

I'm doing a tutorial and I'm stuck in the login area. When I'm login in with Passport.js it always executing "failureRedirect" in authenticate.
After trying to debug replacing the router.post('login') route I received the following message:
Error: null User: false Info: {"message":"Missing credentials"}
After Reading on some forums I think that the problem could be related to body-parser. I've been trying to solve the problem but I haven't been able yet. I'd appreciate the help of a most experienced node.js programmer.
The structure of the project is:
app.js
routes:
users.js
models:
user.js
user.js
var express = require('express');
var router = express.Router();
var multer = require('multer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var User = require('../models/user');
var upload = multer({ dest: './uploads' });
// create application/json parser
var jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
/* 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'
});
});
router.post('/register', upload.single('profileimage'), function (req, res, next) {
//Get Form Values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
// Check for Image Field
if(req.files && req.files.profileimage){
console.log('Uploading File...');
// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}
// Form Validation
req.checkBody('name', 'Name field is required').notEmpty();
req.checkBody('email', 'Email field is required').notEmpty();
req.checkBody('email', 'Email not valid').isEmail();
req.checkBody('username', 'Username field is required').notEmpty();
req.checkBody('password', 'Password field is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
// Check for errors
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileImage: profileImageName
});
// Create User
User.createUser(newUser, function (err, user) {
if(err) throw err;
console.log(user);
});
//Success Message
req.flash('success', 'You are now registered and may log in');
res.location('/');
res.redirect('/');
}
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function (username, password, done) {
User.getUserByUsername(username, function (err, user) {
if(err) throw err;
if(!user){
console.log('Unknown User');
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function (err, isMatch) {
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {message:'Invalid Password'});
}
});
});
}
));
router.post('/login', jsonParser, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login',
failureFlash: true //'Invalid username or password'
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
router.post('/login', passport.authenticate('local', function(err, user, info) {
console.log("authenticate");
console.log(err);
console.log(user);
console.log(info);
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
module.exports = router;
user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
required: true,
bcrypt: true
},
email: {
type: String
},
name:{
type: String
},
profileimage:{
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.comparePassword = function(candidatePassowrd, hash, callback) {
bcrypt.compare(candidatePassowrd, hash, function (err, isMatch) {
if(err) return callback(err);
callback(null, isMatch);
});
}
module.exports.getUserById = function (id, callback) {
User.findById(id, callback);
}
module.exports.getUserByUsername = function (username, callback) {
var query = {username: username};
User.findOne(query, callback);
}
module.exports.createUser = function (newUser, callback) {
bcrypt.hash(newUser.password, 10, function (err, hash) {
if(err) throw err;
// Set hashed pw
newUser.password = hash;
// Create User
newUser.save(callback);
});
}
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle File Uploads
// app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
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
};
}
}));
// app.use(expressValidator({
// errorFormatter
// }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
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');
});
module.exports = app;
Files on Dropbox:
https://www.dropbox.com/sh/ex26xxo85lfo0my/AADET-j6Ift0q-y-ecWCRUEba?dl=0
Thanks for your help :)
Please check the code here on https://github.com/rupalipemare/Mongoose-Demo, wherein there is complete example demonstrating passport authentication.
First.. Please try to modularize code. Putting a functionalities in different files can help you track bugs faster. Second why are there two POST calls to login route? Remove the first one and no need to send jsonParser. Yo have declared to serialize and deserialize user. So passport will handle rest.

Categories

Resources