Limit access to files to user

No database migration is made
This commit is contained in:
Edgar P. Burkhart 2022-12-31 17:28:15 +01:00
parent de06312a2a
commit 06704aaa77
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227
7 changed files with 48 additions and 35 deletions

View file

@ -6,6 +6,7 @@ from django.conf import settings
from django.core.validators import FileExtensionValidator, validate_slug
from django.db import models, transaction
from django.urls import reverse
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
@ -30,6 +31,15 @@ class CustomModel(UserModel):
abstract = True
def get_path(instance, filename):
return pathlib.Path(
"user",
str(instance.user.get_username()),
instance._meta.model_name,
str(instance.pk),
).with_suffix(".pdf")
class Account(CustomModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=64, default=_("Account"), verbose_name=_("Name"))
@ -104,10 +114,6 @@ class Category(CustomModel):
verbose_name_plural = _("Categories")
def snapshot_path(instance, filename):
return pathlib.Path("snapshots", str(instance.id)).with_suffix(".pdf")
class Snapshot(AccountModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
date = models.DateField(default=datetime.date.today, verbose_name=_("End date"))
@ -135,7 +141,7 @@ class Snapshot(AccountModel):
editable=False,
)
file = models.FileField(
upload_to=snapshot_path,
upload_to=get_path,
validators=[FileExtensionValidator(["pdf"])],
verbose_name=_("File"),
max_length=256,
@ -258,17 +264,13 @@ class Transaction(CustomModel):
verbose_name_plural = _("Transactions")
def invoice_path(instance, filename):
return pathlib.Path("invoices", str(instance.id)).with_suffix(".pdf")
class Invoice(CustomModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(
max_length=256, default=_("Invoice"), verbose_name=_("Name")
)
file = models.FileField(
upload_to=invoice_path,
upload_to=get_path,
validators=[FileExtensionValidator(["pdf"])],
verbose_name=_("File"),
max_length=128,
@ -277,13 +279,19 @@ class Invoice(CustomModel):
Transaction, on_delete=models.CASCADE, editable=False
)
def save(self):
if Invoice.objects.filter(id=self.id).exists():
_prever = Invoice.objects.get(id=self.id)
if _prever.file and _prever.file != self.file:
pathlib.Path(_prever.file.path).unlink(missing_ok=True)
def __str__(self):
if hasattr(self, "transaction"):
return f"{self.name} {self.transaction.name}"
return self.name
return str(format_lazy("{} {}", self.name, self.transaction.name))
return str(self.name)
def delete(self, *args, **kwargs):
self.file.delete()
self.file.delete(missing_ok=True)
super().delete(*args, **kwargs)
def get_absolute_url(self):