utils.py 3.17 KB
Newer Older
1
import json
2
import re
3
from contextlib import contextmanager
4
from os.path import join
5
6
7
8
9
from typing import Dict

import reversion
from django.conf import settings
from django.utils import timezone
10
11
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
12

13
from backend_app.settings.defaults import OBJ_MODERATION_PERMISSIONS
14
from base_app.settings.dir_locations import REPO_ROOT_DIR
15
16


17
def get_user_level(user) -> int:
18
19
20
21
22
23
24
25
26
27
28
29
30
    """
    Returns the user level as int.
    """
    if user.is_staff:
        return OBJ_MODERATION_PERMISSIONS["staff"]
    elif is_member("DRI", user):
        return OBJ_MODERATION_PERMISSIONS["DRI"]
    elif is_member("Moderators", user):
        return OBJ_MODERATION_PERMISSIONS["moderator"]
    else:
        return OBJ_MODERATION_PERMISSIONS["authenticated_user"]


31
def is_member(group_name: str, user) -> bool:
32
33
34
35
36
37
38
    """
    Function to know if a user is part of a specific group.
    """
    return group_name in user.cached_groups
    # before:
    # When we were using the standard django model
    # return user.groups.filter(name=group_name).exists()
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53


def clean_route(route):
    """
    Function to clean the route as it is stored in the viewsets.

    :param route: string
    :return: string
    """

    # Remove required parameters
    out = re.sub(r"\(.*\)", "", route)
    # Clean the string
    out = out.replace("//", "/")
    return out.rstrip("/")
54
55
56
57
58


def get_default_theme_settings():
    with open(join(REPO_ROOT_DIR, "frontend/src/config/defaultTheme.json"), "r") as f:
        return json.load(f)
59
60


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class CustomPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = "page_size"
    max_page_size = 500

    def get_paginated_response(self, data):
        previous_link = self.get_previous_link()
        next_link = self.get_next_link()

        return Response(
            dict(
                first=previous_link is None,
                last=next_link is None,
                page=self.page.number,
                pages_count=self.page.paginator.num_pages,
                links=dict(
                    next=self.get_next_link(), previous=self.get_previous_link()
                ),
                number_elements=self.page.paginator.count,
                page_size=self.page_size,
                content=data,
            )
        )


86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
__BOT_USER_CACHE = None


def get_bot_user():
    if settings.TESTING:
        # We need to make sure we have the correct user in testing ENV
        # So we don't use the cache
        from base_app.models import User

        return User.objects.get_or_create(
            username="#bot", defaults=dict(email="osef@fl.fr")
        )[0]
    global __BOT_USER_CACHE
    if __BOT_USER_CACHE is None:
        from base_app.models import User

        __BOT_USER_CACHE = User.objects.get(username="#bot")
    return __BOT_USER_CACHE


def get_module_defaults_for_bot() -> Dict:
    bot = get_bot_user()
    return dict(
        updated_by=bot,
        moderated_by=bot,
        updated_on=timezone.now(),
        moderated_on=timezone.now(),
    )


@contextmanager
def revision_bot():
    with reversion.create_revision():
        yield
        reversion.set_user(get_bot_user())