Alexander Popov
Alexander Popov

Reputation: 24885

How to implement access-control for uploaded assets in Rails?

I have an app with admins and normal users (two separate models). Both can upload files. Currently, the file model does not have an attribute of uploaded_by or or any associations with the Admin/User models. Once a file is uploaded by someone, it's just added to the overall list and everybody sees/can delete everything. I need this:

I would like to ask for advice on how to implement this.

I could add a polymorphic belongs_to for files and then do a query like - File.where(owner: current_user) + File.where(owner_type: 'admin').

I am ok with rolling my own system or using something like punidt or cancancan.

Upvotes: 1

Views: 56

Answers (1)

dimakura
dimakura

Reputation: 7655

You already answered your question. Yes, running punidt or cancancan and adding polymorphic relation are great ways to go. I only can add that your query is much more simple:

File.where(owner: current_user)

no need to check for owner_type.

More complex model

On the other hand, I was surprised by simplicity of your model. What if you need to define several rules on a single file. For instance, user1 is an owner of the document, user2 and user3 are editors, and user4 is just a viewer.

In this, more complicated, case you will need a separate model named UserFileRole maybe, with user (polymorphic), file and role fields.

Personally I would go with this model, because, just being "admin" still means nothing in terms of the right of editing document. They are two different roles. So they should be defined separately.

Still if your system is really as simple, as you describe, your design is very good.

Upvotes: 1

Related Questions