feat: uuid token

This commit is contained in:
Ahmet Kaan GÜMÜŞ 2024-07-03 05:37:18 +03:00
parent a73553ab81
commit b90fa4ae3c
30 changed files with 223 additions and 142 deletions

View file

@ -2,5 +2,5 @@ from django.apps import AppConfig
class HelloConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'hello'
default_auto_field = "django.db.models.BigAutoField"
name = "hello"

View file

@ -1,3 +0,0 @@
from django.db import models
# Create your models here.

View file

@ -1,3 +0,0 @@
from django.test import TestCase
# Create your tests here.

View file

@ -1,12 +1,13 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tJango.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tJango.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
@ -18,5 +19,5 @@ def main():
execute_from_command_line(sys.argv)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -1,4 +1,5 @@
asgiref==3.8.1
Django==5.0.6
djangorestframework==3.15.2
ruff==0.5.0
sqlparse==0.5.0

View file

@ -11,6 +11,6 @@ import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tJango.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tJango.settings")
application = get_asgi_application()

View file

@ -20,7 +20,7 @@ BASE_DIR = Path(__file__).resolve().parent.parent
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-samo*m*8!2jb+0b(7e8e$to@suc7z^5uy*4lm6ojjq5w9jj9h#'
SECRET_KEY = "django-insecure-samo*m*8!2jb+0b(7e8e$to@suc7z^5uy*4lm6ojjq5w9jj9h#"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
@ -31,62 +31,63 @@ ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'hello',
'user',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"rest_framework.authtoken",
"hello",
"user",
"user_token",
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
]
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = 'tJango.urls'
ROOT_URLCONF = "tJango.urls"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = 'tJango.wsgi.application'
WSGI_APPLICATION = "tJango.wsgi.application"
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
@ -96,16 +97,16 @@ DATABASES = {
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
@ -113,9 +114,9 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"
USE_I18N = True
@ -125,9 +126,9 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

View file

@ -14,18 +14,18 @@ Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import DefaultRouter
# from user import views as user_views
router = DefaultRouter()
# router.register(r'users', user_views.UserViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls')),
path('hello/', include('hello.urls')),
path('admin/', admin.site.urls),
path('api/v1/', include('user.urls')),
path("", include(router.urls)),
path("api-auth/", include("rest_framework.urls")),
path("hello/", include("hello.urls")),
path("admin/", admin.site.urls),
path("api/v1/users/", include("user.urls")),
path("api/v1/user-tokens/", include("user_token.urls")),
]

View file

@ -11,6 +11,6 @@ import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tJango.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tJango.settings")
application = get_wsgi_application()

View file

@ -1,5 +1,4 @@
from django.contrib import admin
from .models import User, Token
from .models import User
admin.site.register(User)
admin.site.register(Token)

View file

@ -2,5 +2,5 @@ from django.apps import AppConfig
class UserConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'user'
default_auto_field = "django.db.models.BigAutoField"
name = "user"

View file

@ -1,22 +1,28 @@
# Generated by Django 5.0.6 on 2024-06-28 00:23
# Generated by Django 5.0.6 on 2024-07-03 01:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
dependencies = []
operations = [
migrations.CreateModel(
name='User',
name="User",
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=15)),
('date_created', models.DateTimeField(auto_now_add=True)),
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("username", models.CharField(max_length=15, unique=True)),
("date_created", models.DateTimeField(auto_now_add=True)),
],
),
]

View file

@ -1,18 +0,0 @@
# Generated by Django 5.0.6 on 2024-06-29 23:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(max_length=15, unique=True),
),
]

View file

@ -1,22 +0,0 @@
# Generated by Django 5.0.6 on 2024-07-02 11:13
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0002_alter_user_username'),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token', models.CharField(max_length=16)),
('username', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Token', to='user.user')),
],
),
]

View file

@ -7,10 +7,3 @@ class User(models.Model):
def __str__(self):
return self.username
class Token(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Token')
token = models.CharField(max_length=16)
def __str__(self):
return str(self.username)

View file

@ -1,20 +1,12 @@
from rest_framework import serializers
from .models import User, Token
from .models import User
from user_token.serializers import UserTokenSerializer
class TokenSerializer(serializers.ModelSerializer):
class Meta:
model = Token
fields = '__all__'
read_only_fields = ['username', 'token']
class UserSerializer(serializers.ModelSerializer):
token = TokenSerializer(read_only=True)
tokens = UserTokenSerializer(many=True)
class Meta:
model = User
fields = '__all__'
read_only_fields = ['date_created']
def token(self, object):
print("İMDAAAAAAAAAAAAAAAAAAAAAAAAAAT")
print(object.username)
fields = "__all__"
read_only_fields = ["date_created", "tokens"]

View file

@ -1,3 +1,3 @@
from django.test import TestCase
# from django.test import TestCase
# Create your tests here.

View file

@ -3,8 +3,8 @@ from rest_framework.routers import DefaultRouter
from user import views as user_views
router = DefaultRouter()
router.register(r'users', user_views.UserViewSet)
router.register(r" ", user_views.UserViewSet)
urlpatterns = [
path('', include(router.urls)),
]
path("", include(router.urls)),
]

View file

@ -1,10 +1,11 @@
from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.viewsets import ModelViewSet
# from rest_framework.permissions import IsAuthenticatedOrReadOnly
from .models import User
from .serializers import UserSerializer
class UserViewSet(ReadOnlyModelViewSet):
class UserViewSet(ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# permission_classes = [IsAuthenticatedOrReadOnly]

0
user_token/__init__.py Normal file
View file

View file

@ -1,3 +1,5 @@
from django.contrib import admin
from .models import UserToken
# Register your models here.
admin.site.register(UserToken)

6
user_token/apps.py Normal file
View file

@ -0,0 +1,6 @@
from django.apps import AppConfig
class UserTokenConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "user_token"

View file

@ -0,0 +1,39 @@
# Generated by Django 5.0.6 on 2024-07-03 01:46
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("user", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="UserToken",
fields=[
(
"token",
models.CharField(
auto_created=True,
max_length=16,
primary_key=True,
serialize=False,
unique=True,
),
),
(
"user",
models.ForeignKey(
auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="tokens",
to="user.user",
),
),
],
),
]

View file

@ -0,0 +1,36 @@
# Generated by Django 5.0.6 on 2024-07-03 02:25
import django.db.models.deletion
import uuid
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("user", "0001_initial"),
("user_token", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="usertoken",
name="token",
field=models.CharField(
auto_created=True,
default=uuid.UUID("f609e128-79ad-4fbd-b384-9bb5e9c0b631"),
max_length=36,
primary_key=True,
serialize=False,
unique=True,
),
),
migrations.AlterField(
model_name="usertoken",
name="user",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="tokens",
to="user.user",
),
),
]

View file

17
user_token/models.py Normal file
View file

@ -0,0 +1,17 @@
from django.db import models
from user.models import User
import uuid
class UserToken(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tokens")
token = models.CharField(
max_length=36,
unique=True,
auto_created=True,
primary_key=True,
default=uuid.uuid4(),
)
def __str__(self):
return str(self.token)

View file

@ -0,0 +1,9 @@
from rest_framework import serializers
from .models import UserToken
class UserTokenSerializer(serializers.ModelSerializer):
class Meta:
model = UserToken
fields = "__all__"
read_only_fields = ["user", "token"]

3
user_token/tests.py Normal file
View file

@ -0,0 +1,3 @@
# from django.test import TestCase
# Create your tests here.

10
user_token/urls.py Normal file
View file

@ -0,0 +1,10 @@
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from user_token import views as user_token_views
router = DefaultRouter()
router.register(r"", user_token_views.UserViewSet)
urlpatterns = [
path("", include(router.urls)),
]

11
user_token/views.py Normal file
View file

@ -0,0 +1,11 @@
from rest_framework.viewsets import ReadOnlyModelViewSet
# from rest_framework.permissions import IsAuthenticatedOrReadOnly
from .models import UserToken
from .serializers import UserTokenSerializer
class UserViewSet(ReadOnlyModelViewSet):
queryset = UserToken.objects.all()
serializer_class = UserTokenSerializer
# permission_classes = [IsAuthenticatedOrReadOnly]