I have a problem with passport.js, when I try to log into my account, I get an error: Error: Unknown authentication strategy "local-login". ". What's wrong with my code, thank you.
config/Passport.js
var passport = require('passport');
var request = require('request');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user'); // model User
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(function(username, password,
done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { msg: "Username" + username + "not found."
});
}
user.comparePassword(password, function(err, isMatch) {
if (err) { return done(err); }
// Make sure the user has been verified
if (isMatch) {
return done(null, user);
}
return done(null, false, { msg: 'Invalid email or password.' });
});
});
}));
app.js
var session = require('express-session');
var passport = require('passport');
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1*15*1000 }
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.user;
next();
});
routes/authRoutes.js
app.post('/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if (err) { return next(err); }
if (!user) {
return res.redirect('/login');
}
req.login(user, function(err) {
if (err) { return next(err); }
res.redirect('/');
});
})(req, res, next);
});
It must be 'local' instead of 'local-login'
module.exports.login_post = passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true
});
I Use MySQL. It's the complete code:
passport.use(new LocalStrategy({
passReqToCallback: true
}, function(req, username, password, done) {
pool.query("SELECT * FROM user WHERE username = ?",[username], function(err, rows, fields) {
if (err) throw err;
console.log('checked');
if(!isExist(username) || !isExist(password)){
return done(null, false, req.flash('message_err', 'Username and password cant be emptied!.'));
}
if (!rows[0]) {
return done(null, false, req.flash('message_err', 'Oops! Username or password didnt match.'));
}
if (!bcrypt.compareSync(password, rows[0].password)) {
return done(null, false, req.flash('message_err', 'Oops! Username/password didnt match.'));
}
return done(null, rows[0]);
});
}));
passport.deserializeUser(function(user, done) {
console.log('user : ' + user);
pool.query("SELECT * FROM user WHERE username = ?", [user], function(err, rows, fields) {
if(err) throw err;
console.log('deserialized');
done(err, rows[0]);
});
});
//serialize and deserialize passport
passport.serializeUser(function(req, user, done) {
console.log('serialized');
done(null, user.username, req.flash('message_success', 'Welcome, '+user.username + "!"));
});
module.exports.login_post = passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true
});
Related
I have made a user register and login but I couldnt understand why req.user shows undefined.
I couldnt understand why it shows undefined.
I have middleware of :
app.use(passport.initialize());
app.use(passport.session());
And also I have middleware of body-parser
This is my register(post):
app.post('/register',[
// username must be an email
check('kullanici_adi').notEmpty(),
// email must be at least 5 chars long
check('email').isEmail(),
// email must be at least 5 chars long
check('sifre').notEmpty(),
], async (req, res) => {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.sifre, salt);
let kullanici = new Kullanici({
kullanici_adi: req.body.kullanici_adi,
email: req.body.email,
sifre: hashedPassword,
});
const errors = validationResult(req);
if (!errors.isEmpty()) {
req.flash('danger', 'Bütün Alanların Doldurulması Zorunludur');
res.render('kayit', {
});
}
kullanici.save(function(err) {
if (err) {
console.log(err);
} else {
res.redirect('/');
}
});
});
This is my login parts:
app.get('/login', function(req, res){
res.render('login');
});
app.post('/login', (req, res, next) => {
passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/',
failureFlash: true,
}) (req, res, next);
});
app.get('/logout', function(req, res){
req.logout();
req.flash('success', 'You are logged out');
res.redirect('/login');
});
And this is passportjs configure part:
passport.use(new LocalStrategy({
usernameField: 'kullanici_adi',
passwordField: 'sifre'
},
function(username, password, done) {
Kullanici.findOne({ kullanici_adi: username }, function (err, kullanici) {
if (err) { return done(err); }
if (!kullanici) {
return done(null, false, { message: 'Incorrect username.' });
}
bcrypt.compare(password, kullanici.sifre, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, kullanici);
} else {
return done(null, false, {message: 'Wrong password'});
}
});
});
}
));
passport.serializeUser(function(kullanici, done) { done(null, kullanici.id); });
passport.deserializeUser(function(id, done) { Kullanici.findById(id, function(err, kullanici) { done(err, kullanici); }); });
When I console.log(req.kullanici) in my index or post routes then it says undefined. But at the same time this undefined user can pass through ensureAuthenticated parts of my website.
Note: Some words meaning in English:
Kullanici = User,
kullanici = user,
kullanici_adi = username,
sifre = password,
email = email,
Can someone help met? Why it is being happened and how to solve this issue?
Full code:https://github.com/michelson/dante2/issues/229
Please, I'm trying to redirect to the "edit user route" page after login but the req.user._id is showing undefined, any idea what's wrong here?
login router
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect:'../profiles/edit/' + req.user._id, <<<< **UNDEFINED**
failureRedirect:'./login',
failureFlash: true,
})(req, res, next);
});
passport.js
module.exports = function(passport) {
passport.use(new LocalStrategy({
},
(username, password, done) => {
Profile.findOne({
username:username
}).then(user => {
if(!user) {
return done(null, false, {message: 'No user found'});
}
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {message: 'Password Incorrect'});
}
})
})
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
Profile.findById(id, function(err, user) {
done(err, user);
});
});
}
app.js
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
I'm getting:
TypeError: Cannot read property '_id' of undefined
You can't get user details in the authenticate method, it will check if username has been found and then pass it to the next middleware
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
// here you can access user info
res.redirect('../profiles/edit/' + req.user._id);
});
I'm trying to get a handle on user authentication with PassportJS, and I cannot get it to work my database setup.
I'm using MongoDB without Mongoose, and I can't get the LocalStrategy module to work.
Hopefully my database queries aren't too cumbersome to read.
Local Strategy:
passport.use(new LocalStrategy(
function(username, password, done) {
//Fire up database
mongo.connect("mongodb://localhost:27017/formulas", function(e, db) {
if (e) {return next(e);}
var col = db.collection("users");
//Do a database query to find a record by username
col.findOne({"username": username}, function(err, user){
if (err) { return done(err);}
if(!user) {
return done(null, false, { message: "Please check your log in credentials." });
}
//if it exists call done() object with user information
bcrypt.compare(password, user.password, function(err, res){
if (err) throw err;
if (res == true) {
return done(null, {username: username, password: password});
} else {
return done(null, false, { message: "Invalid password."});
}
});
});
});
}));
I call passport.authenticate() like this:
router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/about',failureFlash: false}),
function(req, res){
console.log(req.body);
console.log(req.user);
console.log("The user was logged");
});
SerializeUser and deserializeUser look like this:
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(id, done) {
mongo.connect("mongodb://localhost:27017/formulas", function(e, db){
if (e) {return next(e);}
var col = db.collection("users");
col.findOne({"username": id}, function(err, user){
done(err, {"username": id});
});
});
});
When I call app.post(/login) I'm taken directly to /about and nothing is logged to the console so I'm not quite sure what's going wrong.
Advice on what to fix or how to troubleshoot is greatly appreciated.
Firstly when u serialize user object , then in deserialize also whole user object must be passed.
Consider the example below.
For routes :
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
req.session.user = req.user;
return res.redirect('/home');
});
})(req, res, next);
});
For passport.js , place the localstrategy and passport in same folder
var passport = require('passport'),
session = require('express-session');
var local = require('./localstrategy.js');
module.exports = function (app) {
app.use(session({
secret: 'Site visit',
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done){
done(null, user);
});
passport.deserializeUser(function(user, done){
done(null, user);
});
local();
};
For local strategy :
'use strict';
var passport = require('passport'),
local = require('passport-local').Strategy;
var user;
// path where the db.js is placed
var db = require('./../db.js');
var ObjectId = db.getObjectID();
var bcrypt = require('bcrypt');
module.exports = function(){
passport.use(new local({
usernameField : 'username',
passwordField : 'password'
}, function(username, password, done){
var collection = db.getDb().collection('users');
collection.findOne({
username: username,
}, function (err, result) {
if(result == null){
cb(null, false);
}else {
bcrypt.compare(password, result.password, function (err, passRes) {
if (passRes == true) {
user = user;
done(err, user);
}else{
done(null, false, { message : 'Invalid Password'});
}
});
}
});
}));
};
I am building app using MEAN STACK. I want to use passport-local authentication for my login form. But a the time of form submission i am getting POST http://localhost/login 404 (Not Found) please have a look of my code below This is my controller:
lyfee.controller('loginCtrl', ['$scope', '$http', function($scope, $http) {
$scope.user = {};
$scope.login = function() {
// var data = {User: $scope.user }
//console.log($scope.user);
console.log("login function call");
$http.post('/login', $scope.user);
console.log("login request send");
}
}]);
and this is my server.js :
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByusername(username, function(err, user) {
if (err) throw err;
if (!user) {
return done(null, false, {
message: 'Unknown USER'
});
}
User.comparePassword(password, user.password, function(err, isMatch) {
if () throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {
message: 'Invalid password'
});
}
});
});
}));
app.post('/login',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}),
function(req, res) {
res.redirect('/');
});
in which file should i write getUserByusername and comparePassword function ? and what is mistake i am doing please correct it and give me some suggestion.
In your model suppose that User.js write functions like this:
/**
* Check the user's password
*/
dbSchema.methods.comparePassword = function(candidatePassword, cb) {
var status = this.password.localeCompare(candidatePassword.trim());
if (status != 0) {
return cb(err);
}
cb(null, true);
};
then use the function like this
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({
username: username
}, function(err, user) {
if (err) throw err;
if (!user) {
return done(null, false, {
message: 'Unknown USER'
});
}
/**
* Check the user's password
*/
User.comparePassword(password, user.password, function(err, isMatch) {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {
message: 'Invalid password'
});
}
});
});
}));
I have a Node.js Express App and I am trying to use MongoStore to save the sessions and Passport-local for authentication. The app is not storing sessions in db.sessions
app.js
var session = require("express-session");
var MongoStore = require("connect-mongo/es5")(session);
var passport = require('passport');
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false,
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
store: new MongoStore({
url: MongoDB.MONGODB_URL
})
}));
app.use(passport.initialize());
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
db.users.findById(id, function(err, user){
if(!err) done(null, user);
else done(err, null);
});
});
localstrategy is implemented as follows. MongoDB is my own module which interacts with MongoDB.
passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, done) {
process.nextTick(function () {
MongoDB.collection("users").findOne({
email: email
}, function (error, doc) {
if (error) {
return done(error);
}
if (doc) {
if (doc.password === PasswordManager.encryptPassword(password)) {
return done(null, doc);
} else {
return done("Invalid Password", false);
}
}
});
});
}
));
Authentication Request.
As I am trying to use MongoStore sessions, I have passed the option - {session: false} to the req.LogIn function.
router.post('/login', function (req, res, next) {
passport.authenticate('local', function (err, user) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).send({
success: false,
error: "User not found!",
data: null
});
}
req.logIn(user, {session: false}, function (err) {
if (err) {
return next(err);
}
req.session.user = user;
return res.send({
success: true,
error: null,
data: user
});
})
})(req, res, next);
});