python - Django OAuth 工具包 - 注册用户

标签 python django django-rest-framework django-registration django-oauth

我已经浏览了 Django OAuth Toolkit 的 Provider 和 Resource 的文档,但我所能找到的只是如何“验证”用户,而不是如何注册 一个用户。

我可以在我的机器上设置所有内容,但不确定如何使用用户名和密码注册用户。我知道我错过了一些非常微妙的东西。我如何准确地注册用户并获取访问 token 作为与我的资源服务器对话的返回。

我是否必须首先使用普通的 Django 机制注册用户,然后获取相同的 token ?

最佳答案

你可以做你想做的,这是你的幸运日。当我第一次开始使用 djangooauth-toolkit 时,我遇到了这个问题。

以下是我使用django-rest-framework实现的。它将注册用户、验证并返回 oauth 响应。

思路是这样的: 使用 django 模型,我们使用适当的序列化器和模型保存新用户。 在同一个响应中,我们创建一个新的 oauth token 并将其返回给用户。

序列化程序.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) 

网址.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()),
]

关于python - Django OAuth 工具包 - 注册用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49031954/

相关文章:

python - 使用delete_values参数的API调用字段删除不起作用

管理中需要具有默认空字符串的 django charfield

python - 模型 View 设计中的属性

django - 在 Django Rest Framework 中测试 PUT 请求

python - PowerManagement.Inhibit 适用于 dbus-python 但不适用于 dbus-send

python - 为什么 Python 不能解析这个 JSON 数据?

python - Django rest 框架在部署后为 post 方法返回 405

django - 如何使用命名空间调用 Django Rest Framework URL?

python - pytorch/numpy 中具有任意和可变维数的部分切片

django - NoReverseMatch Django,CreateView 中的 get_success_url