How to pass parameter from Express to Angular 6? - node.js

How can I pass parameter from Express route to A
`router.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.locals.username=req.user.username;
res.redirect('/home');
});`
This is what I have in the route for Express. I want to pass the username from here to the frontend that I have done in Angular and echo it.

You should return a JSON versus redirects and in the front-end side catch the response to render it.
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return res.json({ error: err });
}
if (!user) {
return res.json({ error: 'Authentication failed' });
}
req.logIn(user, function(err) {
if (err) {
return res.json(err);
}
return res.json({ username: user.username });
});
})(req, res, next);
});
I based in the Passport docs in the Authentication / Custom Callback section:
http://www.passportjs.org/docs/

Related

Passport.authenticate() Error handling inside a route?

If I want to handle errors from "incorrect" logins on this route how to collect (err) and where?
// POST LOGIN
usersRouter
.route('/login')
.post(passport.authenticate('local'), (req, res, next) => {
// for example, to declare an if here to catch err and call next with err...
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, status: 'You are successfully logged in!' });
});
You can use like this
usersRouter.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) {
return res.send(401,{ success : false, message : 'authentication failed' });
}
return res.send({ success : true, message : 'authentication succeeded' });
})(req, res, next);
});

Why does my MERN / Passport User Login not redirect on success?

When entering the correct login info, it does nothing. No error logs or redirect.
router.post("/login", (req, res, next) => {
passport.authenticate(
"local",
{ successRedirect: "/dashboard" },
(err, user, done) => {
if (!user) {
return res.json(done); //sends error msg ("email not registered", "password incorrect", etc.)
}
}
)(req, res, next);
});
What could be the issue for this?
passport.authenticate accept 2 parameters. If you choose custom callback, then removing { successRedirect: "/dashboard" }. Code example:
app.get('/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); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});

Node.js passport custom callback

I am using passport for my node.js app.
When I want to authenticate users local, I can simply do it
function local(req, res) {
req._passport.instance.authenticate('local', function(err, user, info) {
if(err) {
return workflow.emit('exception', err);
}
// and so on
res.end('some data');
}
}
But when I want to use facebook strategy, I must use redirectUrls like this.
function signinFacebook(req, res, next) {
req._passport.instance.authenticate('facebook')(req, res, next);
}
function facebookCallback(req, res, next) {
req._passport.instance.authenticate('facebook', {
successRedirect: '/',
failureRedirect: '/'
})(req, res, next);
}
This way I cant send with response data, that I am sending on local strategy.
Can anyone help me to fix it. I want not give success and failure Redirects, I want to call some function if all goes well like on local strategy.
I've found this in Passport's documentation, it may help.
app.get('/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); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.

Node/Express: Notify User that they have been redirected due to unauthorized access

Node newbie here
So I'm using Node(0.12.x) Express(4.x) & Passport(0.3.x) for authentication, and if the user accesses pages without the proper authentication a res.redirect('/login') will be preformed(by way of ensureLoggedIn('/login')). After a user is redirected to the login page I want to give the user some feedback to tell them they have been redirected ie. "You have been redirected due to unauthorized access, please login". How can I do this? My code below
app.get('/', require('connect-ensure-login').ensureLoggedIn('/login'), function(req, res) {
res.sendFile(path.join(html_dir + 'form.html'), {
user: req.user
});
});
app.get('/login', function(req, res) {
res.sendFile(path.join(html_dir + 'login.html'));
});
app.post('/login', urlencodedParser, function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return res.status(500).send({
success: false,
message: err
});
}
if (!user) {
res.statusCode = 200;
return res.status(200).send({
success: false,
message: "Incorrect username or password"
});
}
req.logIn(user, function(err) {
if (err) {
console.log(err);
return res.status(500).send({
success: false,
message: err
});
}
console.log("verified");
res.statusCode = 200;
res.setHeader("Location", "/");
return res.status(200).send({
success: true
});
});
})(req, res, next);
});

Use request and passport npm login account

I am using nodejs for a project,now I want login my account with passport npm,but not from webpage,from request post method,can it be done?
main code like this:
router.post('/login',function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.json(null); }
req.logIn(user, function(err) {
if (err) { return next(err); }
//return res.redirect('/'); redirect not work
});
})(req, res, next);
});
router.get('/check',function(req, res, next) {
request.post({
url:'http://localhost/login',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
form:{
username:'myname',
password:'mypassword'
}},function(err,httpRes,body){
//do here...?
return res.redirect('/');
});
});
When I call "check" with get method and use the correct username/password,I can print out the user data from database in "login" method,but lost the user session when it redirect home page.Any suggestion?
It's not redirecting the user when they GET /check because the POST request to /login in /check is getting redirected itself, not the actual user. Also making internal requests to internal webpages isn't the best solution for logging in. I suggest creating login() middleware like so:
// Don't forget to set req.body.username and req.body.password when calling login().
var login = function login(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return next(); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return next(null);
});
})(req, res, next);
};
And then calling it appropriately:
router.post('/login', login, function(req, res, next) {
if (req.user) {
console.log('We logged in successfully!');
res.redirect('/');
} else {
res.json(null);
}
});
router.get('/check', function(req, res, next) {
if (!req.user) {
login(req, res, function(err) {
if (err) {
return next(err);
}
if (!req.user) {
// No user, do some error handling.
} else {
// We have the user, do some custom stuff...
}
res.redirect('/');
});
} else {
// User is logged in already, do some other custom stuff...
}
});
You can check if a user is logged in by checking if req.user exists.

Resources