I have a class ImageMediaItem
which consists of name and uploaded media file.
I’m using django-protected-media
package to ensure that only authenticated users can access uploaded media files.
Then I’m using django-rules
to ensure permissions per ImageMediaItem
object.
Even if I protected ImageMediaItem
object, each authenticated user could still manually type the URL of the uploaded media file and view it no matter if he/she has permissions to ImageMediaItem
object.
How could I solve this issue ?
Is it possible to apply specific permissions to each uploaded media file ?
Or is there any other approach to this topic ?
# ...
from rules.predicates import predicate
from rules.contrib.models import RulesModel
# ...
from protected_media.models import ProtectedFileField
from protected_media.models import ProtectedImageField
# ...
@predicate
def can_view_mediaitem(user, media_item):
if media_item.viewable_by.filter(pk=user.pk).exists():
return True
return False
class ImageMediaItem(RulesModel):
# Permissions
class Meta:
rules_permissions = {
"view": can_view_mediaitem,
}
viewable_by = models.ManyToManyField(User)
# other fields
name = models.CharField(max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# protected media
file_path = ProtectedImageField(upload_to=image_file_path,
blank=True,
null=True,
validators=[
validate_file_size_10MB,
FileExtensionValidator(allowed_extensions=['jpg','jpeg','png'])
]
)
# ...