anmol koul
anmol koul

Reputation: 512

Securing an API using passport-local

I will cut to the chase. I built a secure app using passport-local and all the routes are covered nicely. What my app does is fetch data from mongo and server it as an api which in turn feeds d3 charts. Now all my webpages are secure but i can access the api without logging into the app.

Here is how my pages are structured in route.js

    app.get('/dashboard', isLoggedIn, function(req, res) {
    res.render('dashboard.html', {
        user : req.user
    });
});

And this is how my api code looks like:

app.get('/api/finanData1', function(req, res) {
  // use mongoose to get all nerds in the database
  Subjects.find({}, {'_id': 0}, function(err, subjectDetails) {
   // if there is an error retrieving, send the error. 
       // nothing after res.send(err) will execute
   if (err) 
   res.send(err);
else
    res.json(subjectDetails); // return all nerds in JSON format
  });
 });

I tried modeling the api code but its not working out. Would really appreciate any help with this.

Thank you.

EDIT Answering the question for the isLoggedIn middleware, I modified my api code to:

     app.get('/api/finanData1', isLoggedIn, function(req, res) {
  // use mongoose to get all nerds in the database
  Subjects.find({}, {'_id': 0}, function(err, subjectDetails) {
   // if there is an error retrieving, send the error. 
       // nothing after res.send(err) will execute
   if (err) 
   res.send(err);
else
     // return all nerds in JSON format
    res.json(subjectDetails, { 
     user : req.user
        }); 
  });
 });

Now, when i try to access the api without being logged in, i am taken to the login page which is perfect. But upon logging in to the app my charts don,t populate. And if i open the api link while logged in i am getting this response instead of the json data that should be there:

 {"user":{"_id":"55f2f701f26336d85c28012b","__v":0,"local":{"password":"$2a$08$Z69k5PqxWQi5jxFNm2g/xOIAG/QG9L1ud/lO0kJHhDWQWPm2Zfl4e","email":"[email protected]"}}}

Should i share my server file as well?

Upvotes: 0

Views: 168

Answers (1)

Brandon Smith
Brandon Smith

Reputation: 1197

The response you're getting from your api is exactly what you're passing to the json response helper:

{ user : user_serialized }

Change your res.json line back to simply return the results:

res.json(subjectDetails)

If you need the user in addition to the data you'll have to return a more complex object and then map to the data property on the client to plot your chart:

var response = {
    data: subjectDetails,
    user: req.user
};

res.json(response);

Upvotes: 1

Related Questions