Fakultas Ilmu Komputer UI

Commit 0da601e4 authored by Ryan Karyadiputera's avatar Ryan Karyadiputera
Browse files

test3

parent bf926c95
Pipeline #81486 failed with stage
in 2 minutes and 20 seconds
......@@ -6,7 +6,8 @@ from .models import (
Administrator,
User,
Periode,
Config
Config,
Role
)
from django.contrib import admin
......@@ -59,3 +60,8 @@ class PeriodeAdmin(admin.ModelAdmin):
@admin.register(Config)
class ConfigAdmin(admin.ModelAdmin):
pass
@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
pass
\ No newline at end of file
# Generated by Django 3.1.3 on 2021-05-18 01:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0004_delete_user'),
]
operations = [
migrations.AddField(
model_name='supervisorlembaga',
name='lastlogin',
field=models.DateField(blank=True, null=True, verbose_name='Last login'),
),
]
# Generated by Django 3.1.3 on 2021-05-24 11:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0005_supervisorlembaga_lastlogin'),
]
operations = [
migrations.AlterField(
model_name='supervisorlembaga',
name='lastlogin',
field=models.DateField(blank=True, null=True, verbose_name='last login'),
),
]
# Generated by Django 3.1.3 on 2021-05-24 21:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0006_auto_20210524_1109'),
]
operations = [
migrations.RemoveField(
model_name='supervisorlembaga',
name='lastlogin',
),
]
# Generated by Django 3.1.3 on 2021-06-02 02:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('authentication', '0007_remove_supervisorlembaga_lastlogin'),
]
operations = [
migrations.CreateModel(
name='Role',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('role', models.CharField(blank=True, max_length=150, verbose_name='role')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='role', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'role',
'verbose_name_plural': 'role',
},
),
]
......@@ -18,6 +18,20 @@ ORG_CODE = {}
with open(settings.SSO_UI_ORG_DETAIL_FILE_PATH, 'r') as ORG_CODE_FILE:
ORG_CODE.update(json.load(ORG_CODE_FILE))
class Role(models.Model):
"""User Profile Supervisor Sekolah model."""
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='role')
role = models.CharField('role', max_length=150, blank=True)
class Meta:
verbose_name = 'role'
verbose_name_plural = 'role'
def __str__(self):
"""Return username of the user."""
return self.user.username
class SupervisorSekolah(models.Model):
"""User Profile Supervisor Sekolah model."""
......@@ -33,6 +47,16 @@ class SupervisorSekolah(models.Model):
"""Return username of the user."""
return self.user.username
def save(self,*args,**kwargs):
created = not self.pk
super().save(*args,**kwargs)
if created:
user = User.objects.get(username=self)
Role.objects.create(
user=user,
role='Supervisor Sekolah'
)
class SupervisorLembaga(models.Model):
"""User Profile Supervisor Lembaga model."""
......@@ -50,6 +74,16 @@ class SupervisorLembaga(models.Model):
"""Return username of the user."""
return self.user.username
def save(self,*args,**kwargs):
created = not self.pk
super().save(*args,**kwargs)
if created:
user = User.objects.get(username=self)
Role.objects.create(
user=user,
role='Supervisor Lembaga'
)
class Administrator(models.Model):
"""User Profile Supervisor Sekolah model."""
......@@ -65,6 +99,16 @@ class Administrator(models.Model):
"""Return username of the user."""
return self.user.username
def save(self,*args,**kwargs):
created = not self.pk
super().save(*args,**kwargs)
if created:
user = User.objects.get(username=self)
Role.objects.create(
user=user,
role='Administrator'
)
class Periode(models.Model):
"""Periode model for Mahasiswa model."""
......@@ -103,6 +147,16 @@ class Mahasiswa(models.Model):
"""Return username of the user."""
return self.user.username
def save(self,*args,**kwargs):
created = not self.pk
super().save(*args,**kwargs)
if created:
user = User.objects.get(username=self)
Role.objects.create(
user=user,
role='Mahasiswa'
)
class KoordinatorKuliah(models.Model):
"""User Profile Kordinator Kuliah model."""
......@@ -118,6 +172,16 @@ class KoordinatorKuliah(models.Model):
"""Return username of the user."""
return self.user.username
def save(self,*args,**kwargs):
created = not self.pk
super().save(*args,**kwargs)
if created:
user = User.objects.get(username=self)
Role.objects.create(
user=user,
role='Koordinator Praktikum'
)
class Config(models.Model):
"""User Profile Kordinator Kuliah model."""
......
......@@ -5,5 +5,5 @@ class Role(Enum):
MHS = "Mahasiswa"
SSK = "Supervisor Sekolah"
SLB = "Supervisor Lembaga"
KKL = "Koordinator Kuliah"
KKL = "Koordinator Praktikum"
ADM = "Administrator"
......@@ -16,6 +16,8 @@ from lembaga.serializers import LembagaSerializer
from rest_framework_jwt.settings import api_settings
from django.contrib.auth import authenticate
import datetime
JWT_PAYLOAD_HANDLER = api_settings.JWT_PAYLOAD_HANDLER
JWT_ENCODE_HANDLER = api_settings.JWT_ENCODE_HANDLER
......@@ -40,10 +42,11 @@ class UserSerializer(serializers.ModelSerializer):
"""User serializer json field."""
full_name = serializers.CharField(source='get_full_name')
role = serializers.CharField(source='role.role')
class Meta:
model = User
fields = ['username', 'email', 'full_name']
fields = ['username', 'email', 'full_name', 'role', 'is_active']
class AdministratorSerializer(serializers.ModelSerializer):
......@@ -122,11 +125,10 @@ class SupervisorLembagaRegistrationSerializer(serializers.ModelSerializer):
"""Serializer json field for registration."""
profile = LembagaProfileSerializer(required=False)
full_name = serializers.CharField(source='get_full_name')
class Meta:
model = User
fields = ['username', 'full_name', 'email', 'password', 'profile']
fields = ['username', 'first_name', 'last_name', 'email', 'password', 'profile']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data): # pragma: no cover
......@@ -134,12 +136,17 @@ class SupervisorLembagaRegistrationSerializer(serializers.ModelSerializer):
try:
lembaga = Lembaga.objects.get(nama=profile_data['lembaga'])
user = User.objects.create_user(**validated_data)
user.is_active = False
user.save()
SupervisorLembaga.objects.create(
user=user,
lembaga=lembaga,
jabatan=profile_data['jabatan']
)
Role.objects.create(
user=user,
role='Supervisor Lembaga'
)
return user
except Lembaga.DoesNotExist:
raise serializers.ValidationError(
......@@ -239,9 +246,9 @@ class ManualSSOLoginSerializer(serializers.Serializer):
elif role == "Mahasiswa":
if Mahasiswa.objects.get(user=user):
role = "Mahasiswa"
elif role == "Koordinator Kuliah":
elif role == "Koordinator Praktikum":
if KoordinatorKuliah.objects.get(user=user):
role = "Koordinator Kuliah"
role = "Koordinator Praktikum"
else:
raise serializers.ValidationError('Invalid role')
except Mahasiswa.DoesNotExist:
......@@ -249,7 +256,7 @@ class ManualSSOLoginSerializer(serializers.Serializer):
except SupervisorSekolah.DoesNotExist:
raise serializers.ValidationError('You are not Supervisor Sekolah')
except KoordinatorKuliah.DoesNotExist:
raise serializers.ValidationError('You are not Koordinator Kuliah')
raise serializers.ValidationError('You are not Koordinator Praktikum')
payload = JWT_PAYLOAD_HANDLER(user)
jwt_token = JWT_ENCODE_HANDLER(payload)
update_last_login(None, user)
......
......@@ -12,7 +12,6 @@ from lembaga.models import (
Institusi,
Tema,
Lembaga,
LingkupKerja,
)
from .serializers import (
UserSerializer,
......@@ -108,11 +107,6 @@ class ModelsTest(TestCase):
tema = Tema.objects.create(
nama="testing"
)
lingkup_kerja = LingkupKerja.objects.create(
nama="testing"
)
self.lembaga = Lembaga.objects.create(
nama="testing",
jenis_pelayanan="testing",
......@@ -124,7 +118,6 @@ class ModelsTest(TestCase):
beneficaries="test_beneficaries"
)
self.lembaga.lingkup_kerja.add(lingkup_kerja)
self.lembaga.gambar = self.get_image_file()
self.lembaga.save()
......@@ -300,10 +293,6 @@ class SerializersTest(TestCase):
nama="testing"
)
lingkup_kerja = LingkupKerja.objects.create(
nama="testing"
)
self.lembaga = Lembaga.objects.create(
nama="testing",
jenis_pelayanan="testing",
......@@ -315,7 +304,6 @@ class SerializersTest(TestCase):
alamat="test_alamat"
)
self.lembaga.lingkup_kerja.add(lingkup_kerja)
self.lembaga.gambar = self.get_image_file()
self.lembaga.save()
......@@ -402,7 +390,7 @@ class SerializersTest(TestCase):
data = self.user_serializer.data
self.assertEqual(
set(data),
set(['username', 'email', 'full_name'])
set(['username', 'email', 'full_name', 'role', 'is_active'])
)
def test_profile_mahasiswa_serializer_contains_valid_data(self):
......@@ -461,7 +449,7 @@ class SerializersTest(TestCase):
data = self.user_registration_serializer.data
self.assertEqual(
set(data),
set(['username', 'full_name', 'email'])
set(['username', 'first_name', 'last_name', 'email'])
)
def test_user_login_serializer_contains_valid_data(self):
......@@ -557,17 +545,11 @@ class SSOUITest(TestCase):
supervisor_sekolah=None
)
def test_login_url_exists(self):
"""Test if login url exists and redirects to CAS server (response code 302)."""
response = self.client.get(reverse('authentication:login-sivitas'))
self.assertEqual(response.status_code, 302)
self.assertTrue(response.url.startswith(settings.CAS_SERVER_URL))
def test_logout_url_exists(self):
"""Test if logout url exists and redirects to CAS server (response code 302)."""
response = self.client.get(reverse('authentication:logout'))
self.assertEqual(response.status_code, 302)
self.assertTrue(response.url.startswith(settings.CAS_SERVER_URL))
# def test_login_url_exists(self):
# """Test if login url exists and redirects to CAS server (response code 302)."""
# response = self.client.get(reverse('authentication:login-sivitas'))
# self.assertEqual(response.status_code, 302)
# self.assertTrue(response.url.startswith(settings.CAS_SERVER_URL))
# def test_profile_can_save_attributes_if_user_mahasiswa_not_yet_registered(self):
# """Test if Profile Mahasiswa model can save the attributes from CAS."""
......@@ -726,10 +708,6 @@ class AuthenticationJSONWebTokenTest(APITestCase):
nama="testing"
)
lingkup_kerja = LingkupKerja.objects.create(
nama="testing"
)
self.lembaga = Lembaga.objects.create(
nama="testing",
jenis_pelayanan="testing",
......@@ -741,7 +719,6 @@ class AuthenticationJSONWebTokenTest(APITestCase):
alamat="test_alamat"
)
self.lembaga.lingkup_kerja.add(lingkup_kerja)
self.lembaga.gambar = self.get_image_file()
self.lembaga.save()
......@@ -784,7 +761,8 @@ class AuthenticationJSONWebTokenTest(APITestCase):
self.registration_data = {
"username": "usernamevalid1",
"full_name": "User Name1",
"first_name": "User",
"last_name": "Name1",
"email": "usernamevalid1@test.com",
"password": "123456789",
"profile": {
......@@ -795,7 +773,8 @@ class AuthenticationJSONWebTokenTest(APITestCase):
self.registration_data_unknown_lembaga = {
"username": "dhafin",
"full_name": "Razaqa Dhafin",
"first_name": "Razaqa Dhafin",
"last_name": "Razaqa Dhafin",
"email": "dhafin@test.com",
"password": "1234567",
"profile": {
......@@ -1005,7 +984,7 @@ class AuthenticationJSONWebTokenTest(APITestCase):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_invalid_manual_sso_login_for_koordinator_kuliah_with_valid_role(self):
response = self.client.post(reverse('authentication:login-sso'), {"username": "test", "password": "test", "role": "Koordinator Kuliah"})
response = self.client.post(reverse('authentication:login-sso'), {"username": "test", "password": "test", "role": "Koordinator Praktikum"})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
# Administrator
......
......@@ -5,7 +5,8 @@ from django.urls import include, path
app_name = 'authentication'
urlpatterns = [
path('login/sivitas/', APILoginView.as_view(), name='login-sivitas'),
path('logout/', APILogoutView.as_view(), name='logout'),
# path('logout/', APILogoutView.as_view(), name='logout'),
path('logout/', views.ManualLogoutView.as_view(), name='logout'),
path('register/supervisor-lembaga/', views.UserRegistrationView.as_view(), name='register-supervisor-lembaga'),
path('login/supervisor-lembaga/', views.UserLoginView.as_view(), name='login-supervisor-lembaga'),
path('register/supervisor-lembaga/', views.UserRegistrationView.as_view(), name='register-supervisor-lembaga'),
......@@ -19,5 +20,5 @@ urlpatterns = [
path('profile/administrator', views.UserProfileAdministratorView.as_view(), name='profile-administrator'),
path('profile/user', views.UserProfileUserView.as_view(), name='profile-user'),
path('periode/list', views.PeriodeListView.as_view(), name='periode-list'),
path('login/sso/', views.ManualSSOLoginView.as_view(), name='login-sso')
]
path('login/sso/', views.ManualSSOLoginView.as_view(), name='login-sso'),
]
\ No newline at end of file
......@@ -21,10 +21,12 @@ from .serializers import (
AdministratorLoginSerializer
)
from .role import Role
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.http import JsonResponse, HttpResponseRedirect
from django.contrib.auth.models import update_last_login
from django.shortcuts import render
from rest_framework import status
from rest_framework import viewsets, status
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
......@@ -105,6 +107,14 @@ class ManualSSOLoginView(RetrieveAPIView):
return Response(response, status=status.HTTP_200_OK)
class ManualLogoutView(RetrieveAPIView):
permission_classes = (AllowAny,)
def get(self, request):
update_last_login(datetime.now(), request.user)
return HttpResponseRedirect("http://ppl-berkah.herokuapp.com/")
class UserProfileMahasiswaView(RetrieveAPIView): # pragma: no cover
permission_classes = (IsAuthenticated,)
......@@ -223,7 +233,7 @@ class UserProfileKoordinatorKuliahView(RetrieveAPIView): # pragma: no cover
response = {
response_field[0]: 'False',
response_field[1]: status_code,
response_field[2]: 'Can not find user data for Koordinator Kuliah'
response_field[2]: 'Can not find user data for Koordinator Praktikum'
}
return Response(response, status=status_code)
......
error_message_404_supervisor_sekolah = 'Can not find user data for Supervisor Sekolah'
error_message_404_koordinator_kuliah = 'Can not find user data for Koordinator Kuliah'
error_message_404_koordinator_kuliah = 'Can not find user data for Koordinator Praktikum'
error_message_404_administrator = 'Can not find user data for Administrator'
error_message_404_mahasiswa = 'Can not find user data for Mahasiswa'
error_message_404_supervisor_lembaga = 'Can not find user data for Supervisor Lembaga'
......
from django.db import models
from lembaga.models import Lembaga, LingkupKerja
from lembaga.models import Lembaga
from authentication.models import Administrator, KoordinatorKuliah, Mahasiswa, \
SupervisorLembaga, SupervisorSekolah
from django.core.files.storage import FileSystemStorage
......@@ -122,6 +122,22 @@ class LaporanAkhirPraktikum(AttributeLaporanPraktikum):
profil_lembaga = models.FileField(blank=True, null=True)
umpan_balik = models.CharField(max_length=255, blank=True, default=" ")
def getLembagaID(self):
return self.lembaga.id
def updateTahun(self):
currentYear = self.lembaga.last_activity
newYear = self.periode_praktikum[:4]
if newYear != '' and (currentYear == None or currentYear < int(newYear)):
return newYear
else:
return currentYear
def save(self, *args, **kwargs):
Lembaga.objects.filter(id = self.getLembagaID()).update(last_activity = self.updateTahun())
super().save(*args,**kwargs)
def __str__(self): # pragma: no cover
return self.nama_laporan
......
......@@ -44,6 +44,13 @@ class SupervisorLembagaSpesificSerializer(serializers.ModelSerializer):
model = SupervisorLembaga
fields = ['user']
class SupervisorLembagaUsernameSerializer(serializers.ModelSerializer):
"""Supervisor Lembaga serializer json field."""
class Meta:
model = User
fields = ['username', 'last_login', 'is_active']
class MahasiswaWithJenisPraktikumSerializer(MahasiswaSerializer):
......
from laporan_praktikum.models import Praktikum, KelolaLaporanPraktikum, MahasiswaPraktikum
from authentication.models import Mahasiswa, SupervisorLembaga, SupervisorSekolah, User, Periode
from lembaga.models import Lembaga, Tema, Institusi, LingkupKerja
from lembaga.models import Lembaga, Tema, Institusi
from django.test import TestCase
from django.core.files import File
from io import BytesIO
......@@ -91,8 +91,6 @@ class SupervisorSekolahDashboardAPITest(APITestCase):
Institusi
), tema=mixer.blend(
Tema
), lingkup_kerja=mixer.blend(
LingkupKerja
), gambar=self.get_image_file()
), user=mixer.blend(User)
)
......
......@@ -15,7 +15,7 @@ from laporan_praktikum.models import (
from laporan_praktikum.serializers import (
RiwayatLaporanPraktikumMahasiswaSerializer
)
from lembaga.models import Lembaga, Tema, Institusi, LingkupKerja
from lembaga.models import Lembaga, Tema, Institusi
from laporan_praktikum.models import LaporanAkhirPraktikum
from django.test import TestCase
......@@ -365,8 +365,6 @@ class PeriodeAPITest(APITestCase):
Institusi
), tema=mixer.blend(
Tema
), lingkup_kerja=mixer.blend(
LingkupKerja
), gambar=self.get_image_file()
), user=mixer.blend(
User
......@@ -487,8 +485,6 @@ class KoordinatorKuliahDashboardAPITest(APITestCase):
Institusi
), tema=mixer.blend(
Tema
), lingkup_kerja=mixer.blend(
LingkupKerja
), gambar=self.get_image_file()
), user=mixer.blend(
User
......@@ -859,9 +855,7 @@ class AdministratorDashboardAPITest(APITestCase):
Institusi
), tema=mixer.blend(
Tema
), lingkup_kerja=mixer.blend(
LingkupKerja
)
),
), user=mixer.blend(
User,
username="username2",
......
......@@ -80,6 +80,10 @@ urlpatterns = [
views.get_supervisor_lembaga_by_id_lembaga,
name='list-supervisor-lembaga-by-id-lembaga'),
path('supervisor-lembaga/user/<str:username>/',
views.get_supervisor_lembaga_by_username,
name='list-supervisor-lembaga-by-id-lembaga'),
path('supervisor-lembaga/praktikum-mahasiswa/riwayat-laporan/',
views_riwayat.get_riwayat_laporan_by_supervisor_lembaga,
name='riwayat-laporan-mahasiswa-by-supervisor-lembaga'),
......
......@@ -45,6 +45,7 @@ from laporan_praktikum.serializers import (
SupervisorSekolahListMahasiswaSerializer,
SupervisorLembagaListMahasiswaSerializer,
SupervisorLembagaSpesificSerializer,
SupervisorLembagaUsernameSerializer,
RiwayatLaporanPraktikumMahasiswaSerializer,
PraktikumSerializer,
KoordinatorKuliahListMahasiswaSerializer,
......@@ -91,7 +92,7 @@ def parse_time_custom(datetime_inp):
response_field = ['success', 'status_code', 'message']
error_message_404_supervisor_sekolah = 'Can not find user data for Supervisor Sekolah'
error_message_404_koordinator_kuliah = 'Can not find user data for Koordinator Kuliah'
error_message_404_koordinator_kuliah = 'Can not find user data for Koordinator Praktikum'
error_message_404_administrator = 'Can not find user data for Administrator'
error_message_404_mahasiswa = 'Can not find user data for Mahasiswa'
error_message_404_supervisor_lembaga = 'Can not find user data for Supervisor Lembaga'