my app.js is
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
app.set('views', __dirname+'/views');
app.set('view engine', 'ejs');
app.use(bodyParser());
app.use(cookieParser());
app.use(session({secret : 'somthing'}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next){
res.locals.message = req.flash();
console.log(res.locals);
next();
});
app.use(require('./controller/router'));
// Default Controller Come Here
app.listen(3000, function(){
console.log('Running');
})
router.js is
var express = require('express');
var router = express.Router();
router.use('/', require('./home'));
router.use('/login', require('./login'));
router.use('/user', require('./user'));
module.exports=router;
passport.js (inside of config folder)
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../model/users');
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
done(err, id);
});
passport.use(new LocalStrategy(function(username, password, done){
if(username == "test#test.com")
/* hardcore check username and password */
{
if(password=="123")
{
var result = { id : 1, fullname : "james", username : "jamesjoel"};
console.log("Success");
return done(result, true);
}
return done(null, false, { message : "Incorrect Passwordtttt"});
}
return done(null, false, { message : "Incorrect Username and password"});
}
));
module.exports=passport;
and finaly my login.js controller is
var passport = require('../config/passport');
var express = require('express');
var router = express.Router();
router.post('/', passport.authenticate('local', {
successRedirect: '/user',
failureRedirect: '/login',
failureFlash: true
})
);
router.get('/', function(req, res){
console.log(req.flash());
res.render('login', { msg : req.flash()});
});
module.exports=router;
but when i send correct username and password it show in console "success" and show [Object Object] and successRedirect not working infact i wrote somthing on .serializeUser() and .deserializeUser() its also not showing on console....
so please help me for this .....
done is a callback and it takes first argument as an error. But in your case after success still you are passing value as error try to make it null like this return done(null,result, true)
if(password=="123"){
var result = { id : 1, fullname : "james", username : "jamesjoel"};
console.log("Success");
return done(null,result, true);
}
Related
I have been trying to build the authentication using PassportJs and MongoDB. I am using PassportJS only to log in. But, while submitting the post request it does not redirect me to the failureRedirect route, nor to the SuccessRedirect one, instead, the web page enters into an endless loop.
The code I have written is -
It has 2 files- app.js and user.js
App.js file -
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const passport = require('passport');
const mongoose = require('mongoose');
require('./db/db')
var fileupload = require('express-fileupload');
const path = require('path');
const app = express();
app.use(fileupload({
useTempFiles: true
}));
const session = require('express-session');
const mongostore = require('connect-mongo');
app.use(express.static(path.join(__dirname,'public')));
// session middle ware
app.use(session({
secret : 'mysupersecret',
resave : false,
saveUninitialized : false,
store: mongostore.create({
mongoUrl: process.env.DB,
}),
cookie : { maxAge : 180 * 60 * 1000 }
}));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static("public"));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
app.get("/", (req, res) => {
res.render("index");
});
app.use("/admin", require("./routes/admin"));
app.use("/user", require("./routes/user"));
app.use("/task", require("./routes/task"));
// PORT
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
User.js file -
const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router();
const bcrypt = require("bcryptjs");
const passport = require("passport");
const User = require("../models/User");
const Task = require("../models/Task");
var LocalStrategy = require('passport-local');
// var bcrypt = require('bcryptjs');
var strategy = new LocalStrategy(function verify(email, password, done) {
try{
console.log(email);
User.findOne({email: email}, function (err, user) {
console.log(email);
if (err)
console.log(err);
if (!user) {
console.log("doen exist")
return done(null, false);
}
bcrypt.compare(password, user.password, function (err, isMatch) {
if (err)
console.log(err);
if (isMatch) {
return done(null, user);
} else {
console.log("galat password");
return done(null, false);
}
});
});
}catch(err){
console.log(err);
}
});
passport.use('epass',strategy);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
// User login
router.get("/login", (req, res) => {
res.render("user-login");
});
router.post("/login", (req,res) => {
try{
passport.authenticate('epass', { failureRedirect: '/user/login' }),
function(req, res,next) {
res.redirect('/user');
}
}catch(err){
console.log(err);
}
});
router.get("/", (req, res) => {
res.render("user")
})
module.exports = router;
I have searched everywhere and tried all the available possible solutions but nothing is solving this.
passport.authenticate() should be used as a middleware, not as a regular function:
router.post("/login",
passport.authenticate('epass', { failureRedirect: '/user/login' }),
function(req, res,next) {
res.redirect('/user');
}
);
The way you were using it causes the request to POST /user/login to never finish, because it's not sending back any response.
EDIT: also, make sure that you either use the default field names of username and password for logging in, or add the relevant options to the constructor of LocalStrategy to tell it which fields it should be expecting.
I was trying to learn how to use passport-local with its documentation and I could do this, however when I submit the form it does not redirect to any site
const express = require("express");
const router = express.Router();
const passport = require("passport");
const localStrategy = require("passport-local").Strategy;
const UserList = [{ email: "1#1", password: "1" }];
passport.use(new localStrategy(async (email, password, done) => {
const thisUser = UserList.find(x => x.email = "email" && x.password == password);
return done(null, thisUser)
}));
router.get('/signup', (req, res) => {
res.render('auth/signup.hbs')
});
router.post('/signup', (req, res) => {
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
})
});
module.exports = router;
You forgot to initialize passport with
app.use(passport.initialize());
and serializeUser with
passport.serializeUser(function (user, done) {
done(null, user);
});
You can view the full example below. I did a test and it worked.
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var passport = require('passport');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var LocalStrategy = require('passport-local').Strategy;
app.use(morgan('dev')); // log tất cả request ra console log
app.use(cookieParser()); // đọc cookie (cần cho xác thực)
app.use(bodyParser()); // lấy thông tin từ html forms
app.set('view engine', 'ejs'); // cài đặt ejs là templating
app.use(passport.initialize());
const UserList = [{email: "1#1", password: "1"}];
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // cho phép chúng ta gửi reqest lại hàm callback
},
function (req, email, password, done) {
process.nextTick(function () {
const thisUser = UserList.find(x => x.email = "email" && x.password == password);
return done(null, thisUser)
});
}));
//
// routes ======================================================================
app.get('/', function (req, res) {
res.render('index.ejs'); // load the index.ejs file
});
app.get('/signup', function (req, res) {
res.render('signup.ejs');
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/',
failureRedirect: '/signup',
}))
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
I'm using passport with nodejs, express and EJS. I've created a authentication form but when I want to submit the server never responds and then resets the connection without any error message.
Here my server.js
var express = require("express");
var MongoClient = require("mongodb");
var bodyParser = require('body-parser')
var cons = require('consolidate');
var octicons = require("octicons");
var app = express();
var url = process.env.URL || "mongodb://localhost:27017/";
var dbName = process.env.DBNAME || "blog";
var port = process.env.PORT || 8000;
var routes = require("./routes");
var session = require('express-session')
var compte = require('./models/compte');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
require('./config/passport')(passport);
app.engine('html', cons.pug);
app.set('view engine', 'html');
app.set('views', __dirname + '/views')
app.use(express.static(__dirname + '/assets'));
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser());
app.use(session({ secret: 'simonahalepnumberone' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
MongoClient.connect(url, function(err, client) {
if(err) throw err;
routes(app, passport);
app.client = client;
app.db = client.db(dbName);
app.listen(port, function() {
console.log("now listening on http://localhost:" + port)
});
});
module.exports = app;
My index.js (which contains routes)
var posts = require("./posts");
module.exports = function(app, passport) {
function convertDate(dateString) {
var date = new Date(dateString);
return date.getDate()+"/"+date.getMonth()+"/"+date.getFullYear();
}
app.get("/", function(req, res) {
app.db.collection("articles").find({}).sort({date: 1}).toArray(function(err, result){
if(err) throw err;
result = result.reverse();
for(i = 0; i < result.length; ++i){
result[i].article = result[i].article.substr(0,75);
result[i].date = convertDate(result[i].date);
}
res.render("pages/index.ejs", {"articles": result})
});
});
app.get('/connexion', function (req, res, next) {
res.render("pages/connexion.ejs", { message: req.flash('connexionMessage') });
});
app.post('/connexion', passport.authenticate('local-login', {
successRedirect : '/',
failureRedirect : '/connexion',
failureFlash : true
}));
app.get('/deconnexion', function(req, res) {
req.logout();
res.redirect('/');
});
app.get('*', function(req, res){
res.render("pages/erreur404.ejs");
});
// Register posts endpoint
posts(app);
}
My passport.js
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/compte');
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-login', new LocalStrategy({
usernameField : 'pseudo',
passwordField : 'password',
passReqToCallback : true
},
function(req, pseudo, password, done) {
User.findOne({ 'local.pseudo' : pseudo }, function(err, user) {
if (err)
return done(err);
if (!user)
return done(null, false, req.flash('connexionMessage', 'Erreur dans le pseudo.'));
if (!user.validPassword(password))
return done(null, false, req.flash('connexionMessage', 'Erreur dans le mot de passe'));
return done(null, user);
});
}));
};
And my model for the user account
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var compteSchema = mongoose.Schema({
local : {
pseudo : String,
password : String,
}
});
compteSchema.methods.genererHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
compteSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
module.exports = mongoose.model('utilisateur', compteSchema);
I've follow this tutorial so I don't understand why it's not working
link
I have a login created in Express with the use of Passport.js. Now I have everything setup and when username and password are correct it will redirect to the user page. But now I want to show a message when the credentials are incorrect. Right now it leads to a blank page with an auto message of 'unauthorized'
This is my passport.js setup:
App.js:
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/homeapp');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
app.use(require('express-session')({
secret: 'testtest',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
var User = require('./models/User');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
Index.js
var express = require('express');
var router = express.Router();
var auth = require('../controller/AuthController.js');
router.get('/', auth.home);
router.get('/login', auth.login);
router.post('/login', auth.doLogin);
router.get('/logout', auth.logout);
module.exports = router;
Users.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var UserSchema = new Schema({
username: String,
password: String
}, {collection: 'userdata'});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', UserSchema);
AuthController.js:
var mongoose = require("mongoose");
var passport = require("passport");
var User = require("../models/User");
var userController = {};
userController.home = function(req, res) {
res.render('index', { user : req.user });
};
userController.login = function(req, res) {
res.render('login');
};
userController.doLogin = function(req, res){
passport.authenticate('local')(req, res, function(){
res.redirect('/');
});
};
userController.logout = function(req, res) {
req.logout();
res.redirect('/');
};
module.exports = userController;
You can do modification in your code like this :
userController.doLogin = function(req, res){
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login',
failureFlash: true })
passport.authenticate('local', { failureFlash: 'Invalid username or
password.' });
};
Setting the failureFlash option to true instructs Passport to flash an error message using the message given by the strategy's verify callback, if any. This is often the best approach, because the verify callback can make the most accurate determination of why authentication failed.
As ,i have seen you are using passport custom callback method for this you can do like this:
userController.doLogin = function(req, res){
passport.authenticate('local', function(err, user) {
if (err) { return next(err); }
if (!user) { return res.json('invalid credentials'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/');
});
})(req, res);
};
I have a middleware isAuthenticated to ensure that the user is logged in before he can post a comment:
function isAuthenticated(req,res,next) {
req.isAuthenticated ? next() : res.redirect('/login');
}
This middleware is suppose to be running here:
router.post('/cat/:id', isAuthenticated, function(req,res) {
console.log('not suppose to be here');
var id = req.params.id;
Cat.findById(id, function(err, cat) {
if (err) {
console.log(err);
} else {
var id = req.params.id;
var comment = new Comment({
username: req.user.username,
content: req.body.content
});
//more code
However, when I try to post a comment without logging in, my app crashes and the console shows the following:
not suppose to be here
username: req.user.username,
^
TypeError: Cannot read property 'username' of undefined
I refactored all the routes into a separate file, and exported it to app.js. All routes pertaining to cats are stored in cats.js:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var Cat = require('../models/cat.js');
var Comment = require('../models/comment.js');
var mongoose = require('mongoose');
router.use(function(req,res,next) {
res.locals.user = req.user;
next();
});
function isAuthenticated(req,res,next) {
req.isAuthenticated ? next() : res.redirect('/login');
}
router.get('/cat/:id', function(req,res) {
var id = req.params.id;
Cat.findById(id, function(err, cat) {
if (err) {
console.log(err);
} else {
Comment.find({}, function(err, comments) {
if (err) {
console.log(err);
} else {
res.render('show', {cat:cat, comments:comments});
}
});
}
});
});
//more code
module.exports = router;
app.js:
var app = express();
var bodyParser = require('body-parser');
var config = require('./config/config.js');
var mongoose = require('mongoose');
var Cat = require('./models/cat.js');
var Comment = require('./models/comment.js');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var passportLocalMongoose = require('passport-local-mongoose');
var User = require('./models/user.js');
mongoose.connect(config.dbURL, function(err) {
if (err) {
console.log(err);
} else {
console.log('successfully connected to database!');
}
});
app.set('view engine', 'ejs');
app.use(session({
secret:"sfsdfsdfsd",
resave: false,
saveUninitialized: false
}));
app.use(bodyParser.urlencoded({extended:true}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.engine('html', require('ejs').renderFile);
app.use(express.static('public'));
var authRoutes = require('./routes/auth.js');
var catRoutes = require('./routes/cats.js');
app.use(authRoutes);
app.use(catRoutes);
Why is my middleware being bypassed? Please ask for additional code if it's needed.
Edit1: Updated to provide more information.
I solved the problem. I just forgot to call req.isAuthenticated in my middleware. I had it as:
function isAuthenticated(req,res,next) {
req.isAuthenticated ? next() : res.redirect('/login');
}
Whereas it should have been req.isAuthenticated().