简体   繁体   中英

restricting access to user uploaded files in nodejs?

i am creating a Node.js/Express app that allows users to upload files(pictures, sounds...) but i don't want the users to just type in the file URL and access it, i want to confirm user identity and whether the user is the owner of that file and i had a few ideas on how to do it

  • make the files name unpredictable like by adding a UUID or something like that(but doesn't really solve the problem) just makes it harder for users to guess file paths.
  • save the files in the database row, but from what I've read not really the best idea .
  • create a separate server that confirms the users identity and file owner before sending the file or add the functionality to my API server.

so what do you think is the best option or do you have better ideas and how do the big shots like Facebook do it?

Go with UUID but don't just make the files available as static resources. They should still be behind an authentication function. Save the UUID in database for the user that owns that file. The authentication function then checks whether the requested UUID belongs to the logged in user or not.

Something like this:

app.use('/uploads/:uuid', authImage, express.static('uploads'));
function authImage(req, res, next){
    if(req.user.images.contains(req.params.uuid))
        next();
    else
        res.status(403).send('Forbidden');
}

You did not mention what db you using. If you are using mongodb, you can use its GFS (Grid File System) feature to store files. When you store the file you can also add meta data, in your case it will be userid or user's db record ID so you can query with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM