Protect some file storage
Most of your media uploads – user avatars, for instance – you want to be public. But if you have some media that requires authentication before you can access it – say PDF resumes which are only accessible to members – then you don’t want S3BotoStorage’s default S3 ACL of public-read. Here we don’t have to subclass, because we can pass in an instance rather than refer to a class.
so first remove protection for all file fields in your settings and add cache control
AWS_HEADERS = {
'Cache-Control': 'max-age=86400',
}
# By default don't protect s3 urls and handle that in the model
AWS_QUERYSTRING_AUTH = False
Then make the file field you need protected to use your custom protected path
from django.db import models
import storages.backends.s3boto
protected_storage = storages.backends.s3boto.S3BotoStorage(
acl='private',
querystring_auth=True,
querystring_expire=600, # 10 minutes, try to ensure people won't/can't share
)
class Profile(models.Model):
resume = models.FileField(
null=True,
blank=True,
help_text='PDF resume accessible only to members',
storage=protected_storage,
)
But you also need to use your normal storage when you are in dev, and you are usually using local storage so this is how i personally went about it
if settings.DEFAULT_FILE_STORAGE == 'django.core.files.storage.FileSystemStorage':
protected_storage = FileSystemStorage()
logger.debug('Using FileSystemStorage for resumes files')
else:
protected_storage = S3BotoStorage(
acl='private',
querystring_auth=True,
querystring_expire=86400, # 24Hrs, expiration try to ensure people won't/can't share after 24Hrs
)
logger.debug('Using protected S3BotoStorage for resumes files')
REF: https://tartarus.org/james/diary/2013/07/18/fun-with-django-storage-backends