Fakultas Ilmu Komputer UI

Commit a8beb185 authored by annisadevin's avatar annisadevin
Browse files

Setting jwt, membuat model dan serializer user serta views create user

parent 5fe4a7fa
Pipeline #123176 passed with stages
in 4 minutes and 13 seconds
......@@ -11,8 +11,8 @@ https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from datetime import timedelta
from pathlib import Path
import dj_database_url
# Build paths inside the project like this: BASE_DIR / 'subdir'.
......@@ -56,6 +56,8 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
'oauth',
'rest_framework_simplejwt',
]
MIDDLEWARE = [
......@@ -164,3 +166,43 @@ for directory in [*STATICFILES_DIRS, STATIC_ROOT]:
# Enable compression and caching features of whitenoise.
# You can remove this if it causes problems on your setup.
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
AUTH_USER_MODEL = "oauth.UserAccount"
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': False,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer', 'JWT',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
\ No newline at end of file
......@@ -19,4 +19,5 @@ from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('', include('oauth.urls'))
]
from django.contrib import admin
from .models import UserAccount
# Register your models here.
admin.site.register(UserAccount)
\ No newline at end of file
from django.apps import AppConfig
class OauthConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'oauth'
# Generated by Django 3.2.13 on 2022-05-01 00:47
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='UserAccount',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(max_length=255, unique=True)),
('first_name', models.CharField(max_length=255)),
('last_name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class UserAccountManager(BaseUserManager):
def create_user(self, username, password=None, **extra_fields):
user = self.model(username=username, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(
'Superuser must be assigned to is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must be assigned to is_superuser=True.')
return self.create_user(username, password, **extra_fields)
class UserAccount(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=255, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserAccountManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_full_name(self):
return "{fname} {lname}".format(fname=self.first_name, lname=self.last_name)
def __str__(self):
return self.username
\ No newline at end of file
from rest_framework import serializers
from .models import UserAccount
from django.contrib.auth.password_validation import validate_password
from rest_framework.exceptions import ValidationError
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = UserAccount
fields = ('username', 'first_name', 'last_name', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
try:
validate_password(password=password, user=instance)
instance.set_password(password)
instance.save()
return instance
except Exception as err:
raise err
from django.test import TestCase
# Create your tests here.
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView
)
from . import views
app_name = 'oauth'
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
path('api/create-user/', views.UserCreate.as_view()),
path('api/resource/', views.ResourceTest.as_view()),
]
from rest_framework import generics
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import UserAccount
from .serializers import UserSerializer
from rest_framework.permissions import AllowAny, IsAuthenticated
from djangorestframework_camel_case.parser import (CamelCaseJSONParser,
CamelCaseMultiPartParser,
CamelCaseFormParser)
from djangorestframework_camel_case.render import (CamelCaseJSONRenderer,
CamelCaseBrowsableAPIRenderer)
class UserCreate(generics.CreateAPIView):
serializer_class = UserSerializer
permission_classes = [AllowAny]
parser_classes = (CamelCaseJSONParser, CamelCaseFormParser, CamelCaseMultiPartParser, )
renderer_classes = (CamelCaseJSONRenderer, CamelCaseBrowsableAPIRenderer, )
def perform_create(self, serializer):
try:
serializer = serializer.save()
return serializer
except Exception as err:
error_message = {'error': err}
raise ValidationError(error_message)
# Hanya untuk test token
class ResourceTest(generics.ListAPIView):
queryset = UserAccount.objects.all()
serializer_class = UserSerializer
permission_classes = [AllowAny]
parser_classes = (CamelCaseJSONParser, CamelCaseFormParser, CamelCaseMultiPartParser, )
renderer_classes = (CamelCaseJSONRenderer, CamelCaseBrowsableAPIRenderer, )
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment