viewsets.py 7.77 KB
Newer Older
1 2
import logging

3 4
from django.conf import settings
from rest_framework.response import Response
5
from rest_framework.viewsets import ViewSet
6 7

from backend_app.checks import check_viewsets
8
from backend_app.models.abstract.essentialModule import EssentialModuleViewSet
9 10 11 12 13 14 15 16
from backend_app.models.campus import CampusViewSet, MainCampusViewSet
from backend_app.models.campusTaggedItem import CampusTaggedItemViewSet
from backend_app.models.city import CityViewSet
from backend_app.models.cityTaggedItem import CityTaggedItemViewSet
from backend_app.models.country import CountryViewSet
from backend_app.models.countryDri import CountryDriViewSet
from backend_app.models.countryScholarship import CountryScholarshipViewSet
from backend_app.models.countryTaggedItem import CountryTaggedItemViewSet
17
from backend_app.models.courseFeedback import CourseFeedback
18 19
from backend_app.models.currency import CurrencyViewSet
from backend_app.models.department import DepartmentViewSet
20
from backend_app.models.exchangeFeedback import ExchangeFeedbackViewSet
21
from backend_app.models.file_picture import FileViewSet, PictureViewSet
22 23
from backend_app.models.for_testing.moderation import ForTestingModerationViewSet
from backend_app.models.for_testing.versioning import ForTestingVersioningViewSet
24
from backend_app.models.language import LanguageViewSet
25 26 27 28 29
from backend_app.models.offer import OfferViewSet
from backend_app.models.pendingModeration import (
    PendingModerationViewSet,
    PendingModerationObjViewSet,
)
30 31 32 33
from backend_app.models.recommendationList import (
    RecommendationListViewSet,
    RecommendationList,
)
34 35 36 37 38 39 40 41 42 43
from backend_app.models.specialty import SpecialtyViewSet
from backend_app.models.tag import TagViewSet
from backend_app.models.university import UniversityViewSet
from backend_app.models.universityDri import UniversityDriViewSet
from backend_app.models.universityInfo import UniversityInfoViewSet
from backend_app.models.universityScholarship import UniversityScholarshipViewSet
from backend_app.models.universitySemestersDates import UniversitySemestersDatesViewSet
from backend_app.models.universityTaggedItem import UniversityTaggedItemViewSet
from backend_app.models.userData import UserDataViewSet
from backend_app.models.version import VersionViewSet
44
from backend_app.permissions.app_permissions import ReadOnly, IsStaff
45
from backend_app.serializers import CourseFeedbackSerializer
Florent Chehab's avatar
Florent Chehab committed
46
from backend_app.settings.defaults import OBJ_MODERATION_PERMISSIONS
47
from base_app.models import UserViewset, User
48

49 50 51 52 53 54 55

class CourseFeedbackViewSet(EssentialModuleViewSet):
    queryset = CourseFeedback.objects.all().prefetch_related()  # pylint: disable=E1101
    serializer_class = CourseFeedbackSerializer
    end_point_route = "courseFeedbacks"


56
ALL_API_VIEWSETS = [
Florent Chehab's avatar
Florent Chehab committed
57
    UserViewset,
58 59 60 61 62 63 64 65 66
    CampusViewSet,
    MainCampusViewSet,
    CampusTaggedItemViewSet,
    CityViewSet,
    CityTaggedItemViewSet,
    CountryViewSet,
    CountryDriViewSet,
    CountryScholarshipViewSet,
    CountryTaggedItemViewSet,
67
    CourseFeedbackViewSet,
68 69 70
    CurrencyViewSet,
    DepartmentViewSet,
    OfferViewSet,
71
    LanguageViewSet,
72 73
    PendingModerationViewSet,
    PendingModerationObjViewSet,
74 75
    FileViewSet,
    PictureViewSet,
76
    ExchangeFeedbackViewSet,
77
    RecommendationListViewSet,
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    SpecialtyViewSet,
    TagViewSet,
    UniversityViewSet,
    UniversityDriViewSet,
    UniversityInfoViewSet,
    UniversityScholarshipViewSet,
    UniversitySemestersDatesViewSet,
    UniversityTaggedItemViewSet,
    UserDataViewSet,
    VersionViewSet,
]

if settings.TESTING:
    # We only register viewsets in a testing environment
    ALL_API_VIEWSETS += [ForTestingModerationViewSet, ForTestingVersioningViewSet]


95
class AppModerationStatusViewSet(ViewSet):
96 97 98 99 100 101 102 103 104
    """
    Viewset to know what is the app moderation status
    """

    # Since AppModerationStatusViewSet doesn't inherit from BaseModelViewSet
    # We need to link here the correct permissions
    permission_classes = (ReadOnly,)
    end_point_route = "serverModerationStatus"

105
    def list(self, request):
106 107 108 109 110 111 112 113
        return Response(
            {
                "activated": settings.MODERATION_ACTIVATED,
                "moderator_level": OBJ_MODERATION_PERMISSIONS["moderator"],
            }
        )


114
class LogFrontendErrorsViewSet(ViewSet):
115 116 117 118 119 120 121
    """
    Viewset to handle the logging of errors coming from the frontend.
    """

    permission_classes = tuple()
    end_point_route = "frontendErrors"

122
    def create(self, request):
123 124 125 126 127 128 129 130 131
        logger = logging.getLogger("frontend")
        data = request.data
        if "componentStack" in data.keys():
            logger.error(request.data["componentStack"])
        else:
            logger.error(request.data)
        return Response(status=201)


132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
class BannedUserViewSet(ViewSet):
    """
    Viewset to be able to ban and un-ban users from the site
    """

    end_point_route = "banned_users"
    permission_classes = (IsStaff,)

    def list(self, request, **kwargs):
        return Response(
            [
                dict(user_id=user.pk, user_login=user.username)
                for user in User.objects.filter(is_banned=True)
            ]
        )

    def update(self, request, pk=None):
        if pk is None:
            return Response(status=403)

        user = User.objects.get(pk=pk)
        if user.is_staff:
            # Prevent ban of admin users
            return Response(status=403)
        user.is_banned = True
        user.save()
        return Response(status=200)

    def delete(self, request, pk=None):
        if pk is None:
            return Response(status=403)

        user = User.objects.get(pk=pk)
        user.is_banned = False
        user.save()
        return Response(status=200)


170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
class DeleteUserViewSet(ViewSet):
    """
    Viewset to handle account deletion
    """

    end_point_route = "emptyUserAccount"
    permission_classes = tuple()

    def create(self, request):
        """
        Line up the user from the request for deletion
        """
        user = request.user
        user.delete_next_time = True
        user.save()
        return Response(status=201)

    def update(self, request):
        # Here only to have the correct routes automatically generated, not to be used.
        return Response(status=403)

    def delete(self, request, pk="osef"):  # don't delete this unused argument!
        """
        Un-Line up the user from the request for deletion
        """
        user = request.user
        user.delete_next_time = False
        user.save()
        return Response(status=200)


201 202 203 204 205 206 207 208 209 210 211
class RecommendationListChangeFollowerViewSet(ViewSet):
    """
    Viewset to be able to add or delete followers on
    a recommendation list
    """

    # Since RecommendationListChangeFollowerViewSet doesn't inherit from BaseModelViewSet
    # We need to link here the correct permissions
    end_point_route = "recommendationListChangeFollower"
    permission_classes = tuple()

212
    def update(self, request, pk=None):
213 214 215 216 217
        if pk is None:
            return Response(status=403)

        recommendation = RecommendationList.objects.get(pk=pk)
        if recommendation.is_public:
218
            recommendation.followers.add(request.user)
219 220 221 222 223 224 225 226 227
            recommendation.save()
            return Response(status=200)
        else:
            return Response(status=403)

    def delete(self, request, pk=None):
        if pk is None:
            return Response(status=403)
        # can delete folower even if list not public
228
        recommendation = RecommendationList.objects.get(pk=pk)
229
        recommendation.followers.remove(request.user)
230 231 232 233
        recommendation.save()
        return Response(status=200)


234 235 236 237
ALL_API_VIEW_VIEWSETS = [
    AppModerationStatusViewSet,
    LogFrontendErrorsViewSet,
    BannedUserViewSet,
238
    RecommendationListChangeFollowerViewSet,
239
    DeleteUserViewSet,
240
]
241 242 243 244

ALL_VIEWSETS = ALL_API_VIEWSETS + ALL_API_VIEW_VIEWSETS

check_viewsets(ALL_VIEWSETS)