Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect a file directory and only allow authenticated users to access the files?

Tags:

meteor

how do I restrict a folder, so only those who logged in into my Meteor app can download files?

I looked into multiple ways of doing this, but the main problem is that I can't access ( I get null.) with:

Meteor.user() or this.userId()

I tried:

__meteor_bootstrap__.app
    .use(connect.query())
    .use(function(req, res, next) {
        Fiber(function () {  

          // USER HERE?

        }).run();
    });

or

__meteor_bootstrap__.app.stack.unshift({

    route: "/protected/secret_document.doc", // only users can download this

    handle: function(req, res) { Fiber(function() {

        // CHECK USER HERE ?

        // IF NOT LOGGED IN:
        res.writeHead(403, {'Content-Type': 'text/html'});
        var content = '<html><body>403 Forbidden</body></html>';
        res.end(content, 'utf-8');
    }).run() }
});
like image 694
vladikoff Avatar asked Dec 25 '12 01:12

vladikoff


1 Answers

You could try storing the files in mongodb, which would mean that they would then be hooked into your collection system and be queryable on the client and server. Then, just publish the relevant data to the client for specific users, or use Meteor.methods to expose information that way.

Example:

Assuming files are stored in MongoDB, let's first publish them to the client:

Meteor.publish("files", function(folder) {
  if (!this.userId) return;
  // the userHasAccessToFolder method checks whether
  // this user is allowed to see files in this folder
  if (userHasAccessToFolder(this.userId, folder))
    // if so, return the files for that folder
    // (filter the results however you need to)
    return Files.find({folder: folder});
});

Then on the client, we autosubscribe to the published channel so that whenever it changes, it gets refreshed:

Meteor.startup(function() {
  Meteor.autosubscribe(function() {
    // send the current folder to the server, 
    // which will return the files in the folder
    // only if the current user is allowed to see it
    Meteor.subscribe("files", Session.get("currentFolder"));
  });
});

NB. I haven't tested above code so consider it pseudocode, but it should point you in the general direction for solving this problem. The hard part is storing the files in mongodb!

like image 169
Rahul Avatar answered Oct 04 '22 21:10

Rahul