Skip to content

Commit

Permalink
Implementada validação de prefixo de endereço de arquivos
Browse files Browse the repository at this point in the history
  • Loading branch information
renzo authored and renzon committed Sep 4, 2024
1 parent 429d3bf commit e2c5362
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 4 deletions.
8 changes: 7 additions & 1 deletion backend/devpro/base/admin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from django_min_custom_user.admin import MinUserAdmin

from devpro.base.models import User
from devpro.base.models import User, Arquivo


@admin.register(User)
class UserAdmin(MinUserAdmin):
pass


@admin.register(Arquivo)
class ArquivoAdmin(ModelAdmin):
pass
21 changes: 21 additions & 0 deletions backend/devpro/base/migrations/0002_arquivo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 5.0.7 on 2024-09-04 23:25

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('base', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='Arquivo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('arq', models.FileField(upload_to='public/')),
('privado', models.FileField(upload_to='private/')),
],
),
]
6 changes: 6 additions & 0 deletions backend/devpro/base/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
from django.db import models
from django_min_custom_user.models import MinAbstractUser


class User(MinAbstractUser):
pass


class Arquivo(models.Model):
arq = models.FileField(upload_to='public/')
privado = models.FileField(upload_to='private/')
17 changes: 14 additions & 3 deletions backend/devpro/s3_file_handlers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from django.core.files.storage import FileSystemStorage
from storages.backends.s3 import S3Storage

_PUBLIC_PREFIX = 'public/'
_PRIVATE_PREFIX = 'private/'


class FileConfigurationError(Exception):
pass
Expand All @@ -8,22 +12,29 @@ class FileConfigurationError(Exception):
class S3FileStorage(S3Storage):
def url(self, name, parameters=None, expire=None, http_method=None):
url = super().url(name, parameters, expire, http_method)
if name.startswith('public'):
if name.startswith(_PUBLIC_PREFIX):
url = url.split('?')[0]
return url

def get_object_parameters(self, name):
parameters = super().get_object_parameters(name)
self._validate(name)
if self._startswith(name, 'public'):
if self._startswith(name, _PUBLIC_PREFIX):
parameters['ACL'] = 'public-read'
else:
parameters['ACL'] = 'private'
return parameters

def _validate(self, name: str):
if not (self._startswith(name, 'public') or self._startswith(name, 'private')):
if not (self._startswith(name, _PUBLIC_PREFIX) or self._startswith(name, _PRIVATE_PREFIX)):
raise FileConfigurationError(f'property "upload_to" must start with "public" or "private" and it is {name}')

def _startswith(self, name, prefix):
return name.startswith(f'{self.location}/{prefix}')


class FileSystemWithValidationStorage(FileSystemStorage):
def _save(self, name, content):
if not (name.startswith(_PUBLIC_PREFIX) or name.startswith(_PRIVATE_PREFIX)):
raise FileConfigurationError(f'property "upload_to" must start with "public" or "private" and it is {name}')
return super()._save(name, content)
9 changes: 9 additions & 0 deletions backend/devpro/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@
STATIC_ROOT = BASE_DIR.parent / 'docker/staticfiles/static'
MEDIA_ROOT = BASE_DIR.parent / 'docker/mediafiles'
MEDIA_URL = '/mediafiles/'
# Muda a configuração de upload de arquivos locais para bater com produção
STORAGES = {
"default": {
"BACKEND": "devpro.s3_file_handlers.FileSystemWithValidationStorage",
},
"staticfiles": {
"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
},
}
else:
STATIC_URL = f'//{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/static/'

Expand Down

0 comments on commit e2c5362

Please sign in to comment.