Django OAuth Toolkit - Register a User

I looked at the Django OAuth Toolkit provider and resource documents, but all I can find is how to 'authenticate' a user, not as a registeruser.

I can configure everything on my machine, but I don’t know how to register a user using a username and password. I know that I am missing something very subtle. How do I accurately register a user and get an access token in exchange for my resource servers.

OR

Is it that I have to first register the user using the regular Django mechanism, and then get the token of the same?

+4
source share
3 answers

, , . , django oauth-toolkit.

django-rest-framework. , oauth.

: django, , . oauth .

serializers.py

from rest_framework import serializers
import models
from django.utils.translation import gettext_lazy as _


class RegisterSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField()

    def validate(self, data):
        try:
            user = models.User.objects.filter(username=data.get('username'))
            if len(user) > 0:
                raise serializers.ValidationError(_("Username already exists"))
        except models.User.DoesNotExist:
            pass

        if not data.get('password') or not data.get('confirm_password'):
            raise serializers.ValidationError(_("Empty Password"))

        if data.get('password') != data.get('confirm_password'):
            raise serializers.ValidationError(_("Mismatch"))

        return data

    class Meta:
        model = models.User
        fields = ('username', 'first_name', 'last_name', 'password', 'confirm_password', 'is_active')
        extra_kwargs = {'confirm_password': {'read_only': True}}

view.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from oauth2_provider.settings import oauth2_settings
from braces.views import CsrfExemptMixin
from oauth2_provider.views.mixins import OAuthLibMixin

import json
import models
import serializers

from django.utils.decorators import method_decorator
from django.http import HttpResponse
from django.views.generic import View
from django.views.decorators.debug import sensitive_post_parameters
from django.utils.translation import gettext_lazy as _
from django.db import transaction


class UserRegister(CsrfExemptMixin, OAuthLibMixin, APIView):
    permission_classes = (permissions.AllowAny,)

    server_class = oauth2_settings.OAUTH2_SERVER_CLASS
    validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS
    oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS

    def post(self, request):
        if request.auth is None:
            data = request.data
            data = data.dict()
            serializer = serializers.RegisterSerializer(data=data)
            if serializer.is_valid():
                try:
                    with transaction.atomic():
                        user = serializer.save()

                        url, headers, body, token_status = self.create_token_response(request)
                        if token_status != 200:
                            raise Exception(json.loads(body).get("error_description", ""))

                        return Response(json.loads(body), status=token_status)
                except Exception as e:
                    return Response(data={"error": e.message}, status=status.HTTP_400_BAD_REQUEST)
            return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        return Response(status=status.HTTP_403_FORBIDDEN) 

urls.py

rom django.conf.urls import url
from oauth2_provider import views as oauth2_views

import views

urlpatterns = [
    url(r'^user/register/$', views.UserRegister.as_view()),
]
+10

, Django (, admin django). , , OAuth OAuth, , , .

+4

.

django-oauth-toolkit , , , Alexa Skill, "" . , .

django-allauth , . Amazon, Google Slack. , . Alexa "linking".

To integrate with the toy slice, I wrote, I added special code to create new django users based on their unique Slack user ID, completely skipping the OAuth workflow using Slack. Only after django users can exist can django-oauth-toolkit tokens be introduced for them.

+2
source

Source: https://habr.com/ru/post/1694247/


All Articles