Hiding the JSON payload from /api and auth/ routes - node.js

Is there a way to protect the api route when a user enter that in the url? Please see my screen shot. I know there's a way to authenticate a user in the backend using a middleware but it seems like if the data can be viewed publicly, the JSON payloads can also be viewed publicly. I'm still new to this, so forgive me if this question has already been asked. I use Node.js, React, Express and Sequelize.

I'm assuming that you do not want your /api/users route to be accessible to the public, I think this solution should work, although there might be better solutions.
You can try protecting specific routes based on the role of the user. I suggest you add a user_role field to your user schema, and create a middleware function that only allows logged in users with a specific role to access the route, as shown in the pseudo code below:
function (req, res, next) {
// Check if user is logged in and is assigned the role you want to allow.
if(user is logged in) return next();
else throw error;
}

Related

how to give user specific file access in express js

I'm using express js and passport js as authentication system also using view engine. I'm looking for a solution that would give access to user and let users see their file, not the other one's file. for example, in the image folder, the user would access to their files and after that, I want to pass these files to view engine. If I use the public folder, anyone is able to see every file in there. what solution do you recommend?
You should create a directory for each users.
then, for example, your URL is /show/files
the inside your logic, filter the directory by user info.
app.get('/show/files', (req,res)=>{
// filter resources by user info
})
don't forget to create a secure URL for your resources.
Bad Idea: /images/amin/profile.png
Good Idea:
create a route to serve your resources.
app.get('/resources', (req,res)=>{
// add query parameter for resource for example profile.png
// then check user directory and send it
})
your url converts into
/resousrce?file=profile.png
I assume you already have a login system in place, so all you have to do, is create a middleware that checks if the user is logged in, and checks if the image is his image.
app.use("/user/:user/**",function(req,res){
if (req.params.user == thisuser){
//serve the file
} else {
res.status(403); //access denied
res.end();
}
//check based on cookies whether the user has the permission to view this image
});
I would suggest you to use Passport.Js local authentication. You can look into the official docs - http://www.passportjs.org/docs/authenticate/ I personally have used this in the same scenario you're in.
Here is a litte code snippet of the custom middleware function I wrote using passport -
module.exports = {
ensureAuthenticated : function(req, res, next){
if(req.isAuthenticated()){
return next();
}
req.flash('error_msg', 'Please login to view this resource.')
res.redirect('/users/login');
}
}
Feel free to check the entire solution on my github repo -
https://github.com/StechAnurag/loginsys

KeyStone JS Account Controller

I understand MVC structure when coding in NodeJS. I started using Keystone JS recently, and I really like it. But, the way they set their controllers up, it seems that the controllers ONLY serve the purpose of rendering a view.
In an earlier project, I had an Account.js model and an Account.js controller. I'm trying to see how it would copy over to keystone.
So: How would I allow users to signup/signin/logout in a Keystone project (not into the Admin UI, but like a member of a regular site)? How would I make an Account controller (obviously with no view to render)?
There are lots of ways you can implement your own methods of authentication and account management in keystone since it is based on express.js.
You can then add an array of 'middleware' functions to routes which will run before passing the request to the controller.
e.g
Route before middleware added
app.get('/admin', routes.views.userAdmin);
Middleware Function
function isAuthenticated(req, res, next) {
// do any checks you want to in here
// CHECK THE USER STORED IN SESSION FOR A CUSTOM VARIABLE
// you can do this however you want with whatever variables you set up
if (req.user.authenticated)
return next();
// IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
res.redirect('/');
}
Route with middleware added
app.get('/admin', isAuthenticated, routes.views.userAdmin);
It's a very broad questions so I'd recommend you go and decide on the best way you'd like to do it yourself as everyone has their own personal preference. The search terms you want are 'express middleware authentication'. A lot of people use PassporJS http://passportjs.org/
Hope that helps :)

Express JS routing based authentication

I have created node js app using express framework.
I have created middleware for restricting access to some routes.
Middleware actually works fine. but i have difficulties in displaying data.
Suppose In My app i have created route for display list of countries('/country/master')i.e html page which is using internally different/default route ('/country/') to get data from mongoDB.
In this case user will not able to see data cause i have not given permission to "/" routes. but i want to display data but not allow him to make use of "/" route to check data.
How can i deal with this case ????
The answer depends on your authentication strategy i.e. are you using session identifiers, access tokens, etc.
In either case I suggest that you break out the credential exchange (aka login) from the authentication. They should be separate middleware functions. Below is an example of what this looks like.
While this answers your question, specific to ExpressJS, it does leave out a lot of other details that matter when you are building an authentication system (like how to securely store passwords). I work at Stormpath, we provide user management as an API so that you don't have to worry about all the security details! It's very easy to integrate our API into your application, using the express-stormpath module. You'll have a fully featured user database in minutes, without having to setup mongo or a user table.
All that said, here's the example:
/* pseudo example of building your own authentication middleware */
function usernamePasswordExchange(req,res,next){
var username = req.body.username;
var password = req.body.password;
callToAuthService(username,password,function(err,user){
if(err){
next(err); // bad password, user doesn’t exist, etc
}else{
/*
this part depends on your application. do you use
sessions or access tokens? you need to send the user
something that they can use for authentication on
subsequent requests
*/
res.end(/* send something */);
}
});
}
function authenticate(req,res,next){
/*
read the cookie, access token, etc.
verify that it is legit and then find
the user that it’s associated with
*/
validateRequestAndGetUser(req,function(err,user){
if(err){
next(err); // session expired, tampered, revoked
}else{
req.user = user;
next();
}
});
}
app.post('/login',usernamePasswordExchange);
app.get('/protected-resource',authenticate,function(req,res,next){
/*
If we are here we know the user is authenticated and we
can know who the user is by referencing req.user
*/
});
You can positioning of middleware in you app.for example:-
app.get('/country/master',function(req,res){
})
app.use(function(req,res){
your middle ware for providing authentication
})
// other routes where authentication should be enabled
app.get('other urls')

How to check if user is already logged into instagram

I am currently using node.js, express, and mongodb for an instagram app. I have found that many times I would like to know whether or not a user is already logged into instagram (be it through my app via the instagram-node authentication or through instagram's actual website).
Is there an easy way to do this?
I ended up using passport to solve this problem. Passport conveniently takes care of handling instagram authorization and they even include an example app to see how it all works. https://github.com/jaredhanson/passport-instagram/blob/master/examples/login/app.js
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
Is especially useful since it can be placed at the top of your routing file and all the routes underneath it will first check to see if the user is authenticated.

Authenticate before calling route controller

I'm working on an API using restify. There will be a dozen or more endpoints and each one requires authentication. The API will be stateless, so each API request, regardless of endpoint, will pass credentials.
What I'd like to do, if possible, is to authenticate before negotiating the route. Otherwise, if I have a route:
server.get('/activities', activities.index);
Then, within activities.index (and every other routing method), I have to duplicate the following:
var user = require('../models/user')(server);
user.authenticate(req.authorization, function(err, user) {
...
// Do the real activities-related stuff.
});
This is one of those things where it feels like there must be a better way of doing it, but I don't know what it is.
Anyone have any thoughts?
So you can register handlers to be ran before every route is ran.
http://mcavage.me/node-restify/#Common-handlers:-server.use()
server.use(function(req, res, next){
//do authentication here
if(authenticated){
return next();
}
else{
res.send({auth:false});
})
So when you use server.use when the user asks for /activites it will run all of the server.use you created in the order you created them before running the code for the route.

Resources