How to disable passportjs authentication in local - node.js

I am testing my MEAN stack based app on my local. For authentication feature i am using passportjs.
But while debugging i have to login every time i restart the server.
Is there a easy configuration which i can do to disable passportjs without chaning much of my code.

I got it working with the following piece of code. Only following change was required to skip authentication for my app.
var isAuthenticated = function (req, res, next) {
var isAuthorised = req.isAuthenticated();
// TODO remove followoing on production code
// Set user as authorised in local
isAuthorised = true;
req.user = {};
// id of whichever account you want to load
req.user._id = '12345whatever';
if (isAuthorised) {
return next();
}
// if the user is not authenticated then redirect him to the login page
res.redirect('/login');
};
Hope it helps someone.

Related

googleapis oauth2.0 + passport for user registration - nodejs express application

I am using googleapis oauth2.0 for user registration on my website through through OAuth2.0. I get to the point where I get the access token and id token and save the new user in my database, from that point on I want to create a user session and I am trying to use passport for it but passport needs one of its strategies to implement which I do not need at this point because I already have verified user email and everything and have saved the user in my database all I now need to do is create a user session and send the user to the home page but there seems to be no way to just create user session without a strategy in passport.
here is my oauth2.0 redirect function where I get the access token etc.
router.get('/oauth-redirect', function (req, res, next) = > {
const data = await googleAuth.getToken(req.code);
const user = getUserInfoFrom(data);
const savedUser = save(user);
//here: use passport to create a session and send the user to home page ????
})
found the way to do it, there is req.login() function exposed by passport that you can use to manually log the user in.
router.get('/oauth-redirect', function (req, res, next) = > {
const data = await googleAuth.getToken(req.code);
const user = getUserInfoFrom(data);
const savedUser = save(user);
//this below is what will create a session and will set connect.sid cookie
req.login(savedUser, function(err) {
if (err) {
console.log(err);
}
return res.redirect('/home');
});
})

Block regular users from Google auth callback Express Route

I have the following program to log in with Google:
app.get('/oauth/google', function(req, res) {
res.redirect(<OAUTH2_URL>);
});
app.get('/oauth/google/callback', function(req, res, next) {
var code = req.query.code;
if(!code || !_.isString(code)) {
return next(new Error(400, 'Invalid code'));
}
.
.
.
// I try the code to see if it is valid.
});
How do I only allow Googles redirect back to the application to have access to the callback route, and block regular users from using it?
If you're using sessions then you could set a flag from your /oauth/google path before you redirect off to Google, and then on your /oauth/google/callback simply check for that flag, and reset.
app.get('/oauth/google', function(req, res) {
req.session.authFlag = true;
res.redirect(<OAUTH2_URL>);
});
app.get('/oauth/google/callback', function(req, res, next) {
if (!req.session.authFlag) return next(new Error(403, 'Forbidden'));
else req.session.authFlag = false;
...
});
If you're not using sessions though, or for some reason sessions aren't available because the client doesn't support cookies (which should be a concern in above mentioned solution as well!), then I guess your best bet is to just check for req.query.code because other than that query string (req.query.code) there's no difference between requests redirected by Google and direct requests made by regular user.
(...req.headers.referer/origin could've worked in theory but they're unreliable and shouldn't be used as a measure)

testing oauth authenticated routes

I'm using koa-passport & koa to handle my login and registration using twitter oauth. It works great, but I'm having difficulties understanding how I should test my authenticated routes using supertest and mocha.
Most examples I have seen involve using supertest to send a username and password to a login endpoint to first create a user session. My problem is that I don't have a username/passport auth strategy. I need to emulate an oauth login process that will set the appropriate session variables, and therefore test certain routes.
Any clue on how I can achieve this?
My solution these days to this problem is to basically insert a mock authenticated user in the middleware stack temporarily when needed. Here's my basic code for express.
var Layer = require('express/lib/router/layer');
var app = require('../../../server');
exports.login = login;
exports.logout = logout;
function login(user){
var fn = function insertUser(req, res, next){
req.user = user;
next();
}
var layer = new Layer('/', {
sesitive: false,
strict: false,
end: false
}, fn);
layer.route = undefined;
app._router.stack.unshift(layer);
}
function logout(){
app._router.stack.shift();
}
And then within your tests, you call:
it('should allow the user to edit something', function(done){
login(this.user);
// perform supertest task
logout();
});
This is obviously pretty rudimentary... but seems to do the job for testing purposes.

Parse.com redirect user depending on whether he's logged in or not (Express server)

I'm building a web app using Parse.com Express server and I'd like to redirect a user depending on whether he's logged in or not on the server side.
Is there an easy way to do this?
This is how I do it with Passport.js handling the session and loading the user for me.
If you are using another method, you may need to test something different than if(req.user).
function redirectIfAnon(req, res, next){
if(req.user){
return next(); // go to next handling function in middleware chain
} else {
var dest = encodeURIComponent(req.originalUrl);
res.redirect('/login?bounce='+dest)
// careful about redirect loops here... if you apply this middleware to /login,
// and an anonymous user visits /login, it will keep redirecting to /login
};
};
app.get('/test',
redirectIfAnon,
function(req, res){
// req.user is guranteed to be populated if we get here
parse.fetch(req.user.parseID, function(err...){
...
// or something. ive never used parse.com
res.render('parseResults');
})
});

accessing session variables in redirected file in node.js

I am building a crappy login system as a newbie. I have done this so far:
app.post("/verifyLogin",function(request,response){
var usr=request.body.username;
var pass=request.body.password;
userModel.find({$and:[{username:usr},{password:pass}]},function(err,user){
if(user.length==0)
{
response.redirect("/?msg=failed");
}
else
{
request.session.user=user;
response.redirect("/dashboard");
}
});
});
This works fine but after successful login i want to get the user details in the dashboard. I am clueless. Please shed some light.
EDIT
I have the following setup for dashboard in routes:
app.get("/dashboard",function(request,response){
response.sendfile('/lms/site/dashboard.html');
});
If you mean you want to pass the users' details to a template:
app.get('/dashboard', function(req, res) {
res.render('dashboard', {
user : req.session.user
});
});
This assumes a few things though:
you have a working templating setup;
you have a template called dashboard (with an extension matching your templating setup);
you're going to provide some sort of setup to make sure a user is logged in before they can open /dashboard.
EDIT: since you don't want to use templating, you could use AJAX to get the user details from the server into the client:
// server side
app.get('/userdata', function(req, res) {
// check if a user is logged in
...
// return the user details as JSON
res.send(req.session.user);
});
// client side (in 'dashboard.html', this assumes is will load jQuery)
$.getJSON('/userdata', function(user) {
// process user data, insert it into the DOM somewhere...
});
EDIT 2: to check if a user is logged in, you could create a middleware which would check for the existence of req.session.user and redirect to the login page if it's undefined:
var isLoggedIn = function(req, res, next) {
if (req.session && req.session.user)
next(); // user logged in, so pass
else
res.redirect('/'); // not logged in, redirect to login page
};
You would use the isLoggedIn middleware for all routes that require a user to be logged in:
app.get('/userdata', isLoggedIn, function(req, res) {
res.send(req.session.user);
});

Resources