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'
});
}
});
});
}));
Related
I implemented a signup route below. It gets to "User saved..." but the request returns 404.
It doesn't seem to be executing the login strategy:
router.post("/signup", function(req, res, next) {
var email = req.body.email;
var password = req.body.password;
User.findOne({ email: email }, function(err, user) {
if (err) { return next(err); }
if (user) {
return res.status(409).send({message: "Duplicate user - already registered."});
}
var newUser = new User({
email: email,
password: password
});
newUser.save(next);
console.log("User saved...");
});
},
passport.authenticate("login"),
function(req, res) {
return res.status(200).send({
message: "Signup successful",
user: req.user
});
}
);
My Passport login strategy looks like this:
passport.use("login", new LocalStrategy(async (email, password, done) => {
console.log("login...");
User.findOne({ email: email }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: "No user has that email!" });
}
user.checkPassword(password, function(err, isMatch) {
console.log("Checked password...");
console.log("Error? Match?");
console.log(err);
console.log(isMatch);
if (err) { return done(err); }
if (isMatch) {
console.log("Returning done...");
return done(null, user, { message: 'Logged in Successfully' });
} else {
return done(null, false, { message: "Invalid password." });
}
});
});
}));
Here's what I see in the logs:
User saved...
POST /signup 400 181.122 ms - -
Passport is likely throwing the 400 error because the username/password fields are not set.
Passport expects username and password and what you are passing are the email and password. So you can modify the code and let passport's LocalStrategy use the email as the username.
You can set the username and password as follows:
passport.use("login", new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
},async (usernameField, passwordField, done) => {
console.log("login...");
User.findOne({ email: usernameField }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: "No user has that email!" });
}
user.checkPassword(passwordField, function (err, isMatch) {
console.log("Checked password...");
console.log("Error? Match?");
console.log(err);
console.log(isMatch);
if (err) { return done(err); }
if (isMatch) {
console.log("Returning done...");
return done(null, user, { message: 'Logged in Successfully' });
} else {
return done(null, false, { message: "Invalid password." });
}
});
});
}));
You can check the line which was throwing the error from passport's source code here
I'm writing an Express application that uses passport.js for authentication and I'd like to utilise express-session so that the user stays logged in if I call another endpoint. passport.authenticate and req.logIn both work, but when I call another endpoint, req.isAuthenticated() returns false and req.user is undefined
Here's my setup code for passport:
passport.use(new LocalStrategy(
function(username, password, done) {
db.all("SELECT * from users WHERE username='" + username +"'", function(err, rows) {
if (err != null) {
return done(err);
}
if (rows.length == 0) {
return done(null, false, {message: "No user found"});
}
var row = rows[0]
bcrypt.compare(password, row.password, function(err, res) {
if (err) {
return done(err)
}
if (res) {
return done(null, username)
} else {
return done(null, false, {message: "Incorrect password"})
}
})
})
}
))
passport.serializeUser((username, done) => {
done(null, username);
});
passport.deserializeUser(function(id, done) {
db.all("SELECT * from users WHERE username='" + id + "'", function(err, rows){
if (err != null) {
return done(err)
}
if (rows.length == 0) {
return done(null, false)
}
return done(null, id)
})
})
// add & configure middleware
app.use(session({
store: new SQLiteStore,
secret: my-secret
resave: false,
saveUninitialized: true
}))
app.use(passport.initialize());
app.use(passport.session());
This is my login endpoint
app.post('/login', function(req, res) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return res.status(500).json({ err })
}
if (!user) {
return res.status(400).json({
err: info.message
})
}
req.logIn(user, function(err) {
if (err) {
console.log(err)
return res.status(500).json({ err })
}
res.status(200).json({
msg: 'Success'
})
});
})(req, res)
})
Everything is fine at that point. It outputs the correct user ID.
I then call this endpoint:
app.post('/check-log-in', function(req, res, next) {
console.log(req.user)
console.log(req.isAuthenticated())
if (req.user) {
res.status(200).json({
loggedIn: true
})
} else {
res.status(200).json({
loggedIn: false
})
}
})
req.user is undefined and req.isAuthenicated() returns false.
I'm sure I've set up passport somewhere incorrectly but I've looked over examples and even some of code from another project that has worked but nothing seems to be doing the trick. Any advice?
This answer fixed my issue. It was a problem with fetch, so I switched to axios
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
});
This is my passport Login Handler.
Now I want to send JSON Data under every condition so that API can access the response and on behalf of this display anything on frontend.
//Login Handler
passport.use('local-user', new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) {
console.log('error')
logger.log('error', 'Error Generates on User.getUserByUsername Query on users.js file');
throw err;
}
if(!user){
//res.send('unknown user');
console.log('Unknown User');
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) {
logger.log('error', 'Error Generates on User.comparePassword Query on users.js file');
throw err;
}
if(isMatch){
return done(null, user);
}else{
return done(null, false, {message: 'Invalid Credential, please check carefully...!'})
}
});
});
}
));
Anyone have any idea for this? Thanks in advance
The local strategy will pass the user or error with done(), then you receive that with a callback and pack it with res.json()
Here is my implementation. May help?
passport.use(
new LocalStrategy(
{
usernameField: "email"
},
function(username, password, done) {
User.findOne({ email: username }, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
email: "Email not found"
});
}
if (!user.validPassword(password)) {
return done(null, false, {
password: "Password is wrong"
});
}
return done(null, user);
});
}
)
);
router.post("/login", function(req, res) {
passport.authenticate("local", function(err, user, info) {
if (err) {
res.status(404).json(err);
return;
}
if (user) {
const token = user.generateJwt();
res.status(200);
res.json({
userInfo: user,
token: token
});
} else {
res.status(401).json(info);
}
})(req, res);
});
I am trying for days to setup Passport on SPA page. On Client Side I am using AngularJS $http and generally it's working.
angular.module('Factory', []).factory('MainFactory', ['$http',function($http) {
return {
RegisterNewAccount : function(AccountInformation) {
return $http.post('/api/PageSignup', AccountInformation);
}
}
}]);
angular.module('Controllers', [])
.controller('MainPage', ['$scope','MainFactory', function($scope, MainFactory) {
$scope.Signup = function(){
var account = {
email: $scope.RegisterEmail,
password: $scope.RegisterPassword
};
MainFactory.RegisterNewAccount(account)
.success(function(data) {
console.log(data);
});
};
}]);
My problem is on server side code, i am new to passport and still cant figure it out how to make it work without redirect thing. My passport setup is below:
var passport = require('passport');
var LocalStrategy= require('passport-local').Strategy;
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
if (email) email = email.toLowerCase();
process.nextTick(function() {
if (!req.user) {
User.findOne({ 'local.email' : email }, function(err, user) {
if (err) return done(err);
if (user) return done(null, false, { message: 'That email is already taken.' });
else {
var newUser = new User();
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
newUser.save(function(err) {
if (err) return done(err);
return done(null, newUser);
});
}
});
} else if ( !req.user.local.email ) {
User.findOne({ 'local.email' : email }, function(err, user) {
if (err) return done(err);
if (user) {
return done(null, false, { message: 'That email is already taken.'});
} else {
var user = req.user;
user.local.email = email;
user.local.password = user.generateHash(password);
user.save(function (err) {
if (err)
return done(err);
return done(null,user);
});
}
});
} else {
return done(null, req.user);
}
});
}));
var app = express();
app.post('/api/PageSignup', function(req, res, next) {
passport.authenticate('local-signup', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
return res.send(info.message);
}
req.logIn(user, function(err) {
return res.send(user);
});
})(req, res, next);
});
If there are clear example on SPA Authentication with passport please show me.
Overwise can you show me where I am mistaking in my server side code?