Fakultas Ilmu Komputer UI

accounts.py 5.16 KB
Newer Older
1
import requests
2
from django.contrib.auth import authenticate, login
3
from django.contrib.auth.models import User
4
from rest_framework import viewsets, status
5
from rest_framework.decorators import list_route
6
from rest_framework.permissions import AllowAny
7
from rest_framework.permissions import IsAdminUser, IsAuthenticated
8
9
from rest_framework.response import Response

10
11
from core.lib.permissions import IsAdminOrStudent, IsAdminOrSelfOrReadOnly, IsAdminOrCompany, IsAdminOrSupervisor
from core.models.accounts import Student, Company, Supervisor
12
13
from core.serializers.accounts import UserSerializer, StudentSerializer, CompanySerializer, SupervisorSerializer

14

15
16
17
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
18
    permission_classes = [IsAdminUser]
19

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

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

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

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

43
44
45
46

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

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


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

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

65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
121
122
123
124
125
126
127
128
129
130
131
132
133
class LoginViewSet(viewsets.GenericViewSet):
    permission_classes = (AllowAny, )
    serializer_class = UserSerializer
    queryset = User.objects.all()

    def create(self, request):
        """
        Authenticate user by logging in
        ---
        parameters:
        - name: body
          description: JSON object containing three strings: username, password and login-type. login-type should be either 'sso-ui' or 'company'.
          required: true
          paramType: body
          pytype: RequestSerializer
        """
        username = request.data.get('username')
        password = request.data.get('password')
        login_type = request.data.get('login-type')
        if username is None or password is None or login_type is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        if login_type == "sso-ui":
            r = requests.post('https://api.cs.ui.ac.id/authentication/ldap/v2/',
                              json={"username": username, "password": password})
            resp = r.json()
            if resp.get('state') != 0:
                # create user
                name = resp.get('nama').split(" ")
                first_name = name[0]
                name.pop(0)
                last_name = " ".join(name)
                user, created = User.objects.get_or_create(
                    username=username,
                    email=username + "@ui.ac.id",
                    first_name=first_name,
                    last_name=last_name
                )
                user.set_password(password)
                user.save()
                login(request, user)
                if created:
                    if resp.get('nama_role') == "mahasiswa":
                        student = Student.objects.create(
                            user=user,
                            npm=resp.get("kodeidentitas"),
                            resume=None,
                            phone_number=None
                        )
                        user.save()
                        student.save()
                    else:
                        supervisor = Supervisor.objects.create(
                            user=user,
                            nip=resp.get("kodeidentitas")
                        )
                        user.save()
                        supervisor.save()
                    return Response(status=status.HTTP_201_CREATED)
                return Response(status=status.HTTP_200_OK)
            else:
                return Response(status=status.HTTP_401_UNAUTHORIZED)
        else:
            user = authenticate(username = username, password = password)
            if user is not None:
                login(request, user)
                return Response(status=status.HTTP_200_OK)
            else:
                return Response(status=status.HTTP_401_UNAUTHORIZED)