Aller au contenu

Views

GenericContentPermissionMixinBuilder

Bases: View

Used to build permission mixins.

This view protect any child view that would be showing an object that is restricted based on two properties.

Attributes:

Name Type Description
raised_error

permission to be raised

permission_function(obj, user) staticmethod

Function to test permission with.

Source code in core/views/__init__.py
@staticmethod
def permission_function(obj: Any, user: User) -> bool:
    """Function to test permission with."""
    return False

CanCreateMixin

Bases: View

Protect any child view that would create an object.

Raises:

Type Description
PermissionDenied

If the user has not the necessary permission to create the object of the view.

CanEditPropMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has owner permissions on the child view object.

In other word, you can make a view with this view as parent, and it will be retricted to the users that are in the object's owner_group or that pass the obj.can_be_viewed_by test.

Raises:

Type Description
PermissionDenied

If the user cannot see the object

CanEditMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has permission to edit this view's object.

Raises:

Type Description
PermissionDenied

if the user cannot edit this view's object.

CanViewMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has permission to view this view's object.

Raises:

Type Description
PermissionDenied

if the user cannot edit this view's object.

UserIsRootMixin

Bases: GenericContentPermissionMixinBuilder

Allow only root admins.

Raises:

Type Description
PermissionDenied

if the user isn't root

FormerSubscriberMixin

Bases: AccessMixin

Check if the user was at least an old subscriber.

Raises:

Type Description
PermissionDenied

if the user never subscribed.

SubscriberMixin

Bases: AccessMixin

TabedViewMixin

Bases: View

Basic functions for displaying tabs in the template.

QuickNotifMixin

get_context_data(**kwargs)

Add quick notifications to context.

Source code in core/views/__init__.py
def get_context_data(self, **kwargs):
    """Add quick notifications to context."""
    kwargs = super().get_context_data(**kwargs)
    kwargs["quick_notifs"] = []
    for n in self.quick_notif_list:
        kwargs["quick_notifs"].append(settings.SITH_QUICK_NOTIF[n])
    for key, val in settings.SITH_QUICK_NOTIF.items():
        for gk in self.request.GET:
            if key == gk:
                kwargs["quick_notifs"].append(val)
    return kwargs

DetailFormView

Bases: SingleObjectMixin, FormView

Class that allow both a detail view and a form view.

get_object()

Get current group from id in url.

Source code in core/views/__init__.py
def get_object(self):
    """Get current group from id in url."""
    return self.cached_object

cached_object()

Optimisation on group retrieval.

Source code in core/views/__init__.py
@cached_property
def cached_object(self):
    """Optimisation on group retrieval."""
    return super().get_object()

AllowFragment

Add is_fragment to templates. It's only True if the request is emitted by htmx

SithFile

Bases: Model

clean()

Cleans up the file.

Source code in core/models.py
def clean(self):
    """Cleans up the file."""
    super().clean()
    if "/" in self.name:
        raise ValidationError(_("Character '/' not authorized in name"))
    if self == self.parent:
        raise ValidationError(_("Loop in folder tree"), code="loop")
    if self == self.parent or (
        self.parent is not None and self in self.get_parent_list()
    ):
        raise ValidationError(_("Loop in folder tree"), code="loop")
    if self.parent and self.parent.is_file:
        raise ValidationError(
            _("You can not make a file be a children of a non folder file")
        )
    if (
        self.parent is None
        and SithFile.objects.exclude(id=self.id)
        .filter(parent=None, name=self.name)
        .exists()
    ) or (
        self.parent
        and self.parent.children.exclude(id=self.id).filter(name=self.name).exists()
    ):
        raise ValidationError(_("Duplicate file"), code="duplicate")
    if self.is_folder:
        if self.file:
            try:
                import imghdr

                if imghdr.what(None, self.file.read()) not in [
                    "gif",
                    "png",
                    "jpeg",
                ]:
                    self.file.delete()
                    self.file = None
            except:  # noqa E722 I don't know the exception that can be raised
                self.file = None
        self.mime_type = "inode/directory"
    if self.is_file and (self.file is None or self.file == ""):
        raise ValidationError(_("You must provide a file"))

apply_rights_recursively(*, only_folders=False)

Apply the rights of this file to all children recursively.

Parameters:

Name Type Description Default
only_folders bool

If True, only apply the rights to SithFiles that are folders.

False
Source code in core/models.py
def apply_rights_recursively(self, *, only_folders: bool = False) -> None:
    """Apply the rights of this file to all children recursively.

    Args:
        only_folders: If True, only apply the rights to SithFiles that are folders.
    """
    file_ids = []
    explored_ids = [self.id]
    while len(explored_ids) > 0:  # find all children recursively
        file_ids.extend(explored_ids)
        next_level = SithFile.objects.filter(parent_id__in=explored_ids)
        if only_folders:
            next_level = next_level.filter(is_folder=True)
        explored_ids = list(next_level.values_list("id", flat=True))
    for through in (SithFile.view_groups.through, SithFile.edit_groups.through):
        # force evaluation. Without this, the iterator yields nothing
        groups = list(
            through.objects.filter(sithfile_id=self.id).values_list(
                "group_id", flat=True
            )
        )
        # delete previous rights
        through.objects.filter(sithfile_id__in=file_ids).delete()
        through.objects.bulk_create(  # create new rights
            [through(sithfile_id=f, group_id=g) for f in file_ids for g in groups]
        )

copy_rights()

Copy, if possible, the rights of the parent folder.

Source code in core/models.py
def copy_rights(self):
    """Copy, if possible, the rights of the parent folder."""
    if self.parent is not None:
        self.edit_groups.set(self.parent.edit_groups.all())
        self.view_groups.set(self.parent.view_groups.all())

move_to(parent)

Move a file to a new parent. parent must be a SithFile with the is_folder=True property. Otherwise, this function doesn't change anything. This is done only at the DB level, so that it's very fast for the user. Indeed, this function doesn't modify SithFiles recursively, so it stays efficient even with top-level folders.

Source code in core/models.py
def move_to(self, parent):
    """Move a file to a new parent.
    `parent` must be a SithFile with the `is_folder=True` property. Otherwise, this function doesn't change
    anything.
    This is done only at the DB level, so that it's very fast for the user. Indeed, this function doesn't modify
    SithFiles recursively, so it stays efficient even with top-level folders.
    """
    if not parent.is_folder:
        return
    self.parent = parent
    self.clean()
    self.save()

MultipleFileInput

Bases: ClearableFileInput

MultipleFileField(*args, **kwargs)

Bases: _MultipleFieldMixin, FileField

Source code in core/views/files.py
def __init__(self, *args, **kwargs):
    kwargs.setdefault("widget", MultipleFileInput())
    super().__init__(*args, **kwargs)

MultipleImageField(*args, **kwargs)

Bases: _MultipleFieldMixin, ImageField

Source code in core/views/files.py
def __init__(self, *args, **kwargs):
    kwargs.setdefault("widget", MultipleFileInput())
    super().__init__(*args, **kwargs)

AddFilesForm

Bases: Form

FileListView

Bases: ListView

FileEditView

Bases: CanEditMixin, UpdateView

FileEditPropForm

Bases: ModelForm

FileEditPropView

Bases: CanEditPropMixin, UpdateView

FileView

Bases: CanViewMixin, DetailView, FormMixin

Handle the upload of new files into a folder.

handle_clipboard(request, obj) staticmethod

Handle the clipboard in the view.

This method can fail, since it does not catch the exceptions coming from below, allowing proper handling in the calling view. Use this method like this:

FileView.handle_clipboard(request, self.object)

request is usually the self.request obj in your view obj is the SithFile object you want to put in the clipboard, or where you want to paste the clipboard

Source code in core/views/files.py
@staticmethod
def handle_clipboard(request, obj):
    """Handle the clipboard in the view.

    This method can fail, since it does not catch the exceptions coming from
    below, allowing proper handling in the calling view.
    Use this method like this:

        FileView.handle_clipboard(request, self.object)

    `request` is usually the self.request obj in your view
    `obj` is the SithFile object you want to put in the clipboard, or
             where you want to paste the clipboard
    """
    if "delete" in request.POST:
        for f_id in request.POST.getlist("file_list"):
            file = SithFile.objects.filter(id=f_id).first()
            if file:
                file.delete()
    if "clear" in request.POST:
        request.session["clipboard"] = []
    if "cut" in request.POST:
        for f_id_str in request.POST.getlist("file_list"):
            f_id = int(f_id_str)
            if (
                f_id in [c.id for c in obj.children.all()]
                and f_id not in request.session["clipboard"]
            ):
                request.session["clipboard"].append(f_id)
    if "paste" in request.POST:
        for f_id in request.session["clipboard"]:
            file = SithFile.objects.filter(id=f_id).first()
            if file:
                file.move_to(obj)
        request.session["clipboard"] = []
    request.session.modified = True

FileDeleteView

Bases: AllowFragment, CanEditPropMixin, DeleteView

FileModerationView

Bases: AllowFragment, ListView

FileModerateView

Bases: CanEditPropMixin, SingleObjectMixin

RealGroup

Bases: Group

RealGroups are created by the developer.

Most of the time they match a number in settings to be easily used for permissions.

EditMembersForm(*args, **kwargs)

Bases: Form

Add and remove members from a Group.

Source code in core/views/group.py
def __init__(self, *args, **kwargs):
    self.current_users = kwargs.pop("users", [])
    super().__init__(*args, **kwargs)

    self.fields["users_added"] = forms.ModelMultipleChoiceField(
        label=_("Users to add to group"),
        help_text=_("Search users to add (one or more)."),
        required=False,
        widget=AutoCompleteSelectMultipleUser,
        queryset=User.objects.exclude(id__in=self.current_users).all(),
    )

    self.fields["users_removed"] = forms.ModelMultipleChoiceField(
        User.objects.filter(id__in=self.current_users).all(),
        label=_("Users to remove from group"),
        required=False,
        widget=forms.CheckboxSelectMultiple,
    )

GroupListView

Bases: CanEditMixin, ListView

Displays the Group list.

GroupEditView

Bases: CanEditMixin, UpdateView

Edit infos of a Group.

GroupCreateView

Bases: CanCreateMixin, CreateView

Add a new Group.

GroupTemplateView

Bases: CanEditMixin, DetailFormView

Display all users in a given Group Allow adding and removing users from it.

GroupDeleteView

Bases: CanEditMixin, DeleteView

Delete a Group.

LockError

Bases: Exception

There was a lock error on the object.

Page

Bases: Model

The page class to build a Wiki Each page may have a parent and it's URL is of the form my.site/page/// It has an ID field, but don't use it, since it's only there for DB part, and because compound primary key is awkward! Prefere querying pages with Page.get_page_by_full_name().

Be careful with the _full_name attribute: this field may not be valid until you call save(). It's made for fast query, but don't rely on it when playing with a Page object, use get_full_name() instead!

save(*args, **kwargs)

Performs some needed actions before and after saving a page in database.

Source code in core/models.py
def save(self, *args, **kwargs):
    """Performs some needed actions before and after saving a page in database."""
    locked = kwargs.pop("force_lock", False)
    if not locked:
        locked = self.is_locked()
    if not locked:
        raise NotLocked("The page is not locked and thus can not be saved")
    self.full_clean()
    if not self.id:
        super().save(
            *args, **kwargs
        )  # Save a first time to correctly set _full_name
    # This reset the _full_name just before saving to maintain a coherent field quicker for queries than the
    # recursive method
    # It also update all the children to maintain correct names
    self._full_name = self.get_full_name()
    for c in self.children.all():
        c.save()
    super().save(*args, **kwargs)
    self.unset_lock()

get_page_by_full_name(name) staticmethod

Quicker to get a page with that method rather than building the request every time.

Source code in core/models.py
@staticmethod
def get_page_by_full_name(name):
    """Quicker to get a page with that method rather than building the request every time."""
    return Page.objects.filter(_full_name=name).first()

clean()

Cleans up only the name for the moment, but this can be used to make any treatment before saving the object.

Source code in core/models.py
def clean(self):
    """Cleans up only the name for the moment, but this can be used to make any treatment before saving the object."""
    if "/" in self.name:
        self.name = self.name.split("/")[-1]
    if (
        Page.objects.exclude(pk=self.pk)
        .filter(_full_name=self.get_full_name())
        .exists()
    ):
        raise ValidationError(_("Duplicate page"), code="duplicate")
    super().clean()
    if self.parent is not None and self in self.get_parent_list():
        raise ValidationError(_("Loop in page tree"), code="loop")

is_locked()

Is True if the page is locked, False otherwise.

This is where the timeout is handled, so a locked page for which the timeout is reach will be unlocked and this function will return False.

Source code in core/models.py
def is_locked(self):
    """Is True if the page is locked, False otherwise.

    This is where the timeout is handled,
    so a locked page for which the timeout is reach will be unlocked and this
    function will return False.
    """
    if self.lock_timeout and (
        timezone.now() - self.lock_timeout > timedelta(minutes=5)
    ):
        self.unset_lock()
    return (
        self.lock_user
        and self.lock_timeout
        and (timezone.now() - self.lock_timeout < timedelta(minutes=5))
    )

set_lock(user)

Sets a lock on the current page or raise an AlreadyLocked exception.

Source code in core/models.py
def set_lock(self, user):
    """Sets a lock on the current page or raise an AlreadyLocked exception."""
    if self.is_locked() and self.get_lock() != user:
        raise AlreadyLocked("The page is already locked by someone else")
    self.lock_user = user
    self.lock_timeout = timezone.now()
    super().save()

set_lock_recursive(user)

Locks recursively all the child pages for editing properties.

Source code in core/models.py
def set_lock_recursive(self, user):
    """Locks recursively all the child pages for editing properties."""
    for p in self.children.all():
        p.set_lock_recursive(user)
    self.set_lock(user)

unset_lock_recursive()

Unlocks recursively all the child pages.

Source code in core/models.py
def unset_lock_recursive(self):
    """Unlocks recursively all the child pages."""
    for p in self.children.all():
        p.unset_lock_recursive()
    self.unset_lock()

unset_lock()

Always try to unlock, even if there is no lock.

Source code in core/models.py
def unset_lock(self):
    """Always try to unlock, even if there is no lock."""
    self.lock_user = None
    self.lock_timeout = None
    super().save()

get_lock()

Returns the page's mutex containing the time and the user in a dict.

Source code in core/models.py
def get_lock(self):
    """Returns the page's mutex containing the time and the user in a dict."""
    if self.lock_user:
        return self.lock_user
    raise NotLocked("The page is not locked and thus can not return its user")

get_full_name()

Computes the real full_name of the page based on its name and its parent's name You can and must rely on this function when working on a page object that is not freshly fetched from the DB (For example when treating a Page object coming from a form).

Source code in core/models.py
def get_full_name(self):
    """Computes the real full_name of the page based on its name and its parent's name
    You can and must rely on this function when working on a page object that is not freshly fetched from the DB
    (For example when treating a Page object coming from a form).
    """
    if self.parent is None:
        return self.name
    return f"{self.parent.get_full_name()}/{self.name}"

PageRev

Bases: Model

True content of the page.

Each page object has a revisions field that is a list of PageRev, ordered by date. my_page.revisions.last() gives the PageRev object that is the most up-to-date, and thus, is the real content of the page. The content is in PageRev.title and PageRev.content .

CanEditPagePropMixin

PageListView

Bases: CanViewMixin, ListView

PageView

Bases: CanViewMixin, DetailView

PageHistView

Bases: CanViewMixin, DetailView

PageRevView

Bases: CanViewMixin, DetailView

PageCreateView

Bases: CanCreateMixin, CreateView

PagePropView

Bases: CanEditPagePropMixin, UpdateView

PageEditViewBase

Bases: CanEditMixin, UpdateView

PageEditView

PageDeleteView

Bases: CanEditPagePropMixin, DeleteView

Notification

Bases: Model

Club

Bases: Model

The Club class, made as a tree to allow nice tidy organization.

check_loop()

Raise a validation error when a loop is found within the parent list.

Source code in club/models.py
def check_loop(self):
    """Raise a validation error when a loop is found within the parent list."""
    objs = []
    cur = self
    while cur.parent is not None:
        if cur in objs:
            raise ValidationError(_("You can not make loops in clubs"))
        objs.append(cur)
        cur = cur.parent

is_owned_by(user)

Method to see if that object can be super edited by the given user.

Source code in club/models.py
def is_owned_by(self, user):
    """Method to see if that object can be super edited by the given user."""
    if user.is_anonymous:
        return False
    return user.is_board_member

can_be_edited_by(user)

Method to see if that object can be edited by the given user.

Source code in club/models.py
def can_be_edited_by(self, user):
    """Method to see if that object can be edited by the given user."""
    return self.has_rights_in_club(user)

can_be_viewed_by(user)

Method to see if that object can be seen by the given user.

Source code in club/models.py
def can_be_viewed_by(self, user):
    """Method to see if that object can be seen by the given user."""
    sub = User.objects.filter(pk=user.pk).first()
    if sub is None:
        return False
    return sub.was_subscribed

get_membership_for(user)

Return the current membership the given user.

Note

The result is cached.

Source code in club/models.py
def get_membership_for(self, user: User) -> Membership | None:
    """Return the current membership the given user.

    Note:
        The result is cached.
    """
    if user.is_anonymous:
        return None
    membership = cache.get(f"membership_{self.id}_{user.id}")
    if membership == "not_member":
        return None
    if membership is None:
        membership = self.members.filter(user=user, end_date=None).first()
        if membership is None:
            cache.set(f"membership_{self.id}_{user.id}", "not_member")
        else:
            cache.set(f"membership_{self.id}_{user.id}", membership)
    return membership

NotificationList

Bases: ListView

User

Bases: AbstractUser

Defines the base user class, useable in every app.

This is almost the same as the auth module AbstractUser since it inherits from it, but some fields are required, and the username is generated automatically with the name of the user (see generate_username()).

Added field: nick_name, date_of_birth Required fields: email, first_name, last_name, date_of_birth

cached_groups: list[Group] property

Get the list of groups this user is in.

The result is cached for the default duration (should be 5 minutes)

Returns: A list of all the groups this user is in.

is_in_group(*, pk=None, name=None)

Check if this user is in the given group. Either a group id or a group name must be provided. If both are passed, only the id will be considered.

The group will be fetched using the given parameter. If no group is found, return False. If a group is found, check if this user is in the latter.

Returns:

Type Description
bool

True if the user is the group, else False

Source code in core/models.py
def is_in_group(self, *, pk: int | None = None, name: str | None = None) -> bool:
    """Check if this user is in the given group.
    Either a group id or a group name must be provided.
    If both are passed, only the id will be considered.

    The group will be fetched using the given parameter.
    If no group is found, return False.
    If a group is found, check if this user is in the latter.

    Returns:
         True if the user is the group, else False
    """
    if pk is not None:
        group: Optional[Group] = get_group(pk=pk)
    elif name is not None:
        group: Optional[Group] = get_group(name=name)
    else:
        raise ValueError("You must either provide the id or the name of the group")
    if group is None:
        return False
    if group.id == settings.SITH_GROUP_PUBLIC_ID:
        return True
    if group.id == settings.SITH_GROUP_SUBSCRIBERS_ID:
        return self.is_subscribed
    if group.id == settings.SITH_GROUP_OLD_SUBSCRIBERS_ID:
        return self.was_subscribed
    if group.id == settings.SITH_GROUP_ROOT_ID:
        return self.is_root
    if group.is_meta:
        # check if this group is associated with a club
        group.__class__ = MetaGroup
        club = group.associated_club
        if club is None:
            return False
        membership = club.get_membership_for(self)
        if membership is None:
            return False
        if group.name.endswith(settings.SITH_MEMBER_SUFFIX):
            return True
        return membership.role > settings.SITH_MAXIMUM_FREE_ROLE
    return group in self.cached_groups

age()

Return the age this user has the day the method is called. If the user has not filled his age, return 0.

Source code in core/models.py
@cached_property
def age(self) -> int:
    """Return the age this user has the day the method is called.
    If the user has not filled his age, return 0.
    """
    if self.date_of_birth is None:
        return 0
    today = timezone.now()
    age = today.year - self.date_of_birth.year
    # remove a year if this year's birthday is yet to come
    age -= (today.month, today.day) < (
        self.date_of_birth.month,
        self.date_of_birth.day,
    )
    return age

get_short_name()

Returns the short name for the user.

Source code in core/models.py
def get_short_name(self):
    """Returns the short name for the user."""
    if self.nick_name:
        return self.nick_name
    return self.first_name + " " + self.last_name

get_display_name()

Returns the display name of the user.

A nickname if possible, otherwise, the full name.

Source code in core/models.py
def get_display_name(self) -> str:
    """Returns the display name of the user.

    A nickname if possible, otherwise, the full name.
    """
    if self.nick_name:
        return "%s (%s)" % (self.get_full_name(), self.nick_name)
    return self.get_full_name()

get_age()

Returns the age.

Source code in core/models.py
def get_age(self):
    """Returns the age."""
    today = timezone.now()
    born = self.date_of_birth
    return (
        today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    )

get_family(godfathers_depth=4, godchildren_depth=4)

Get the family of the user, with the given depth.

Parameters:

Name Type Description Default
godfathers_depth NonNegativeInt

The number of generations of godfathers to fetch

4
godchildren_depth NonNegativeInt

The number of generations of godchildren to fetch

4

Returns:

Type Description
set[through]

A list of family relationships in this user's family

Source code in core/models.py
def get_family(
    self,
    godfathers_depth: NonNegativeInt = 4,
    godchildren_depth: NonNegativeInt = 4,
) -> set[User.godfathers.through]:
    """Get the family of the user, with the given depth.

    Args:
        godfathers_depth: The number of generations of godfathers to fetch
        godchildren_depth: The number of generations of godchildren to fetch

    Returns:
        A list of family relationships in this user's family
    """
    res = []
    for depth, key, reverse_key in [
        (godfathers_depth, "from_user_id", "to_user_id"),
        (godchildren_depth, "to_user_id", "from_user_id"),
    ]:
        if depth == 0:
            continue
        links = list(User.godfathers.through.objects.filter(**{key: self.id}))
        res.extend(links)
        for _ in range(1, depth):  # noqa: F402 we don't care about gettext here
            ids = [getattr(c, reverse_key) for c in links]
            links = list(
                User.godfathers.through.objects.filter(
                    **{f"{key}__in": ids}
                ).exclude(id__in=[r.id for r in res])
            )
            if not links:
                break
            res.extend(links)
    return set(res)

email_user(subject, message, from_email=None, **kwargs)

Sends an email to this User.

Source code in core/models.py
def email_user(self, subject, message, from_email=None, **kwargs):
    """Sends an email to this User."""
    if from_email is None:
        from_email = settings.DEFAULT_FROM_EMAIL
    send_mail(subject, message, from_email, [self.email], **kwargs)

generate_username()

Generates a unique username based on the first and last names.

For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

Returns:

Type Description
str

The generated username.

Source code in core/models.py
def generate_username(self) -> str:
    """Generates a unique username based on the first and last names.

    For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

    Returns:
        The generated username.
    """

    def remove_accents(data):
        return "".join(
            x
            for x in unicodedata.normalize("NFKD", data)
            if unicodedata.category(x)[0] == "L"
        ).lower()

    user_name = (
        remove_accents(self.first_name[0] + self.last_name)
        .encode("ascii", "ignore")
        .decode("utf-8")
    )
    # load all usernames which could conflict with the new one.
    # we need to actually load them, instead of performing a count,
    # because we cannot be sure that two usernames refer to the
    # actual same word (eg. tmore and tmoreau)
    possible_conflicts: list[str] = list(
        User.objects.filter(username__startswith=user_name).values_list(
            "username", flat=True
        )
    )
    nb_conflicts = sum(
        1 for name in possible_conflicts if name.rstrip(string.digits) == user_name
    )
    if nb_conflicts > 0:
        user_name += str(nb_conflicts)  # exemple => exemple1
    self.username = user_name
    return user_name

is_owner(obj)

Determine if the object is owned by the user.

Source code in core/models.py
def is_owner(self, obj):
    """Determine if the object is owned by the user."""
    if hasattr(obj, "is_owned_by") and obj.is_owned_by(self):
        return True
    if hasattr(obj, "owner_group") and self.is_in_group(pk=obj.owner_group.id):
        return True
    return self.is_root

can_edit(obj)

Determine if the object can be edited by the user.

Source code in core/models.py
def can_edit(self, obj):
    """Determine if the object can be edited by the user."""
    if hasattr(obj, "can_be_edited_by") and obj.can_be_edited_by(self):
        return True
    if hasattr(obj, "edit_groups"):
        for pk in obj.edit_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    if isinstance(obj, User) and obj == self:
        return True
    return self.is_owner(obj)

can_view(obj)

Determine if the object can be viewed by the user.

Source code in core/models.py
def can_view(self, obj):
    """Determine if the object can be viewed by the user."""
    if hasattr(obj, "can_be_viewed_by") and obj.can_be_viewed_by(self):
        return True
    if hasattr(obj, "view_groups"):
        for pk in obj.view_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    return self.can_edit(obj)

clubs_with_rights()

The list of clubs where the user has rights

Source code in core/models.py
@cached_property
def clubs_with_rights(self) -> list[Club]:
    """The list of clubs where the user has rights"""
    memberships = self.memberships.ongoing().board().select_related("club")
    return [m.club for m in memberships]

Gift

Bases: Model

Preferences

Bases: Model

SithLoginView

Bases: LoginView

The login View.

SithPasswordChangeView

Bases: PasswordChangeView

Allows a user to change its password.

SithPasswordChangeDoneView

Bases: PasswordChangeDoneView

Allows a user to change its password.

SithPasswordResetView

Bases: PasswordResetView

Allows someone to enter an email address for resetting password.

SithPasswordResetDoneView

Bases: PasswordResetDoneView

Confirm that the reset email has been sent.

SithPasswordResetConfirmView

Bases: PasswordResetConfirmView

Provide a reset password form.

SithPasswordResetCompleteView

Bases: PasswordResetCompleteView

Confirm the password has successfully been reset.

UserCreationView

Bases: FormView

UserTabsMixin

UserView

Bases: UserTabsMixin, CanViewMixin, DetailView

Display a user's profile.

UserPicturesView

Bases: UserTabsMixin, CanViewMixin, DetailView

Display a user's pictures.

UserGodfathersView

Bases: UserTabsMixin, CanViewMixin, DetailView, FormView

Display a user's godfathers.

UserGodfathersTreeView

Bases: UserTabsMixin, CanViewMixin, DetailView

Display a user's family tree.

UserStatsView

Bases: UserTabsMixin, CanViewMixin, DetailView

Display a user's stats.

UserMiniView

Bases: CanViewMixin, DetailView

Display a user's profile.

UserListView

Bases: ListView, CanEditPropMixin

Displays the user list.

UserUpdateProfileView

Bases: UserTabsMixin, CanEditMixin, UpdateView

Edit a user's profile.

remove_restricted_fields(request)

Removes edit_once and board_only fields.

Source code in core/views/user.py
def remove_restricted_fields(self, request):
    """Removes edit_once and board_only fields."""
    for i in self.edit_once:
        if getattr(self.form.instance, i) and not (
            request.user.is_board_member or request.user.is_root
        ):
            self.form.fields.pop(i, None)
    for i in self.board_only:
        if not (request.user.is_board_member or request.user.is_root):
            self.form.fields.pop(i, None)

UserClubView

Bases: UserTabsMixin, CanViewMixin, DetailView

Display the user's club(s).

UserPreferencesView

Bases: UserTabsMixin, CanEditMixin, UpdateView

Edit a user's preferences.

UserUpdateGroupView

Bases: UserTabsMixin, CanEditPropMixin, UpdateView

Edit a user's groups.

UserToolsView

Bases: LoginRequiredMixin, QuickNotifMixin, UserTabsMixin, TemplateView

Displays the logged user's tools.

UserAccountBase

Bases: UserTabsMixin, DetailView

Base class for UserAccount.

UserAccountView

Bases: UserAccountBase

Display a user's account.

UserAccountDetailView

Bases: UserAccountBase, YearMixin, MonthMixin

Display a user's account for month.

GiftCreateView

Bases: CreateView

GiftDeleteView

Bases: CanEditPropMixin, DeleteView

forbidden(request, exception)

Source code in core/views/__init__.py
def forbidden(request, exception):
    context = {"next": request.path, "form": LoginForm()}
    if popup := request.resolver_match.kwargs.get("popup"):
        context["popup"] = popup
    return HttpResponseForbidden(render(request, "core/403.jinja", context=context))

not_found(request, exception)

Source code in core/views/__init__.py
def not_found(request, exception):
    return HttpResponseNotFound(
        render(request, "core/404.jinja", context={"exception": exception})
    )

internal_servor_error(request)

Source code in core/views/__init__.py
def internal_servor_error(request):
    request.sentry_last_event_id = last_event_id
    return HttpResponseServerError(render(request, "core/500.jinja"))

can_edit_prop(obj, user)

Can the user edit the properties of the object.

Parameters:

Name Type Description Default
obj Any

Object to test for permission

required
user User

core.models.User to test permissions against

required

Returns:

Type Description
bool

True if user is authorized to edit object properties else False

Examples:

if not can_edit_prop(self.object ,request.user):
    raise PermissionDenied
Source code in core/views/__init__.py
def can_edit_prop(obj: Any, user: User) -> bool:
    """Can the user edit the properties of the object.

    Args:
        obj: Object to test for permission
        user: core.models.User to test permissions against

    Returns:
        True if user is authorized to edit object properties else False

    Examples:
        ```python
        if not can_edit_prop(self.object ,request.user):
            raise PermissionDenied
        ```
    """
    return obj is None or user.is_owner(obj)

can_edit(obj, user)

Can the user edit the object.

Parameters:

Name Type Description Default
obj Any

Object to test for permission

required
user User

core.models.User to test permissions against

required

Returns:

Type Description
bool

True if user is authorized to edit object else False

Examples:

if not can_edit(self.object, request.user):
    raise PermissionDenied
Source code in core/views/__init__.py
def can_edit(obj: Any, user: User) -> bool:
    """Can the user edit the object.

    Args:
        obj: Object to test for permission
        user: core.models.User to test permissions against

    Returns:
        True if user is authorized to edit object else False

    Examples:
        ```python
        if not can_edit(self.object, request.user):
            raise PermissionDenied
        ```
    """
    if obj is None or user.can_edit(obj):
        return True
    return can_edit_prop(obj, user)

can_view(obj, user)

Can the user see the object.

Parameters:

Name Type Description Default
obj Any

Object to test for permission

required
user User

core.models.User to test permissions against

required

Returns:

Type Description
bool

True if user is authorized to see object else False

Examples:

if not can_view(self.object ,request.user):
    raise PermissionDenied
Source code in core/views/__init__.py
def can_view(obj: Any, user: User) -> bool:
    """Can the user see the object.

    Args:
        obj: Object to test for permission
        user: core.models.User to test permissions against

    Returns:
        True if user is authorized to see object else False

    Examples:
        ```python
        if not can_view(self.object ,request.user):
            raise PermissionDenied
        ```
    """
    if obj is None or user.can_view(obj):
        return True
    return can_edit(obj, user)

send_file(request, file_id, file_class=SithFile, file_attr='file')

Send a protected file, if the user can see it.

In prod, the server won't handle the download itself, but set the appropriate headers in the response to make the reverse-proxy deal with it. In debug mode, the server will directly send the file.

Source code in core/views/files.py
def send_file(
    request: HttpRequest,
    file_id: int,
    file_class: type[SithFile] = SithFile,
    file_attr: str = "file",
) -> HttpResponse:
    """Send a protected file, if the user can see it.

    In prod, the server won't handle the download itself,
    but set the appropriate headers in the response to make the reverse-proxy
    deal with it.
    In debug mode, the server will directly send the file.
    """
    f = get_object_or_404(file_class, id=file_id)
    if not can_view(f, request.user) and not is_logged_in_counter(request):
        raise PermissionDenied
    name = getattr(f, file_attr).name

    response = HttpResponse(
        headers={"Content-Disposition": f'inline; filename="{quote(name)}"'}
    )
    if not settings.DEBUG:
        # When receiving a response with the Accel-Redirect header,
        # the reverse proxy will automatically handle the file sending.
        # This is really hard to test (thus isn't tested)
        # so please do not mess with this.
        response["Content-Type"] = ""  # automatically set by nginx
        response["X-Accel-Redirect"] = quote(urljoin(settings.MEDIA_URL, name))
        return response

    filepath = settings.MEDIA_ROOT / name
    # check if file exists on disk
    if not filepath.exists():
        raise Http404
    with open(filepath, "rb") as filename:
        response.content = FileWrapper(filename)
        response["Content-Type"] = mimetypes.guess_type(filepath)[0]
        response["Last-Modified"] = http_date(f.date.timestamp())
        response["Content-Length"] = filepath.stat().st_size
        return response

index(request, context=None)

Source code in core/views/site.py
def index(request, context=None):
    from com.views import NewsListView

    return NewsListView.as_view()(request)

notification(request, notif_id)

Source code in core/views/site.py
def notification(request, notif_id):
    notif = Notification.objects.filter(id=notif_id).first()
    if notif:
        if notif.type not in settings.SITH_PERMANENT_NOTIFICATIONS:
            notif.viewed = True
        else:
            notif.callback()
        notif.save()
        return redirect(notif.url)
    return redirect("/")

search_user(query)

Source code in core/views/site.py
def search_user(query):
    try:
        # slugify turns everything into ascii and every whitespace into -
        # it ends by removing duplicate - (so ' - ' will turn into '-')
        # replace('-', ' ') because search is whitespace based
        query = slugify(query).replace("-", " ")
        # TODO: is this necessary?
        query = html.escape(query)
        res = (
            SearchQuerySet()
            .models(User)
            .autocomplete(auto=query)
            .order_by("-last_login")
            .load_all()[:20]
        )
        return [r.object for r in res]
    except TypeError:
        return []

search_club(query, *, as_json=False)

Source code in core/views/site.py
def search_club(query, *, as_json=False):
    clubs = []
    if query:
        clubs = Club.objects.filter(name__icontains=query).all()
        clubs = clubs[:5]
        if as_json:
            # Re-loads json to avoid double encoding by JsonResponse, but still benefit from serializers
            clubs = json.loads(serializers.serialize("json", clubs, fields=("name")))
        else:
            clubs = list(clubs)
    return clubs

search_view(request)

Source code in core/views/site.py
@login_required
def search_view(request):
    result = {
        "users": search_user(request.GET.get("query", "")),
        "clubs": search_club(request.GET.get("query", "")),
    }
    return render(request, "core/search.jinja", context={"result": result})

search_user_json(request)

Source code in core/views/site.py
@login_required
def search_user_json(request):
    result = {"users": search_user(request.GET.get("query", ""))}
    return JsonResponse(result)

search_json(request)

Source code in core/views/site.py
@login_required
def search_json(request):
    result = {
        "users": search_user(request.GET.get("query", "")),
        "clubs": search_club(request.GET.get("query", ""), as_json=True),
    }
    return JsonResponse(result)

logout(request)

The logout view.

Source code in core/views/user.py
def logout(request):
    """The logout view."""
    return views.logout_then_login(request)

password_root_change(request, user_id)

Allows a root user to change someone's password.

Source code in core/views/user.py
def password_root_change(request, user_id):
    """Allows a root user to change someone's password."""
    if not request.user.is_root:
        raise PermissionDenied
    user = User.objects.filter(id=user_id).first()
    if not user:
        raise Http404("User not found")
    if request.method == "POST":
        form = views.SetPasswordForm(user=user, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect("core:password_change_done")
    else:
        form = views.SetPasswordForm(user=user)
    return TemplateResponse(
        request, "core/password_change.jinja", {"form": form, "target": user}
    )

delete_user_godfather(request, user_id, godfather_id, is_father)

Source code in core/views/user.py
def delete_user_godfather(request, user_id, godfather_id, is_father):
    user_is_admin = request.user.is_root or request.user.is_board_member
    if user_id != request.user.id and not user_is_admin:
        raise PermissionDenied()
    user = get_object_or_404(User, id=user_id)
    to_remove = get_object_or_404(User, id=godfather_id)
    if is_father:
        user.godfathers.remove(to_remove)
    else:
        user.godchildren.remove(to_remove)
    return redirect("core:user_godfathers", user_id=user_id)