From 5dce2441fa6c11fc56babd638a1735f1c793e24d Mon Sep 17 00:00:00 2001 From: simon Date: Tue, 29 Mar 2022 10:17:47 +0700 Subject: [PATCH] add API login view --- tubearchivist/api/README.md | 18 ++++++++++++++++++ tubearchivist/api/urls.py | 2 ++ tubearchivist/api/views.py | 22 ++++++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/tubearchivist/api/README.md b/tubearchivist/api/README.md index bc75eda..274c862 100644 --- a/tubearchivist/api/README.md +++ b/tubearchivist/api/README.md @@ -20,6 +20,24 @@ headers = {"Authorization": "Token xxxxxxxxxx"} response = requests.get(url, headers=headers) ``` +## Login View +Return token and user ID for username and password: +POST /api/login +```json +{ + "username": "tubearchivist", + "password": "verysecret" +} +``` + +after successful login returns +```json +{ + "token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "user_id": 1 +} +``` + ## Video Item View /api/video/\/ diff --git a/tubearchivist/api/urls.py b/tubearchivist/api/urls.py index 8ba3dcf..677682d 100644 --- a/tubearchivist/api/urls.py +++ b/tubearchivist/api/urls.py @@ -5,6 +5,7 @@ from api.views import ( ChannelApiView, DownloadApiListView, DownloadApiView, + LoginApiView, PlaylistApiView, VideoApiView, VideoProgressView, @@ -12,6 +13,7 @@ from api.views import ( from django.urls import path urlpatterns = [ + path("login/", LoginApiView.as_view(), name="api-login"), path( "video//", VideoApiView.as_view(), diff --git a/tubearchivist/api/views.py b/tubearchivist/api/views.py index f22941c..a01371c 100644 --- a/tubearchivist/api/views.py +++ b/tubearchivist/api/views.py @@ -10,6 +10,8 @@ from rest_framework.authentication import ( SessionAuthentication, TokenAuthentication, ) +from rest_framework.authtoken.models import Token +from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView @@ -242,3 +244,23 @@ class DownloadApiListView(ApiBaseView): extrac_dl.delay(youtube_ids) return Response(data) + + +class LoginApiView(ObtainAuthToken): + """resolves to /api/login/ + POST: return token and username after successful login + """ + + def post(self, request, *args, **kwargs): + """post data""" + # pylint: disable=no-member + serializer = self.serializer_class( + data=request.data, context={"request": request} + ) + serializer.is_valid(raise_exception=True) + user = serializer.validated_data["user"] + token, _ = Token.objects.get_or_create(user=user) + + print(f"returning token for user with id {user.pk}") + + return Response({"token": token.key, "user_id": user.pk})