简体   繁体   English

限制访问用户在nodejs中上传的文件?

[英]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 我正在创建一个Node.js / Express应用程序,该应用程序允许用户上传文件(图片,声音...),但是我不希望用户仅输入文件URL并访问它,我想确认用户身份并用户是否是该文件的所有者,而我对此有一些想法

  • 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. 通过添加UUID或类似的方式使文件名变得不可预测(但并不能真正解决问题),只会使用户更难猜测文件路径。
  • 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. 在发送文件或将功能添加到我的API服务器之前,创建一个单独的服务器以确认用户身份和文件所有者。

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? 那么您认为什么是最好的选择,或者您有更好的主意?像Facebook这样的大人物怎么做到的?

Go with UUID but don't just make the files available as static resources. 使用UUID,但不仅要使文件可用作静态资源。 They should still be behind an authentication function. 它们仍应位于身份验证功能之后。 Save the UUID in database for the user that owns that file. 将UUID保存在拥有该文件的用户的数据库中。 The authentication function then checks whether the requested UUID belongs to the logged in user or not. 然后,身份验证功能将检查所请求的UUID是否属于登录用户。

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. 如果您使用的是mongodb,则可以使用其GFS(网格文件系统)功能来存储文件。 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. 当您存储文件时,您还可以添加元数据,在您的情况下,它将是用户ID或用户的db记录ID,以便您查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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