Compare commits

...

12 Commits

Author SHA1 Message Date
imperosol 43ecc509a3 test thumbnail management of AlbumEditForm 2026-04-26 17:32:35 +02:00
imperosol d621911849 Automatically resize album thumbnail 2026-04-26 17:32:35 +02:00
thomas girod f9c5297473 Merge pull request #1358 from ae-utbm/sas-style
Sas style improvement
2026-04-22 22:37:24 +02:00
imperosol 52117b5a24 add og tags to sas main page
Quand quelqu'un qui n'a pas le droit tente d'accéder au SAS, il reçoit un HTTP 200 au lieu d'un 403. C'est pas forcément le plus pertinent, mais autant en profiter pour mettre les tags og.
2026-04-22 15:02:03 +02:00
imperosol ae72a2e00f improve SAS picture tools style 2026-04-22 15:02:03 +02:00
thomas girod fdf89ea716 Merge pull request #1356 from ae-utbm/sas-parent-fix
actually fix bug where you can't select /SAS as a parent album
2026-04-22 13:06:03 +02:00
imperosol 3954f2f170 apply review comments 2026-04-22 10:59:56 +02:00
imperosol d36d672d0b actually fix bug where you can't select /SAS as a parent album 2026-04-22 00:07:39 +02:00
klmp200 da3602329c Merge pull request #1355 from ae-utbm/profile_whitelist
Fix hidden user can't search itself
2026-04-20 21:43:52 +02:00
klmp200 8b18999514 Fix hidden user can't search itself 2026-04-20 20:17:39 +02:00
klmp200 1d525ca6d4 Merge pull request #1337 from ae-utbm/album_fix
Fix bug where you can't select /SAS as a parent album
2026-04-16 15:37:33 +02:00
klmp200 4dea60ac66 Fix bug where you can't select /SAS as a parent album 2026-04-16 09:29:51 +02:00
13 changed files with 412 additions and 94 deletions
+4 -2
View File
@@ -16,7 +16,7 @@
# details. # details.
# #
# You should have received a copy of the GNU General Public License along with # You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple # this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA. # Place - Suite 330, Boston, MA 02111-1307, USA.
# #
# #
@@ -110,7 +110,9 @@ class Command(BaseCommand):
p.save(force_lock=True) p.save(force_lock=True)
club_root = SithFile.objects.create(name="clubs", owner=root) club_root = SithFile.objects.create(name="clubs", owner=root)
sas = SithFile.objects.create(name="SAS", owner=root) sas = SithFile.objects.create(
name="SAS", owner=root, id=settings.SITH_SAS_ROOT_DIR_ID
)
main_club = Club.objects.create( main_club = Club.objects.create(
id=1, name="AE", address="6 Boulevard Anatole France, 90000 Belfort" id=1, name="AE", address="6 Boulevard Anatole France, 90000 Belfort"
) )
+7 -3
View File
@@ -131,7 +131,9 @@ class UserQuerySet(models.QuerySet):
if user.has_perm("core.view_hidden_user"): if user.has_perm("core.view_hidden_user"):
return self return self
if user.has_perm("core.view_user"): if user.has_perm("core.view_user"):
return self.filter(Q(is_viewable=True) | Q(whitelisted_users=user)) return self.filter(
Q(is_viewable=True) | Q(whitelisted_users=user) | Q(pk=user.pk)
)
if user.is_anonymous: if user.is_anonymous:
return self.none() return self.none()
return self.filter(id=user.id) return self.filter(id=user.id)
@@ -884,8 +886,10 @@ class SithFile(models.Model):
return self.get_parent_path() + "/" + self.name return self.get_parent_path() + "/" + self.name
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
sas = SithFile.objects.filter(id=settings.SITH_SAS_ROOT_DIR_ID).first() sas_id = settings.SITH_SAS_ROOT_DIR_ID
self.is_in_sas = sas in self.get_parent_list() or self == sas self.is_in_sas = self.id == sas_id or any(
p.id == sas_id for p in self.get_parent_list()
)
adding = self._state.adding adding = self._state.adding
super().save(*args, **kwargs) super().save(*args, **kwargs)
if adding: if adding:
+11
View File
@@ -344,3 +344,14 @@ def test_quick_upload_image(
assert ( assert (
parsed["name"] == Path(file.name).stem[: QuickUploadImage.IMAGE_NAME_SIZE - 1] parsed["name"] == Path(file.name).stem[: QuickUploadImage.IMAGE_NAME_SIZE - 1]
) )
@pytest.mark.django_db
def test_populated_sas_is_in_sas():
"""Test that, in the data generated by the populate command,
the SAS has value is_in_sas=True.
If it's not the case, it has no incidence in prod, but it's annoying
in dev and may cause misunderstandings.
"""
assert SithFile.objects.get(id=settings.SITH_SAS_ROOT_DIR_ID).is_in_sas
+12 -4
View File
@@ -410,12 +410,20 @@ class TestUserQuerySetViewableBy:
assert set(viewable) == set(users) assert set(viewable) == set(users)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"user_factory", [old_subscriber_user.make, subscriber_user.make] "user_factory",
[
old_subscriber_user.make,
lambda: old_subscriber_user.make(is_viewable=False),
subscriber_user.make,
lambda: subscriber_user.make(is_viewable=False),
],
) )
def test_subscriber(self, users: list[User], user_factory): def test_can_search(self, users: list[User], user_factory):
user = user_factory() user = user_factory()
viewable = User.objects.filter(id__in=[u.id for u in users]).viewable_by(user) viewable = User.objects.filter(
assert set(viewable) == {users[0], users[1]} id__in=[u.id for u in [*users, user]]
).viewable_by(user)
assert set(viewable) == {user, users[0], users[1]}
def test_whitelist(self, users: list[User]): def test_whitelist(self, users: list[User]):
user = subscriber_user.make() user = subscriber_user.make()
+43 -6
View File
@@ -1,16 +1,23 @@
from typing import Any import copy
from pathlib import Path
from typing import TYPE_CHECKING, Any
from django import forms from django import forms
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from PIL import Image
from core.models import User from core.models import User
from core.utils import resize_image
from core.views import MultipleImageField from core.views import MultipleImageField
from core.views.forms import SelectDate from core.views.forms import SelectDate
from core.views.widgets.ajax_select import AutoCompleteSelectMultipleGroup from core.views.widgets.ajax_select import AutoCompleteSelectMultipleGroup
from sas.models import Album, Picture, PictureModerationRequest from sas.models import Album, Picture, PictureModerationRequest
from sas.widgets.ajax_select import AutoCompleteSelectAlbum from sas.widgets.ajax_select import AutoCompleteSelectAlbum
if TYPE_CHECKING:
from django.db.models.fields.files import FieldFile
class AlbumCreateForm(forms.ModelForm): class AlbumCreateForm(forms.ModelForm):
class Meta: class Meta:
@@ -49,14 +56,44 @@ class AlbumEditForm(forms.ModelForm):
class Meta: class Meta:
model = Album model = Album
fields = ["name", "date", "file", "parent", "edit_groups"] fields = ["name", "date", "file", "parent", "edit_groups"]
widgets = { widgets = {"edit_groups": AutoCompleteSelectMultipleGroup, "date": SelectDate}
"parent": AutoCompleteSelectAlbum,
"edit_groups": AutoCompleteSelectMultipleGroup,
}
name = forms.CharField(max_length=Album.NAME_MAX_LENGTH, label=_("file name")) name = forms.CharField(max_length=Album.NAME_MAX_LENGTH, label=_("file name"))
date = forms.DateField(label=_("Date"), widget=SelectDate, required=True)
recursive = forms.BooleanField(label=_("Apply rights recursively"), required=False) recursive = forms.BooleanField(label=_("Apply rights recursively"), required=False)
parent = forms.ModelChoiceField(
Album.objects.all(), required=True, widget=AutoCompleteSelectAlbum
)
def clean_file(self):
# if a file was given in the form, resize it
f: FieldFile = self.cleaned_data["file"]
if self.errors or not f or "file" not in self.changed_data:
return f
f.file = resize_image(Image.open(f.file), 200, "WEBP")
return f
def save(self, commit=True): # noqa: FBT002
initial_file = copy.copy(self.initial["file"])
if not self.cleaned_data["file"]:
# if no file is in the form, it can mean either :
# - there was a file initially, but the deletion box was checked
# - there was no file initially, and there still isn't
# in both cases, we procedurally generate the thumbnail
self.instance.generate_thumbnail()
elif "file" in self.changed_data:
self.instance.file.name = str(Path(self.instance.name) / "thumb.webp")
res = super().save(commit=commit)
if initial_file and (
not self.instance.file or initial_file.path != self.instance.file.path
):
# The initial file must be removed from storage
# AFTER the new one has been dealt with,
# in order to be sure that django will generate a different filename.
# Otherwise, the client cache wouldn't be properly busted.
# Even if there was no file, this operation cannot fail, because django
# will just silently return in that case.
initial_file.delete(save=False)
return res
class PictureModerationRequestForm(forms.ModelForm): class PictureModerationRequestForm(forms.ModelForm):
+6 -14
View File
@@ -22,6 +22,7 @@ from typing import ClassVar, Self
from django.conf import settings from django.conf import settings
from django.core.cache import cache from django.core.cache import cache
from django.core.files.base import ContentFile
from django.db import models from django.db import models
from django.db.models import Exists, OuterRef, Q from django.db.models import Exists, OuterRef, Q
from django.urls import reverse from django.urls import reverse
@@ -110,7 +111,7 @@ class Picture(SasFile):
def get_absolute_url(self): def get_absolute_url(self):
return reverse("sas:picture", kwargs={"picture_id": self.id}) return reverse("sas:picture", kwargs={"picture_id": self.id})
def generate_thumbnails(self, *, overwrite=False): def generate_thumbnails(self):
im = Image.open(BytesIO(self.file.read())) im = Image.open(BytesIO(self.file.read()))
with contextlib.suppress(Exception): with contextlib.suppress(Exception):
im = exif_auto_rotate(im) im = exif_auto_rotate(im)
@@ -126,10 +127,6 @@ class Picture(SasFile):
file = resize_image(im, max(im.size), extension, optimize=False) file = resize_image(im, max(im.size), extension, optimize=False)
thumb = resize_image(im, 200, "webp") thumb = resize_image(im, 200, "webp")
compressed = resize_image(im, 1200, "webp") compressed = resize_image(im, 1200, "webp")
if overwrite:
self.file.delete()
self.thumbnail.delete()
self.compressed.delete()
new_extension_name = str(Path(self.name).with_suffix(".webp")) new_extension_name = str(Path(self.name).with_suffix(".webp"))
self.file = file self.file = file
self.file.name = self.name self.file.name = self.name
@@ -245,17 +242,12 @@ class Album(SasFile):
return reverse("sas:album_preview", kwargs={"album_id": self.id}) return reverse("sas:album_preview", kwargs={"album_id": self.id})
def generate_thumbnail(self): def generate_thumbnail(self):
p = ( p = self.children_pictures.order_by("?").first()
self.children_pictures.order_by("?").first() if p and p.thumbnail:
or self.children_albums.exclude(file=None) image = ContentFile(
.exclude(file="") name=str(Path(self.name) / "thumb.webp"), content=p.thumbnail.read()
.order_by("?")
.first()
) )
if p and p.file:
image = resize_image(Image.open(BytesIO(p.file.read())), 200, "webp")
self.file = image self.file = image
self.file.name = f"{self.name}/thumb.webp"
self.save() self.save()
+24 -29
View File
@@ -134,7 +134,7 @@
--loading-size: 20px --loading-size: 20px
} }
@media (max-width: 1000px) { @media (min-width: 700px) and (max-width: 1000px) {
max-width: calc(50% - 5px); max-width: calc(50% - 5px);
} }
@@ -201,57 +201,52 @@
} }
} }
.general { #pict .general {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
gap: 20px; gap: 3em;
justify-content: space-evenly;
@media (max-width: 1000px) { @media (max-width: 1000px) {
gap: 1em;
flex-direction: column; flex-direction: column;
} }
>.infos { .infos, .tools {
flex: 1;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 50%; gap: .5em;
@media (min-width: 700px) {
max-width: 350px;
}
}
.infos > div, .tools > div > div {
display: flex;
flex-direction: column;
gap: .35em;
}
>div>div { .tools > div, >.infos >div>div {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-between; justify-content: space-between;
>*:first-child {
min-width: 150px;
@media (max-width: 1000px) {
min-width: auto;
}
}
}
} }
>.tools { >.tools {
display: flex; flex: 1;
flex-direction: column;
width: 50%;
>div { >div>div {
display: flex; >a.btn {
flex-direction: row;
justify-content: space-between;
>div {
>a.button {
box-sizing: border-box;
background-color: $primary-neutral-light-color; background-color: $primary-neutral-light-color;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
padding: 10px; padding: 0;
color: black; color: black;
border-radius: 5px;
width: 40px; width: 40px;
height: 40px; height: 40px;
font-size: 20px;
&:hover { &:hover {
background-color: #aaa; background-color: #aaa;
@@ -268,9 +263,9 @@
&.buttons { &.buttons {
display: flex; display: flex;
flex-direction: row;
gap: 5px; gap: 5px;
} }
} }
} }
}
} }
+4 -4
View File
@@ -2,19 +2,19 @@
<a href="{{ url('sas:album', album_id=a.id) }}"> <a href="{{ url('sas:album', album_id=a.id) }}">
{% if a.file %} {% if a.file %}
{% set img = a.get_download_url() %} {% set img = a.get_download_url() %}
{% set src = a.name %} {% set alt = a.name %}
{% elif a.children.filter(is_folder=False, is_moderated=True).exists() %} {% elif a.children.filter(is_folder=False, is_moderated=True).exists() %}
{% set picture = a.children.filter(is_folder=False).first().as_picture %} {% set picture = a.children.filter(is_folder=False).first().as_picture %}
{% set img = picture.get_download_thumb_url() %} {% set img = picture.get_download_thumb_url() %}
{% set src = picture.name %} {% set alt = picture.name %}
{% else %} {% else %}
{% set img = static('core/img/sas.jpg') %} {% set img = static('core/img/sas.jpg') %}
{% set src = "sas.jpg" %} {% set alt = "sas.jpg" %}
{% endif %} {% endif %}
<div <div
class="album{% if not a.is_moderated %} not_moderated{% endif %}" class="album{% if not a.is_moderated %} not_moderated{% endif %}"
> >
<img src="{{ img }}" alt="{{ src }}" loading="lazy" /> <img src="{{ img }}" alt="{{ alt }}" loading="lazy" />
{% if not a.is_moderated %} {% if not a.is_moderated %}
<div class="overlay">&nbsp;</div> <div class="overlay">&nbsp;</div>
<div class="text">{% trans %}To be moderated{% endtrans %}</div> <div class="text">{% trans %}To be moderated{% endtrans %}</div>
+11
View File
@@ -12,6 +12,17 @@
{% trans %}See all the photos taken during events organised by the AE.{% endtrans %} {% trans %}See all the photos taken during events organised by the AE.{% endtrans %}
{%- endblock %} {%- endblock %}
{% block metatags %}
<meta property="og:url" content="{{ request.build_absolute_uri() }}" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Stock à souvenirs" />
<meta
property="og:description"
content="Retrouvez toutes les photos prises durant les événements organisés par l'AE."
/>
<meta property="og:image" content="{{ request.build_absolute_uri(static("core/img/logo_no_text.png")) }}" />
{% endblock %}
{% set is_sas_admin = user.is_root or user.is_in_group(pk=settings.SITH_GROUP_SAS_ADMIN_ID) %} {% set is_sas_admin = user.is_root or user.is_in_group(pk=settings.SITH_GROUP_SAS_ADMIN_ID) %}
{% from "sas/macros.jinja" import display_album %} {% from "sas/macros.jinja" import display_album %}
+10 -5
View File
@@ -118,15 +118,20 @@
<a class="text" :href="currentPicture.full_size_url"> <a class="text" :href="currentPicture.full_size_url">
{% trans %}HD version{% endtrans %} {% trans %}HD version{% endtrans %}
</a> </a>
<br> <a class="text danger " :href="currentPicture.report_url">
<a class="text danger" :href="currentPicture.report_url">
{% trans %}Ask for removal{% endtrans %} {% trans %}Ask for removal{% endtrans %}
</a> </a>
</div> </div>
<div class="buttons"> <div class="buttons">
<a class="button" :href="currentPicture.edit_url"><i class="fa-regular fa-pen-to-square edit-action"></i></a> <a
<a class="button" href="?rotate_left"><i class="fa-solid fa-rotate-left"></i></a> class="btn btn-no-text"
<a class="button" href="?rotate_right"><i class="fa-solid fa-rotate-right"></i></a> :href="currentPicture.edit_url"
x-show="{{ user.has_perm("sas.change_sasfile")|tojson }} || currentPicture.owner.id === {{ user.id }}"
>
<i class="fa-regular fa-pen-to-square edit-action"></i>
</a>
<a class="btn btn-no-text" href="?rotate_left"><i class="fa-solid fa-rotate-left"></i></a>
<a class="btn btn-no-text" href="?rotate_right"><i class="fa-solid fa-rotate-right"></i></a>
</div> </div>
</div> </div>
</div> </div>
+218
View File
@@ -0,0 +1,218 @@
import random
import string
from pathlib import Path
from typing import Callable
from unittest.mock import patch
import pytest
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client
from django.urls import reverse
from django.utils.datastructures import MultiValueDict
from django.utils.timezone import localdate
from model_bakery import baker
from PIL import Image
from pytest_django.asserts import assertInHTML, assertRedirects
from core.baker_recipes import subscriber_user
from core.models import Group, User
from core.utils import RED_PIXEL_PNG
from sas.baker_recipes import picture_recipe
from sas.forms import AlbumEditForm
from sas.models import Album
@pytest.fixture
def sas_root(db) -> Album:
return Album.objects.get(id=settings.SITH_SAS_ROOT_DIR_ID)
@pytest.fixture
def album(db) -> Album:
name = "".join(
random.choice(string.ascii_letters) for _ in range(Album.NAME_MAX_LENGTH)
)
return baker.make(
Album, name=name, parent_id=settings.SITH_SAS_ROOT_DIR_ID, is_moderated=True
)
@pytest.mark.parametrize("user", [None, lambda: baker.make(User), subscriber_user.make])
@pytest.mark.django_db
def test_permission_denied(
client: Client, album: Album, user: Callable[[], User] | None
):
if user:
client.force_login(user())
url = reverse("sas:album_edit", kwargs={"album_id": album.pk})
for method in client.get, client.post:
assert method(url).status_code == 403
@pytest.mark.django_db
def test_sas_root_read_only(client: Client, sas_root: Album):
moderator = baker.make(
User, groups=[Group.objects.get(pk=settings.SITH_GROUP_SAS_ADMIN_ID)]
)
client.force_login(moderator)
url = reverse("sas:album_edit", kwargs={"album_id": sas_root.pk})
for method in client.get, client.post:
assert method(url).status_code == 404
@pytest.mark.parametrize(
("excluded", "is_valid"),
[
("name", False),
("date", False),
("file", True),
("parent", False),
("edit_groups", True),
("recursive", True),
],
)
@pytest.mark.django_db
def test_form_required(album: Album, excluded: str, is_valid: bool): # noqa: FBT001
data = {
"name": album.name,
"parent": baker.make(Album, parent=album.parent, is_moderated=True).pk,
"date": localdate(),
"file": "/random/path",
"edit_groups": [settings.SITH_GROUP_SAS_ADMIN_ID],
"recursive": False,
}
del data[excluded]
assert AlbumEditForm(data=data).is_valid() == is_valid
@pytest.mark.django_db
def test_form_album_name(album: Album):
data = {
"name": "a" * Album.NAME_MAX_LENGTH,
"parent": album.pk,
"date": localdate(),
}
assert AlbumEditForm(data=data).is_valid()
data["name"] = "a" * (Album.NAME_MAX_LENGTH + 1)
assert not AlbumEditForm(data=data).is_valid()
@pytest.mark.django_db
def test_update_recursive_parent(client: Client, album: Album):
client.force_login(baker.make(User, is_superuser=True))
payload = {"name": album.name, "parent": album.pk, "date": localdate()}
response = client.post(
reverse("sas:album_edit", kwargs={"album_id": album.pk}), payload
)
assertInHTML("<li>Boucle dans l'arborescence des dossiers</li>", response.text)
assert response.status_code == 200
@pytest.mark.parametrize(
"user",
[
lambda: baker.make(User, is_superuser=True),
lambda: baker.make(
User, groups=[Group.objects.get(pk=settings.SITH_GROUP_SAS_ADMIN_ID)]
),
],
)
@pytest.mark.parametrize(
"parent",
[
lambda: baker.make(
Album, parent_id=settings.SITH_SAS_ROOT_DIR_ID, is_moderated=True
),
lambda: Album.objects.get(id=settings.SITH_SAS_ROOT_DIR_ID),
],
)
@pytest.mark.django_db
def test_update(
client: Client,
album: Album,
sas_root: Album,
user: Callable[[], User],
parent: Callable[[], Album],
):
client.force_login(user())
expected_redirect = reverse("sas:album", kwargs={"album_id": album.pk})
payload = {
"name": "foo",
"parent": parent().id,
"date": localdate(),
"recursive": False,
}
response = client.post(
reverse("sas:album_edit", kwargs={"album_id": album.pk}), payload
)
assertRedirects(response, expected_redirect)
album.refresh_from_db()
assert album.name == "foo"
assert album.parent.id == payload["parent"]
assert localdate(album.date) == localdate()
class TestAlbumThumbnail:
@pytest.fixture
def files(self):
return MultiValueDict(
{"file": [SimpleUploadedFile(name="foo.png", content=RED_PIXEL_PNG)]}
)
def test_thumbnail_resized(self, album, files):
"""Test that album thumbnails are resized to the correct dimensions."""
form = AlbumEditForm(
data={"name": album.name, "date": localdate(), "parent": album.parent.id},
files=files,
instance=album,
)
assert form.is_valid()
form.save()
album.refresh_from_db()
assert album.file.name == f"SAS/{album.name}/thumb.webp"
assert Image.open(album.file).size == (200, 200)
def test_thumbnail_removed(self, album):
"""Test the case where the user checks the box to remove the thumbnail"""
album.file = ContentFile(name="foo.png", content=RED_PIXEL_PNG)
album.save()
previous_filename = album.file.name
form = AlbumEditForm(
data={
"name": "foo",
"date": localdate(),
"parent": album.parent.id,
"file-clear": True,
},
instance=album,
)
# as there is now no picture, a thumbnail should be generated
with patch.object(Album, "generate_thumbnail") as mock:
assert form.is_valid()
form.save()
album.refresh_from_db()
assert album.file.storage.exists(album.file.name)
assert not album.file.storage.exists(previous_filename)
mock.assert_called_once()
def test_generate_thumbnail(self, album):
"""Test that if no image is given and the album has pictures,
the thumbnail is automatically generated.
"""
picture = picture_recipe.make(
parent=album, thumbnail=ContentFile(name="foo.png", content=RED_PIXEL_PNG)
)
form = AlbumEditForm(
data={"name": "foo", "date": localdate(), "parent": album.parent.id},
instance=album,
)
assert form.is_valid()
form.save()
album.refresh_from_db()
assert Path(album.file.name) == Path("SAS/foo/thumb.webp")
assert album.file.storage.exists(album.file.name)
assert Image.open(album.file) == Image.open(picture.thumbnail)
+29
View File
@@ -64,6 +64,25 @@ def test_main_page_no_form_for_regular_users(client: Client):
assert len(forms) == 0 assert len(forms) == 0
@pytest.mark.django_db
def test_main_page_displayed_albums(client: Client):
"""Test that the right data is displayed on the SAS main page"""
sas = Album.objects.get(id=settings.SITH_SAS_ROOT_DIR_ID)
Album.objects.exclude(id=sas.id).delete()
album_a = baker.make(Album, parent=sas, is_moderated=True)
album_b = baker.make(Album, parent=album_a, is_moderated=True)
album_c = baker.make(Album, parent=sas, is_moderated=True)
baker.make(Album, parent=sas, is_moderated=False)
client.force_login(subscriber_user.make())
res = client.get(reverse("sas:main"))
# album_b is not a direct child of the SAS, so it shouldn't be displayed
# in the categories, but it should appear in the latest albums.
# album_d isn't moderated, so it shouldn't appear at all for a simple user.
# Also, the SAS itself shouldn't be listed in the albums.
assert res.context_data["latest"] == [album_c, album_b, album_a]
assert res.context_data["categories"] == [album_a, album_c]
@pytest.mark.django_db @pytest.mark.django_db
def test_main_page_content_anonymous(client: Client): def test_main_page_content_anonymous(client: Client):
"""Test that public users see only an incentive to login""" """Test that public users see only an incentive to login"""
@@ -76,6 +95,7 @@ def test_main_page_content_anonymous(client: Client):
@pytest.mark.django_db @pytest.mark.django_db
def test_album_access_non_subscriber(client: Client): def test_album_access_non_subscriber(client: Client):
"""Test that non-subscribers can only access albums where they are identified.""" """Test that non-subscribers can only access albums where they are identified."""
cache.clear()
album = baker.make(Album, parent_id=settings.SITH_SAS_ROOT_DIR_ID) album = baker.make(Album, parent_id=settings.SITH_SAS_ROOT_DIR_ID)
user = baker.make(User) user = baker.make(User)
client.force_login(user) client.force_login(user)
@@ -89,6 +109,15 @@ def test_album_access_non_subscriber(client: Client):
assert res.status_code == 200 assert res.status_code == 200
@pytest.mark.django_db
def test_accessing_sas_from_album_view_is_404(client: Client):
"""Test that trying to see the SAS with a regular album view isn't allowed."""
res = client.get(
reverse("sas:album", kwargs={"album_id": settings.SITH_SAS_ROOT_DIR_ID})
)
assert res.status_code == 404
@pytest.mark.django_db @pytest.mark.django_db
class TestAlbumUpload: class TestAlbumUpload:
@staticmethod @staticmethod
+10 -4
View File
@@ -16,6 +16,7 @@ from typing import Any
from django.conf import settings from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import PermissionDenied
from django.db.models import Count, OuterRef, Subquery from django.db.models import Count, OuterRef, Subquery
from django.http import Http404, HttpResponseRedirect from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
@@ -85,7 +86,9 @@ class SASMainView(UseFragmentsMixin, TemplateView):
kwargs["categories"] = list( kwargs["categories"] = list(
albums_qs.filter(parent_id=settings.SITH_SAS_ROOT_DIR_ID).order_by("id") albums_qs.filter(parent_id=settings.SITH_SAS_ROOT_DIR_ID).order_by("id")
) )
kwargs["latest"] = list(albums_qs.order_by("-id")[:5]) kwargs["latest"] = list(
albums_qs.exclude(id=settings.SITH_SAS_ROOT_DIR_ID).order_by("-id")[:5]
)
return kwargs return kwargs
@@ -126,6 +129,9 @@ def send_thumb(request, picture_id):
class AlbumView(CanViewMixin, UseFragmentsMixin, DetailView): class AlbumView(CanViewMixin, UseFragmentsMixin, DetailView):
model = Album model = Album
# exclude the SAS from the album accessible with this view
# the SAS can be viewed only with SASMainView
queryset = Album.objects.exclude(id=settings.SITH_SAS_ROOT_DIR_ID)
pk_url_kwarg = "album_id" pk_url_kwarg = "album_id"
template_name = "sas/album.jinja" template_name = "sas/album.jinja"
@@ -147,9 +153,8 @@ class AlbumView(CanViewMixin, UseFragmentsMixin, DetailView):
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
self.object = self.get_object() self.object = self.get_object()
if not self.object.file: if not request.user.can_edit(self.object):
self.object.generate_thumbnail() raise PermissionDenied
if request.user.can_edit(self.object): # Handle the copy-paste functions
FileView.handle_clipboard(request, self.object) FileView.handle_clipboard(request, self.object)
return HttpResponseRedirect(self.request.path) return HttpResponseRedirect(self.request.path)
@@ -262,6 +267,7 @@ class PictureAskRemovalView(CanViewMixin, DetailView, FormView):
class AlbumEditView(CanEditMixin, UpdateView): class AlbumEditView(CanEditMixin, UpdateView):
model = Album model = Album
queryset = Album.objects.exclude(id=settings.SITH_SAS_ROOT_DIR_ID)
form_class = AlbumEditForm form_class = AlbumEditForm
template_name = "core/edit.jinja" template_name = "core/edit.jinja"
pk_url_kwarg = "album_id" pk_url_kwarg = "album_id"