mirror of
https://github.com/ae-utbm/sith.git
synced 2026-12-05 07:12:48 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ac2bb48c2 | ||
|
|
d7fa0b5ed6 | ||
|
|
be81c2e51e | ||
|
|
b883e7b17a | ||
|
|
702524d77d | ||
|
|
2c3580f776 |
No files matched your search
+1
-1
@@ -36,7 +36,7 @@ class GroupAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "description", "is_manually_manageable")
|
||||
list_filter = ("is_manually_manageable",)
|
||||
search_fields = ("name",)
|
||||
autocomplete_fields = ("permissions",)
|
||||
autocomplete_fields = ("permissions", "manageable_by")
|
||||
|
||||
|
||||
@admin.register(BanGroup)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Generated by Django 5.2.19 on 2026-12-04 13:24
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
import core.models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("core", "0053_alter_user_email_alter_user_second_email")]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelManagers(
|
||||
name="group", managers=[("objects", core.models.CustomGroupManager())]
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="group",
|
||||
name="manageable_by",
|
||||
field=models.ManyToManyField(
|
||||
blank=True,
|
||||
help_text="Groups that are able to grant and remove this group.",
|
||||
related_name="managed_groups",
|
||||
to="core.group",
|
||||
verbose_name="manageable by",
|
||||
),
|
||||
),
|
||||
]
|
||||
+23
-1
@@ -33,7 +33,7 @@ from typing import TYPE_CHECKING, Final, Self
|
||||
from uuid import uuid4
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import AbstractUser, UserManager
|
||||
from django.contrib.auth.models import AbstractUser, GroupManager, UserManager
|
||||
from django.contrib.auth.models import AnonymousUser as AuthAnonymousUser
|
||||
from django.contrib.auth.models import Group as AuthGroup
|
||||
from django.contrib.staticfiles.storage import staticfiles_storage
|
||||
@@ -65,6 +65,19 @@ if TYPE_CHECKING:
|
||||
from club.models import Club
|
||||
|
||||
|
||||
class GroupQuerySet(models.QuerySet):
|
||||
def manageable_by(self, user: User):
|
||||
"""Filter groups that are editable by this user in the sith UI."""
|
||||
if user.has_perm("core.change_group"):
|
||||
return self.filter(is_manually_manageable=True)
|
||||
return self.filter(
|
||||
is_manually_manageable=True, manageable_by__in=user.groups.all()
|
||||
)
|
||||
|
||||
|
||||
class CustomGroupManager(GroupManager.from_queryset(GroupQuerySet)): ...
|
||||
|
||||
|
||||
class Group(AuthGroup):
|
||||
"""Wrapper around django.auth.Group"""
|
||||
|
||||
@@ -74,6 +87,15 @@ class Group(AuthGroup):
|
||||
help_text=_("If False, this shouldn't be shown on group management pages"),
|
||||
)
|
||||
description = models.TextField(_("description"))
|
||||
manageable_by = models.ManyToManyField(
|
||||
"Group",
|
||||
verbose_name=_("manageable by"),
|
||||
help_text=_("Groups that are able to grant and remove this group."),
|
||||
related_name="managed_groups",
|
||||
blank=True,
|
||||
)
|
||||
|
||||
objects = CustomGroupManager()
|
||||
|
||||
def get_absolute_url(self) -> str:
|
||||
return reverse("core:group_list")
|
||||
|
||||
@@ -295,6 +295,49 @@ def test_user_update_groups(client: Client):
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_user_update_groups_non_admin(client: Client):
|
||||
"""Test that a non-admin user can update the groups it is allowed to."""
|
||||
managed_group = baker.make(Group, is_manually_manageable=True)
|
||||
other_group = baker.make(Group, is_manually_manageable=True)
|
||||
operator = subscriber_user.make(
|
||||
groups=[baker.make(Group, managed_groups=[managed_group])]
|
||||
)
|
||||
user = baker.make(User, groups=[other_group])
|
||||
client.force_login(operator)
|
||||
response = client.post(
|
||||
reverse("core:user_groups", kwargs={"user_id": user.id}),
|
||||
data={"groups": [managed_group.id]},
|
||||
)
|
||||
assertRedirects(response, user.get_absolute_url())
|
||||
# the manageable group should have been attributed
|
||||
# and the non-manageable groups should be kept
|
||||
assert set(user.groups.all()) == {
|
||||
Group.objects.get(pk=settings.SITH_GROUP_PUBLIC_ID),
|
||||
managed_group,
|
||||
other_group,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_user_update_groups_denied(client: Client):
|
||||
"""Test that a user that can manage no group cannot access the page at all."""
|
||||
operator = subscriber_user.make(groups=[baker.make(Group)])
|
||||
user = baker.make(User)
|
||||
client.force_login(operator)
|
||||
response = client.get(reverse("core:user_groups", kwargs={"user_id": user.id}))
|
||||
assert response.status_code == 403
|
||||
response = client.post(
|
||||
reverse("core:user_groups", kwargs={"user_id": user.id}),
|
||||
data={"groups": [baker.make(Group).id]},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
# no group should have been attributed at all
|
||||
assert set(user.groups.all()) == {
|
||||
Group.objects.get(pk=settings.SITH_GROUP_PUBLIC_ID)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_logout(client: Client):
|
||||
user = baker.make(User)
|
||||
@@ -378,6 +421,19 @@ def test_displayed_user_self_tabs(user_factory, expected_tabs: list[str]):
|
||||
"account",
|
||||
],
|
||||
),
|
||||
(
|
||||
# this user is in a group that is allowed to manage another group
|
||||
# so the groups tab should be displayed
|
||||
lambda: subscriber_user.make(
|
||||
groups=[
|
||||
baker.make(
|
||||
Group,
|
||||
managed_groups=[baker.make(Group, is_manually_manageable=True)],
|
||||
)
|
||||
]
|
||||
),
|
||||
["infos", "godfathers", "pictures", "clubs", "groups"],
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_displayed_other_user_tabs(user_factory, expected_tabs: list[str]):
|
||||
|
||||
+6
-2
@@ -366,7 +366,7 @@ class UserGroupsForm(forms.ModelForm):
|
||||
required_css_class = "required"
|
||||
|
||||
groups = forms.ModelMultipleChoiceField(
|
||||
queryset=Group.objects.filter(is_manually_manageable=True),
|
||||
queryset=Group.objects.none(),
|
||||
widget=CheckboxSelectMultiple,
|
||||
label=_("Groups"),
|
||||
required=False,
|
||||
@@ -376,6 +376,10 @@ class UserGroupsForm(forms.ModelForm):
|
||||
model = User
|
||||
fields = ["groups"]
|
||||
|
||||
def __init__(self, *args, request_user: User, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["groups"].queryset = Group.objects.manageable_by(request_user).all()
|
||||
|
||||
def save(self, *args, **kwargs) -> User:
|
||||
# make the super method manage error without persisting in db
|
||||
super().save(commit=False)
|
||||
@@ -384,7 +388,7 @@ class UserGroupsForm(forms.ModelForm):
|
||||
self.instance.groups.set(
|
||||
[
|
||||
*self.cleaned_data["groups"],
|
||||
*self.instance.groups.filter(is_manually_manageable=False),
|
||||
*self.instance.groups.difference(self.fields["groups"].queryset),
|
||||
]
|
||||
)
|
||||
return self.instance
|
||||
|
||||
+10
-5
@@ -26,7 +26,6 @@ from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import ListView
|
||||
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
||||
|
||||
from core.auth.mixins import CanEditMixin
|
||||
from core.models import Group, User
|
||||
from core.views import DetailFormView
|
||||
from core.views.forms import PermissionGroupsForm
|
||||
@@ -61,16 +60,19 @@ class EditMembersForm(forms.Form):
|
||||
# Views
|
||||
|
||||
|
||||
class GroupListView(CanEditMixin, ListView):
|
||||
class GroupListView(PermissionRequiredMixin, ListView):
|
||||
"""Displays the Group list."""
|
||||
|
||||
model = Group
|
||||
queryset = Group.objects.filter(is_manually_manageable=True)
|
||||
ordering = ["name"]
|
||||
template_name = "core/group_list.jinja"
|
||||
# This page is basically a list of links towards group edit pages,
|
||||
# so give access only to users who can edit groups
|
||||
permission_required = "core.change_group"
|
||||
|
||||
|
||||
class GroupEditView(CanEditMixin, UpdateView):
|
||||
class GroupEditView(PermissionRequiredMixin, UpdateView):
|
||||
"""Edit infos of a Group."""
|
||||
|
||||
model = Group
|
||||
@@ -78,6 +80,7 @@ class GroupEditView(CanEditMixin, UpdateView):
|
||||
pk_url_kwarg = "group_id"
|
||||
template_name = "core/group_edit.jinja"
|
||||
fields = ["name", "description"]
|
||||
permission_required = "core.change_group"
|
||||
|
||||
|
||||
class GroupCreateView(PermissionRequiredMixin, CreateView):
|
||||
@@ -90,7 +93,7 @@ class GroupCreateView(PermissionRequiredMixin, CreateView):
|
||||
permission_required = "core.add_group"
|
||||
|
||||
|
||||
class GroupTemplateView(CanEditMixin, DetailFormView):
|
||||
class GroupTemplateView(PermissionRequiredMixin, DetailFormView):
|
||||
"""Display all users in a given Group
|
||||
Allow adding and removing users from it.
|
||||
"""
|
||||
@@ -100,6 +103,7 @@ class GroupTemplateView(CanEditMixin, DetailFormView):
|
||||
form_class = EditMembersForm
|
||||
pk_url_kwarg = "group_id"
|
||||
template_name = "core/group_detail.jinja"
|
||||
permission_required = "core.change_group"
|
||||
|
||||
def form_valid(self, form):
|
||||
resp = super().form_valid(form)
|
||||
@@ -127,7 +131,7 @@ class GroupTemplateView(CanEditMixin, DetailFormView):
|
||||
return kwargs
|
||||
|
||||
|
||||
class GroupDeleteView(CanEditMixin, DeleteView):
|
||||
class GroupDeleteView(PermissionRequiredMixin, DeleteView):
|
||||
"""Delete a Group."""
|
||||
|
||||
model = Group
|
||||
@@ -135,6 +139,7 @@ class GroupDeleteView(CanEditMixin, DeleteView):
|
||||
pk_url_kwarg = "group_id"
|
||||
template_name = "core/delete_confirm.jinja"
|
||||
success_url = reverse_lazy("core:group_list")
|
||||
permission_required = "core.delete_group"
|
||||
|
||||
|
||||
class PermissionGroupsUpdateView(
|
||||
|
||||
+19
-4
@@ -33,7 +33,10 @@ from django.contrib import messages
|
||||
from django.contrib.auth import login, views
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib.auth.forms import SetPasswordForm
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
|
||||
from django.contrib.auth.mixins import (
|
||||
LoginRequiredMixin,
|
||||
UserPassesTestMixin,
|
||||
)
|
||||
from django.contrib.messages.views import SuccessMessageMixin
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db.models import DateField, F, QuerySet, Sum
|
||||
@@ -58,7 +61,7 @@ from django.views.generic.edit import FormView, UpdateView
|
||||
from honeypot.decorators import check_honeypot
|
||||
|
||||
from core.auth.mixins import CanEditMixin, CanEditPropMixin, CanViewMixin
|
||||
from core.models import Gift, Preferences, User
|
||||
from core.models import Gift, Group, Preferences, User
|
||||
from core.views.forms import (
|
||||
CGUApprovalForm,
|
||||
GiftForm,
|
||||
@@ -296,7 +299,10 @@ class UserTabsMixin(TabedViewMixin):
|
||||
"name": _("Timetable"),
|
||||
}
|
||||
)
|
||||
if self.request.user.is_owner(user):
|
||||
if (
|
||||
user.has_perm("core.change_group")
|
||||
or Group.objects.manageable_by(self.request.user).exists()
|
||||
):
|
||||
tab_list.append(
|
||||
{
|
||||
"url": reverse("core:user_groups", kwargs={"user_id": user.id}),
|
||||
@@ -591,7 +597,7 @@ class UserPreferencesView(UserTabsMixin, UseFragmentsMixin, CanEditMixin, Update
|
||||
return kwargs
|
||||
|
||||
|
||||
class UserUpdateGroupView(UserTabsMixin, CanEditPropMixin, UpdateView):
|
||||
class UserUpdateGroupView(UserPassesTestMixin, UserTabsMixin, UpdateView):
|
||||
"""Edit a user's groups."""
|
||||
|
||||
model = User
|
||||
@@ -601,6 +607,15 @@ class UserUpdateGroupView(UserTabsMixin, CanEditPropMixin, UpdateView):
|
||||
context_object_name = "profile"
|
||||
current_tab = "groups"
|
||||
|
||||
def test_func(self) -> bool:
|
||||
return self.request.user.is_authenticated and (
|
||||
self.request.user.has_perm("core.change_group")
|
||||
or Group.objects.manageable_by(self.request.user).exists()
|
||||
)
|
||||
|
||||
def get_form_kwargs(self) -> dict[str, Any]:
|
||||
return super().get_form_kwargs() | {"request_user": self.request.user}
|
||||
|
||||
|
||||
class UserToolsView(LoginRequiredMixin, UserTabsMixin, TemplateView):
|
||||
"""Displays the logged user's tools."""
|
||||
|
||||
@@ -190,6 +190,17 @@
|
||||
>
|
||||
{{ refilling_fragment }}
|
||||
</div>
|
||||
{% elif customer in request.barmen %}
|
||||
<div class="accordion-content">
|
||||
<p class="alert alert-yellow">
|
||||
{% trans trimmed %}
|
||||
You are able to refill AE accounts.
|
||||
However, it is forbidden to self-refill on a counter.
|
||||
To refill your account, please ask to another barman,
|
||||
or do it in the eboutic.
|
||||
{% endtrans %}
|
||||
</p>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="accordion-content">
|
||||
<p class="alert alert-yellow">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<form
|
||||
id="counter-refill-fragment"
|
||||
hx-trigger="submit"
|
||||
hx-post="{{ action }}"
|
||||
hx-swap="outerHTML"
|
||||
|
||||
@@ -18,7 +18,7 @@ from decimal import Decimal
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from bs4 import BeautifulSoup
|
||||
from bs4 import BeautifulSoup, SoupStrainer
|
||||
from dateutil.relativedelta import relativedelta
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.hashers import make_password
|
||||
@@ -144,6 +144,24 @@ class TestRefilling(TestFullClickBase):
|
||||
),
|
||||
)
|
||||
|
||||
def refill_form_displayed(self, customer: User | Customer | None = None) -> bool:
|
||||
"""Assert the click interface is displayed,
|
||||
then return if it contains the refill form.
|
||||
"""
|
||||
if not customer:
|
||||
customer = self.customer
|
||||
click_res = self.client.get(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": customer.pk},
|
||||
)
|
||||
)
|
||||
assert click_res.status_code == 200
|
||||
soup = BeautifulSoup(
|
||||
click_res.content, "lxml", parse_only=SoupStrainer(id="click-form")
|
||||
)
|
||||
return soup.find(id="counter-refill-fragment") is not None
|
||||
|
||||
def test_refilling_office_fail(self):
|
||||
self.client.force_login(self.club_admin)
|
||||
assert self.refill_user(self.customer, self.club_counter, 10).status_code == 403
|
||||
@@ -197,9 +215,22 @@ class TestRefilling(TestFullClickBase):
|
||||
|
||||
def test_refilling_counter_no_board_member(self):
|
||||
self.login_in_bar(barmen=self.barmen)
|
||||
assert not self.refill_form_displayed()
|
||||
assert self.refill_user(self.customer, self.counter, 10).status_code == 403
|
||||
assert self.updated_amount(self.customer) == 0
|
||||
|
||||
def test_self_refill_fails(self):
|
||||
"""Test that a barman cannot refill itself."""
|
||||
original_amount = self.barmen.customer.amount
|
||||
self.barmen.user_permissions.add(
|
||||
Permission.objects.get(codename="add_refilling")
|
||||
)
|
||||
self.login_in_bar(barmen=self.barmen)
|
||||
|
||||
assert not self.refill_form_displayed(customer=self.barmen)
|
||||
assert self.refill_user(self.barmen, self.counter, 10).status_code == 403
|
||||
assert self.updated_amount(self.customer) == original_amount
|
||||
|
||||
def test_refilling_user_can_not_buy(self):
|
||||
self.login_in_bar(barmen=self.barmen)
|
||||
|
||||
@@ -228,6 +259,7 @@ class TestRefilling(TestFullClickBase):
|
||||
def test_refilling_counter_success(self):
|
||||
self.login_in_bar()
|
||||
|
||||
assert self.refill_form_displayed()
|
||||
assert self.refill_user(self.customer, self.counter, 30).status_code == 302
|
||||
assert self.updated_amount(self.customer) == 30
|
||||
assert self.refill_user(self.customer, self.counter, 10.1).status_code == 302
|
||||
|
||||
+12
-3
@@ -147,7 +147,9 @@ class CounterClick(
|
||||
}
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.customer = get_object_or_404(Customer, user_id=self.kwargs["user_id"])
|
||||
self.customer = get_object_or_404(
|
||||
Customer.objects.select_related("user"), user_id=self.kwargs["user_id"]
|
||||
)
|
||||
obj: Counter = self.get_object()
|
||||
|
||||
if not self.customer.can_buy or self.customer.user.is_banned_counter:
|
||||
@@ -278,7 +280,11 @@ class CounterClick(
|
||||
res["student_card_fragment"] = StudentCardFormFragment.as_fragment()(
|
||||
self.request, customer=self.customer
|
||||
)
|
||||
if self.object.can_refill:
|
||||
if self.object.can_refill and self.customer.user not in self.request.barmen:
|
||||
# The counter must a bar with a barman allowed to refill.
|
||||
# However, a barman, even with the required permission,
|
||||
# cannot refill itself, which means the refilling process always
|
||||
# implies two persons (in order to prevent fraud and genuine errors).
|
||||
res["refilling_fragment"] = RefillingCreateView.as_fragment()(
|
||||
self.request, customer=self.customer, counter=self.object
|
||||
)
|
||||
@@ -312,7 +318,9 @@ class RefillingCreateView(FragmentMixin, CreateView):
|
||||
template_name = "counter/fragments/create_refill.jinja"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.customer: Customer = get_object_or_404(Customer, pk=kwargs["customer_id"])
|
||||
self.customer: Customer = get_object_or_404(
|
||||
Customer.objects.select_related("user"), pk=kwargs["customer_id"]
|
||||
)
|
||||
if not self.customer.can_buy:
|
||||
raise Http404
|
||||
|
||||
@@ -321,6 +329,7 @@ class RefillingCreateView(FragmentMixin, CreateView):
|
||||
if (
|
||||
not is_logged_in_counter(request, counter=self.counter)
|
||||
or not self.counter.can_refill
|
||||
or self.customer.user in self.request.barmen
|
||||
):
|
||||
raise PermissionDenied
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-11-27 11:02+0100\n"
|
||||
"POT-Creation-Date: 2026-12-03 08:59+0100\n"
|
||||
"PO-Revision-Date: 2016-07-18\n"
|
||||
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
|
||||
"Language-Team: AE info <ae.info@utbm.fr>\n"
|
||||
@@ -3841,6 +3841,18 @@ msgstr "Terminer"
|
||||
msgid "Refilling"
|
||||
msgstr "Rechargement"
|
||||
|
||||
#: counter/templates/counter/counter_click.jinja
|
||||
msgid ""
|
||||
"You are able to refill AE accounts. However, it is forbidden to self-refill "
|
||||
"on a counter. To refill your account, please ask to another barman, or do it "
|
||||
"in the eboutic."
|
||||
msgstr ""
|
||||
"Vous avez le droit de recharger des comptes AE."
|
||||
"Cependant, le rechargement de son propre compte sur un comptoir"
|
||||
"est administrativement prohibé."
|
||||
"Pour recharger votre compte, veuillez demander à un autre"
|
||||
"barman ou passer par l'eboutic."
|
||||
|
||||
#: counter/templates/counter/counter_click.jinja
|
||||
msgid ""
|
||||
"As a barman, you are not able to refill any account on your own. An admin "
|
||||
|
||||
Reference in new issue
Block a user