From 1abb20d4871dcf8ab07f3f327fd3cbe65a22a9b1 Mon Sep 17 00:00:00 2001 From: jdlugosz963 Date: Sun, 7 Nov 2021 18:45:40 +0100 Subject: auth features --- .gitignore | 3 + auth_api/__init__.py | 0 auth_api/admin.py | 4 ++ auth_api/apps.py | 6 ++ auth_api/migrations/__init__.py | 0 auth_api/models.py | 3 + auth_api/serializers.py | 21 ++++++ auth_api/tests.py | 3 + auth_api/urls.py | 12 ++++ auth_api/views.py | 61 ++++++++++++++++++ chat_api/__init__.py | 0 chat_api/admin.py | 3 + chat_api/apps.py | 6 ++ chat_api/migrations/__init__.py | 0 chat_api/models.py | 3 + chat_api/tests.py | 3 + chat_api/urls.py | 5 ++ chat_api/views.py | 3 + lom_api/__init__.py | 0 lom_api/asgi.py | 16 +++++ lom_api/settings.py | 137 ++++++++++++++++++++++++++++++++++++++++ lom_api/urls.py | 22 +++++++ lom_api/wsgi.py | 16 +++++ manage.py | 22 +++++++ python.req | 46 ++++++++++++++ 25 files changed, 395 insertions(+) create mode 100644 .gitignore create mode 100644 auth_api/__init__.py create mode 100644 auth_api/admin.py create mode 100644 auth_api/apps.py create mode 100644 auth_api/migrations/__init__.py create mode 100644 auth_api/models.py create mode 100644 auth_api/serializers.py create mode 100644 auth_api/tests.py create mode 100644 auth_api/urls.py create mode 100644 auth_api/views.py create mode 100644 chat_api/__init__.py create mode 100644 chat_api/admin.py create mode 100644 chat_api/apps.py create mode 100644 chat_api/migrations/__init__.py create mode 100644 chat_api/models.py create mode 100644 chat_api/tests.py create mode 100644 chat_api/urls.py create mode 100644 chat_api/views.py create mode 100644 lom_api/__init__.py create mode 100644 lom_api/asgi.py create mode 100644 lom_api/settings.py create mode 100644 lom_api/urls.py create mode 100644 lom_api/wsgi.py create mode 100755 manage.py create mode 100644 python.req diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7de1644 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +db.sqlite3 +venv/ +__pycache__/ \ No newline at end of file diff --git a/auth_api/__init__.py b/auth_api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/auth_api/admin.py b/auth_api/admin.py new file mode 100644 index 0000000..979b710 --- /dev/null +++ b/auth_api/admin.py @@ -0,0 +1,4 @@ +from django.contrib import admin +from knox.models import AuthToken + +admin.register(AuthToken) diff --git a/auth_api/apps.py b/auth_api/apps.py new file mode 100644 index 0000000..875065a --- /dev/null +++ b/auth_api/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class AuthApiConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'auth_api' diff --git a/auth_api/migrations/__init__.py b/auth_api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/auth_api/models.py b/auth_api/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/auth_api/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/auth_api/serializers.py b/auth_api/serializers.py new file mode 100644 index 0000000..d39c5f3 --- /dev/null +++ b/auth_api/serializers.py @@ -0,0 +1,21 @@ +from rest_framework import serializers +from django.contrib.auth.models import User + +class UserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ('id', 'username', 'is_staff') + +class RegisterUserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ('username', 'password') + + + def register_user(self): + user = User.objects.create_user( + username = self.validated_data['username'], + password = self.validated_data['password'] + ) + + return user \ No newline at end of file diff --git a/auth_api/tests.py b/auth_api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/auth_api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/auth_api/urls.py b/auth_api/urls.py new file mode 100644 index 0000000..e8a1d86 --- /dev/null +++ b/auth_api/urls.py @@ -0,0 +1,12 @@ +from django.urls import path +from knox import views as knox_views +from .views import LoginView, RegisterView, UserInfo + + +urlpatterns = [ + path('login/', LoginView.as_view(), name='login'), + path('register/', RegisterView.as_view(), name='register'), + path('info/', UserInfo.as_view(), name='info'), + path('logout/', knox_views.LogoutView.as_view(), name='logout'), + path('logoutall/', knox_views.LogoutAllView.as_view(), name='logoutall'), +] diff --git a/auth_api/views.py b/auth_api/views.py new file mode 100644 index 0000000..caf4782 --- /dev/null +++ b/auth_api/views.py @@ -0,0 +1,61 @@ +from django.contrib.auth import login +from django.contrib.auth.models import User +from django.http.response import Http404 +from django.shortcuts import get_object_or_404 + +from rest_framework import permissions, serializers +from rest_framework.authtoken.serializers import AuthTokenSerializer +from rest_framework.response import Response +from rest_framework.views import APIView + +from knox.views import LoginView as KnoxLoginView +from knox.auth import TokenAuthentication + +from .serializers import UserSerializer, RegisterUserSerializer + +class LoginView(KnoxLoginView): + permission_classes = (permissions.AllowAny, ) + + def post(self, request, format=None): + serializer = AuthTokenSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + user = serializer.validated_data['user'] + login(request, user) + return super(LoginView, self).post(request, format=None) + +class RegisterView(APIView): + + def post(self, request): + serializer = RegisterUserSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + user = serializer.register_user() + + return Response(status=200) + +class UserInfo(APIView): + authentication_classes = (TokenAuthentication, ) + permission_classes = (permissions.IsAuthenticated, ) + + def get(self, request): + user = request.GET.get("pk", request.user) + username = request.GET.get("username", None) + + if username: + users = User.objects.filter(username__startswith = username)[:5] + serializer = UserSerializer(users, many=True) + + return Response({ + "users": serializer.data + }) + + if not isinstance(user, User): + try: + user = get_object_or_404(User, pk=user) + except ValueError: + raise Http404 + + serializer = UserSerializer(user) + + return Response({ + "user": serializer.data + }) \ No newline at end of file diff --git a/chat_api/__init__.py b/chat_api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chat_api/admin.py b/chat_api/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/chat_api/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/chat_api/apps.py b/chat_api/apps.py new file mode 100644 index 0000000..89f7109 --- /dev/null +++ b/chat_api/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ChatApiConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'chat_api' diff --git a/chat_api/migrations/__init__.py b/chat_api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chat_api/models.py b/chat_api/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/chat_api/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/chat_api/tests.py b/chat_api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/chat_api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/chat_api/urls.py b/chat_api/urls.py new file mode 100644 index 0000000..d2d839f --- /dev/null +++ b/chat_api/urls.py @@ -0,0 +1,5 @@ +from django.urls import path + +urlpatterns = [ + +] diff --git a/chat_api/views.py b/chat_api/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/chat_api/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/lom_api/__init__.py b/lom_api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lom_api/asgi.py b/lom_api/asgi.py new file mode 100644 index 0000000..9f97758 --- /dev/null +++ b/lom_api/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for lom_api project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lom_api.settings') + +application = get_asgi_application() diff --git a/lom_api/settings.py b/lom_api/settings.py new file mode 100644 index 0000000..7c85027 --- /dev/null +++ b/lom_api/settings.py @@ -0,0 +1,137 @@ +""" +Django settings for lom_api project. + +Generated by 'django-admin startproject' using Django 3.2.9. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.2/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-w699xg1453&j057k$g465vldjn+4*skp8!13ua=aq0s_91b@c)' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +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', + 'knox', + 'auth_api', + 'chat_api' +] + +REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), +} + +REST_KNOX = { + 'TOKEN_LIMIT_PER_USER': 1, +} + +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', +] + +ROOT_URLCONF = 'lom_api.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', + ], + }, + }, +] + +WSGI_APPLICATION = 'lom_api.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + # { + # 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + # }, + # { + # 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + # }, + # { + # 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + # }, + # { + # 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + # }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.2/howto/static-files/ + +STATIC_URL = '/static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/lom_api/urls.py b/lom_api/urls.py new file mode 100644 index 0000000..0bc8e32 --- /dev/null +++ b/lom_api/urls.py @@ -0,0 +1,22 @@ +"""lom_api URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +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 + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/auth/', include('auth_api.urls')) +] diff --git a/lom_api/wsgi.py b/lom_api/wsgi.py new file mode 100644 index 0000000..3b98667 --- /dev/null +++ b/lom_api/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for lom_api project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lom_api.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..6af86cb --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/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', 'lom_api.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/python.req b/python.req new file mode 100644 index 0000000..abe973a --- /dev/null +++ b/python.req @@ -0,0 +1,46 @@ +asgiref==3.4.1 +backcall==0.2.0 +backports.entry-points-selectable==1.1.0 +cffi==1.15.0 +cryptography==35.0.0 +debugpy==1.5.1 +decorator==5.1.0 +distlib==0.3.3 +Django==3.2.9 +django-rest-knox==4.1.0 +djangorestframework==3.12.4 +entrypoints==0.3 +filelock==3.3.2 +htmlentities==0.3.0 +ipykernel==6.5.0 +ipython==7.29.0 +jedi==0.18.0 +jupyter-client==7.0.6 +jupyter-core==4.9.1 +matplotlib-inline==0.1.3 +nest-asyncio==1.5.1 +parso==0.8.2 +pexpect==4.8.0 +pickleshare==0.7.5 +platformdirs==2.4.0 +prompt-toolkit==3.0.22 +ptyprocess==0.7.0 +pycairo==1.20.1 +pycparser==2.21 +Pygments==2.10.0 +PyGObject==3.40.1 +pyinotify==0.9.6 +python-dateutil==2.8.2 +python-Levenshtein==0.12.0 +pytz==2021.3 +pyxdg==0.27 +pyzmq==22.3.0 +ranger-fm==1.9.3 +six==1.16.0 +sqlparse==0.4.2 +tornado==6.1 +traitlets==5.1.1 +ulauncher==5.13.0 +virtualenv==20.10.0 +wcwidth==0.2.5 +websocket-client==1.2.1 -- cgit v1.2.3