add API login view

This commit is contained in:
simon 2022-03-29 10:17:47 +07:00
parent 5d8e314983
commit 5dce2441fa
No known key found for this signature in database
GPG Key ID: 2C15AA5E89985DD4
3 changed files with 42 additions and 0 deletions

View File

@ -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/\<video_id>/

View File

@ -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/<slug:video_id>/",
VideoApiView.as_view(),

View File

@ -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})