Files
RosterChief/club/services/access.py
Bernard Siebens 581cc81ba7 Add group/club-wide event audiences and a Resend email backend
Events can now target members.Group audiences alongside teams, or go
club_wide (every ACTIVE ClubMembership member for the event's season)
instead of specific teams/groups -- the two are mutually exclusive,
enforced in EventForm/EventSeriesForm.clean() since an M2M can't be
validated via a DB CheckConstraint or Event.clean() (no PK yet). Attendance
sync (events/signals.py) now reacts to GroupMembership and ClubMembership
changes the same way it already did for TeamMembership. Authorization:
club.services.access.groups_manageable_by mirrors teams_managed_by (all
groups for an ADMIN, else only the ones the user belongs to -- Group has no
manager/owner concept); a non-admin needs at least one managed team or
belonged-to group to create/edit an event, club_wide stays admin-only, and
EventManagerRequiredMixin gained a get_groups() hook so a non-admin who
creates a group-only event isn't immediately locked out of managing it.

Also adds rosterchief.mail.ResendEmailBackend, an HTTP-API-based Django
email backend for Resend (resend.com) using the existing `requests`
dependency -- no new SDK. Opt in via DJANGO_EMAIL_BACKEND and RESEND_API_KEY;
every Django-sent email (allauth's password reset included) follows
whichever EMAIL_BACKEND is configured, so this covers all of them for free.
Resend's own SMTP relay remains a valid code-free alternative, documented
alongside it in .env.production.example.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 12:02:26 +02:00

182 lines
7.4 KiB
Python

"""Per-club access decisions.
All authorisation goes through this module (ARCHITECTURE §3): stored
``ClubRole`` rows plus object-scoped facts — coach/manager is *derived* from
``StaffAssignment`` (never a ClubRole), and parent/guardian from the family
graph. ADMIN is the club-wide override.
Two axes, deliberately separate:
* **Authority** (``teams_managed_by``, ``can_edit_event``) requires a
*management* position, and only for the **current season** — a StaffAssignment
is per-season, so a former coach's authority expires with it. (A ``ClubRole``,
by contrast, is permanent and survives a lapsed membership.)
* **Visibility** (``teams_staffed_by`` → ``members_visible_to``) covers *any*
staff position, so support staff (physio, kit manager) can see the roster they
work with without gaining any authority over it.
"""
from django.db.models import Q, QuerySet
from django.utils import timezone
from authentication.models import User
from club.models import Club, ClubRole, Season
from events.models import Event
from members.models import FamilyMembership, Group, Member
from teams.models import StaffAssignment, Team
#: Derived (never stored) roles.
COACH = "coach"
MANAGER = "manager"
COACH_MANAGER = "coach_manager"
def current_season(club: Club) -> Season | None:
"""The club's season covering today. Staff authority is scoped to it."""
return Season.covering(club, timezone.localdate())
def event_season(event: Event) -> Season | None:
"""The season an event belongs to (explicit, else derived from its start)."""
return event.season or Season.covering(event.club, event.start.date())
def has_club_role(user: User, club: Club, role: ClubRole.Roles) -> bool:
return ClubRole.objects.filter(member__user=user, club=club, role=role).exists()
def is_club_admin(user: User, club: Club) -> bool:
return has_club_role(user, club, ClubRole.Roles.ADMIN)
def has_management_access(user: User, club: Club) -> bool:
"""Anyone with real authority in the club: ADMIN/EDITOR, or *any* current-season
staff assignment (coach, team manager, physio, ...).
Deliberately excludes the plain MEMBER role -- every signed-up player (or club
member generally) holds that automatically the moment their ClubMembership goes
active (club/signals.py), so it says nothing about whether someone is staff.
"""
elevated = ClubRole.objects.filter(member__user=user, club=club, role__in=(ClubRole.Roles.ADMIN, ClubRole.Roles.EDITOR)).exists()
return elevated or teams_staffed_by(user, club).exists()
def is_coach_manager(user: User, club: Club) -> bool:
"""Derived from a current-season StaffAssignment in a *management* position."""
return StaffAssignment.objects.filter(
member__user=user,
team__club=club,
position__management_position=True,
season=current_season(club),
).exists()
def roles_in_club(user: User, club: Club) -> set[str]:
"""The user's roles in ``club``, including the derived COACH_MANAGER role."""
roles = set(ClubRole.objects.filter(member__user=user, club=club).values_list("role", flat=True))
if is_coach_manager(user, club):
roles.add(COACH_MANAGER)
return roles
def teams_managed_by(user: User, club: Club) -> QuerySet[Team]:
"""Teams the user has authority over: all for an ADMIN, else the ones they
manage *this season* (management position only)."""
if is_club_admin(user, club):
return Team.objects.filter(club=club)
return Team.objects.filter(
club=club,
staff_assignments__member__user=user,
staff_assignments__position__management_position=True,
staff_assignments__season=current_season(club),
).distinct()
def groups_manageable_by(user: User, club: Club) -> QuerySet[Group]:
"""Groups the user may schedule an event for: all for an ADMIN, else only
the ones they're themselves a member of -- unlike Team, Group has no
manager/owner concept, so membership is the only claim there is to check."""
if is_club_admin(user, club):
return Group.objects.filter(club=club)
return Group.objects.filter(club=club, memberships__member__user=user).distinct()
def teams_staffed_by(user: User, club: Club) -> QuerySet[Team]:
"""Teams the user is on the staff of this season, management or not.
Visibility only — being a team's physio grants sight of the roster, never
authority over it.
"""
return Team.objects.filter(
club=club,
staff_assignments__member__user=user,
staff_assignments__season=current_season(club),
).distinct()
def members_visible_to(user: User, club: Club) -> QuerySet[Member]:
"""Members the user may see.
ADMIN: everyone linked to the club (membership, roster, staff or role).
Otherwise: themselves, their children, and the current-season players *and*
staff of every team they're staffed on.
"""
if is_club_admin(user, club):
return Member.objects.filter(Q(member_of__club=club) | Q(team_memberships__team__club=club) | Q(staff_assignments__team__club=club) | Q(roles__club=club)).distinct()
me = Member.objects.filter(user=user).first()
if me is None:
return Member.objects.none()
children = Member.objects.filter(
family_memberships__role=FamilyMembership.FamilyRole.CHILD,
family_memberships__family__memberships__member=me,
family_memberships__family__memberships__role__in=[FamilyMembership.FamilyRole.PARENT, FamilyMembership.FamilyRole.GUARDIAN],
)
season = current_season(club)
teams = teams_staffed_by(user, club)
roster = Member.objects.filter(Q(team_memberships__team__in=teams, team_memberships__season=season) | Q(staff_assignments__team__in=teams, staff_assignments__season=season))
visible = {me.pk} | set(children.values_list("pk", flat=True)) | set(roster.values_list("pk", flat=True))
return Member.objects.filter(pk__in=visible)
def can_edit_event(user: User, event: Event) -> bool:
"""ADMIN/EDITOR in the club, the event's owner, or a manager of one of its
teams *for that event's season*."""
club = event.club
if is_club_admin(user, club) or has_club_role(user, club, ClubRole.Roles.EDITOR):
return True
if event.created_by_id is not None and event.created_by.user_id == user.pk:
return True
return StaffAssignment.objects.filter(
member__user=user,
team__in=event.teams.all(),
position__management_position=True,
season=event_season(event),
).exists()
def can_manage_shop(user: User, club: Club) -> bool:
return is_club_admin(user, club)
def can_add_news(user: User, club: Club) -> bool:
"""ADMIN, EDITOR, or a current-season coach_manager -- who's trusted to
author club content, not just anyone on staff (a physio shouldn't post news)."""
return is_club_admin(user, club) or has_club_role(user, club, ClubRole.Roles.EDITOR) or is_coach_manager(user, club)
def can_publish_news(user: User, club: Club) -> bool:
"""Only ADMIN/EDITOR may push a news item live -- the release-flow gate."""
return is_club_admin(user, club) or has_club_role(user, club, ClubRole.Roles.EDITOR)
def can_edit_news(user: User, news_item) -> bool:
"""Broad while it's a draft (anyone who could create one); editor/admin-only
once published -- an editor is accountable for what's actually live."""
if news_item.status == news_item.Status.PUBLISHED:
return can_publish_news(user, news_item.club)
return can_add_news(user, news_item.club)