Autologin with node.js, express and DaftMonk/generator-angular-fullstack - node.js

Please, help to figure out the best way to autologin user with passport.js local in MEAN stack applications by DaftMonk https://github.com/DaftMonk/generator-angular-fullstack
I want to login user right after saving him. The following code doesn't help
passport.authenticate('local', function (err, user, info) {
var error = err || info;
if (error) return res.json(401, error);
if (!user) return res.json(404, {message: 'Something went wrong, please try again.'});
var token = auth.signToken(user._id, user.role);
res.json({token: token});
})(req, res, next)
Thanks!

Are you tried to review signup module? Its login the user automatically after registering.

Related

node js jwt how to pass token to other routes to check logged user information later

I'm creating an application learn for my self. So at the moment i need to authenticate an user using with jsonwebtoken and i know how to create a token to authenticate a user. So actually i need to know how can i retrieve logged users's information later by using the token created by the user when logged into the system. i searched everywhere for a good answer but i couldn't find a good answer
apiRoutes.post('/authenticate', function(req, res) {
// find the user
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {
// check if password matches
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
} else {
// if user is found and password is right
// create a token
var token = jwt.sign(user, app.get('superSecret'));
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
});
this is the user login and token creation process
and the below router i need to retrieve all the user information if the user logged into the system and created the token
apiRoutes.get('/users', function(req, res) {
if(!loggedinUser){
//throw err
}
else {
User.find({}, function(err, users) {
res.json(users);
});
});
}
so please help me to understand this and i hope you guys provide me a good answer for this question
thank you
Once your authorisation token is generated you need to send that token in all requests through client side.
On the the server side you need to implement a authentication middleware in this you will check the authentication token. and process that request further
check this link
How to use the middleware to check the authorization before entering each route in express?
Add User login token in to req.session.token then check it in jwt middle ware .

Passport deserialize function is removing user from the session

To be frank, I just started learning passport today. I feel I understand some of how passport is working, but I'm still trying to familiarize myself. My problem here (I think) is that my user is getting removed from the session, which is preventing me from reaching my authenticated routes. I console.logged the user id in the deserialize function to check if it was getting stored in the session, and it is ...
//serialize user into the session
passport.serializeUser(function(user,done){
done(null,user.id);
});
//deserialize the user from the session
passport.deserializeUser(function(id,done){
console.log('user id is: ' + id); //works and logs user id
User.findById(id, function(err,user){
done(err,user);
});
});
Here are my routes and passport middleware ...
app.post('/login', function(req,res,next){
passport.authenticate('local-login', function(err,user,info){
if(err){
console.log("we have an internal error!");
return next(err);
}
if(!user){
return res.send({success:false, message:'failed to login!'});
}else{
req.login(user, function(err){
if(err){
return next(err);
}
return res.send({ success : true, message : 'authentication succeeded' });
});
}
})(req,res,next);
});
//route middleware to make sure that a user is logged in
function isLoggedIn(req,res,next){
//if the user is authenticated in the session, carry on
if(req.isAuthenticated()){
next();
}
//if they are not authenticated in the session, redirect them to the home page
res.redirect('/');
}
Any help, insights, advice is greatly appreciated; thanks!
It's because you're always redirecting the user to the index page in your isLoggedIn middleware. Need to use return:
function isLoggedIn(req,res,next){
if(req.isAuthenticated()){
next();
// STOPS further execution of this function and prevents redirecting the user
return;
}
res.redirect('/');
}
Keep in mind that it's just JavaScript - no framework does any changes - Express, Passport, even Promises are pure JS and they don't modify the way the virtual machine works. GL!
p.s.
If things go wrong, especially in the beginning, I recommend using if-else statement. You wouldn't have problems this way:
if (req.isAuthenticated()) {
next();
} else {
res.redirect('/');
}

Passportjs local strategy returns 'invalid credentials', is there any way to override this?

passport has been a real thorn in my side lately. I'm trying to register a user and have a custom callback. However, if the user doesn't supply a username and password and just submits the form I get back an 'invalid credentials' error. I would like to intercept this before then so I can format it like the rest of my error messages, and send it back.
Is there any way to do this? I dug through passport and couldn't find anything.
You can make that happen on the callback, look at this example (not pretty code but it illustrates the idea well). In this case, if the user credentials are valid but the user has not confirmed their email address, I am returning a flash object to notify the user of the error. You could also make user of the /success or /failure options on passport to call specific url's upon a success or failure of authentication.
app.post('/login', function(req, res, next){
passport.authenticate('local', function(error, user, info){
if(error){
//handle error here
}
else{
if(!user){
res.status(404).end();
} else{
req.logIn(user, function(error){
if(error) return res.status(500).end();
if(!user.isEmailConfirmed){
req.session.flash = {
type: 'warning',
intro: 'Achtung',
message: 'error message'
};
res.redirect('/');
}
else res.redirect('/');
});
}
}
})(req, res, next);
});

How to log in with passport.js after resetting the password in Node.js?

I am working with passport.js for authentication.
I have an issue which I want to resolve:
Whenever user want to reset his password, I send an email of password reset link to him with token id.
And he can reset his password after clicking that link, but after resetting password,
I want the user being redirect to dashboard page instead of log in page.
I try to find out solution with passport.js but didn't get any luck.
Can someone give me any idea to resolve this issue?
Thank You
when the user resets the password you need to authenticate the user on user's behalf.
Code would look something like this
app.post('/resetpassword', function(req, res, next) {
/*
code to reset the password
*/
// append username and new password to req.body
// assuming passport still uses username and password as field indicator
req.body.username= "user_name";
req.body.password= "user_new_password";
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.sendStatus(401); }
// it is your responsibility to establish the session
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.rediect("to_users_dashboard_path");
});
})(req, res, next);
});
Note: while using custom callback, it is applications responsibility to establish the session, see Custom Callback

Passport.js Session Confusion

I am learning node and express. I am trying to build a very basic app that will simply let a user log in using json. Then will maintain session until they log out. With asp.net this is a doddle you just set it up in the config and call...
Auth.Login(username,pasword)
When they log out you just do:
Auth.logout()
And if you need to check if they are logged in you simply do:
Auth.IsLoggedIn()
Or code to that effect. Well seems like Passport for node is just not that simple. I spent all night getting this working...
app.post('/authentication/login', function handleLocalAuthentication(req, res, next) {
passport.authenticate('local', function(err, user, info) {
// Manually establish the session...
req.login({username:'me#me.com',password:'password'}, function(err) {
if (err) return next(err);
return res.json({
message: 'user authenticated'
});
});
})(req, res, next);
});
app.get('/authentication/isauthenticated',function(req,res){
console.log(req.isAuthenticated());
})
passport.use(new LocalStrategy(
function(username, password, done) {
return done(null, {username:'ss',password:'sffds'});
}
));
So now I have no cookies, no session persisted when I login and then hit the /authentication/isAuthenticated url. I can't even get a breakpoint to stop in the strategy...
passport.use(new LocalStrategy(
function(username, password, done) {
console.log('ggg');
return done(null, {username:'ss',password:'sffds'});
}
));
Am I looking at the wrong solution for this? Should I be rolling my own auth or something with a basic middleware function?
Check out this tutorial. It's really great and it helped me a lot.
And here's my repo which has implemented passport authentication with users stored in mongodb through mongoose, and hashed passwords. Clone it or just check it out, it should help.
https://github.com/thyforhtian/auth_base.

Resources