Fakultas Ilmu Komputer UI

accounts.py 2.24 KB
Newer Older
1
2
from django.contrib.auth.models import User
from rest_framework import viewsets
3
from rest_framework.decorators import list_route
4
from rest_framework.permissions import IsAdminUser, IsAuthenticated, AllowAny
5
6
from rest_framework.response import Response

7
8
from core.lib.permissions import IsAdminOrStudent, IsAdminOrSelfOrReadOnly, IsAdminOrCompany, IsAdminOrSupervisor
from core.models.accounts import Student, Company, Supervisor
9
10
from core.serializers.accounts import UserSerializer, StudentSerializer, CompanySerializer, SupervisorSerializer

11

12
13
14
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
15
    permission_classes = [IsAdminUser]
16

17
    @list_route(methods=['get'], permission_classes=[IsAuthenticated])
18
19
20
21
22
    def me(self, request):
        user = self.request.user
        serializer = UserSerializer(user, context={"request": request})
        return Response(serializer.data)

23
24
25
26
27
28
29
    def get_permissions(self):
        if self.action == "update":
            return [IsAdminOrSelfOrReadOnly(), IsAuthenticated()]
        if self.action == "create":
            return [AllowAny()]
        return super(UserViewSet, self).get_permissions()

30
31
32
33

class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
34
35
36
37
38
39
    permission_classes = [IsAdminUser]

    def get_permissions(self):
        if self.action == "update":
            return [IsAdminOrSelfOrReadOnly(), IsAdminOrStudent()]
        return super(StudentViewSet, self).get_permissions()
40

41
42
43
44

class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer
45
46
47
48
49
50
    permission_classes = [IsAdminUser]

    def get_permissions(self):
        if self.action == "update":
            return [IsAdminOrSelfOrReadOnly(), IsAdminOrCompany()]
        return super(CompanyViewSet, self).get_permissions()
51
52
53
54
55


class SupervisorViewSet(viewsets.ModelViewSet):
    queryset = Supervisor.objects.all()
    serializer_class = SupervisorSerializer
56
    permission_classes = [IsAdminUser]
57

58
59
60
61
    def get_permissions(self):
        if self.action == "update":
            return [IsAdminOrSelfOrReadOnly(), IsAdminOrSupervisor()]
        return super(SupervisorViewSet, self).get_permissions()
62