How to protect the Django media url?

女生的网名这么多〃 提交于 2021-01-29 09:49:36

问题


In my code I know how to protect my endpoint url. I can do simply like this

class ApprovalViewSet(mixins.RetrieveModelMixin,
                      mixins.UpdateModelMixin,
                      mixins.ListModelMixin,
                      GenericViewSet):
    permission_classes = (IsAdminUser,)
    queryset = User.objects.all()
    serializer_class = ApprovalSerializer

Problem:
However, my challenging task is I need to change /media url every time since it is sensitive files. And my files are stored in AWS S3

Questions:
1. How to protect the /media url in Django
2. My workaround is keep changing the url. How can I do that?


回答1:


@markwalker_ Thank you very much for your comment. Here is my answer. res variable here is sloppy since it can be None and raises the error. I will add my exception definition later on this problem

Put private in settings.py AWS_DEFAULT_ACL = 'private'

import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger('django')

def create_presigned_url(bucket_name, object_name, expiration=3600):
    """Generate a presigned URL to share an S3 object

    :param bucket_name: string
    :param object_name: string
    :param expiration: Time in seconds for the presigned URL to remain valid
    :return: Presigned URL as string. If error, returns None.
    """

    # Generate a presigned URL for the S3 object
    s3_client = boto3.client('s3')
    try:
        response = s3_client.generate_presigned_url('get_object',
                                                    Params={'Bucket': bucket_name,
                                                            'Key': object_name},
                                                    ExpiresIn=expiration)
    except ClientError as e:
        logging.error(e)
        return None

    # The response contains the presigned URL
    return response

Then I have to override method to_representation

class AWSImageField(serializers.ImageField):
    def to_representation(self, value):
        if not value:
            return None

        # `media/` is `MEDIA_URL`, but it is being used with `public-config`. I don't want to mess up the common use case
        url = create_presigned_url(settings.AWS_STORAGE_BUCKET_NAME, 'media/' + value.name)
        if url is not None:
            res = requests.get(url)

        return res.url

References:
https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl

Setting up media file access on AWS S3

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html



来源:https://stackoverflow.com/questions/59767269/how-to-protect-the-django-media-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!