Django OAuth Toolkit-注册用户 [英] Django OAuth Toolkit - Register a user

查看:106
本文介绍了Django OAuth Toolkit-注册用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遍历了Django OAuth Toolkit的提供程序和资源文档,但是我只能找到如何认证用户,而不是如何注册用户。

I've gone through the docs of Provider and Resource of Django OAuth Toolkit, but all I'm able to find is how to 'authenticate' a user, not how to register a user.

我可以在计算机上进行所有设置,但不确定如何使用用户名&注册用户密码。我知道我缺少一些非常微妙的东西。如何正确注册用户并获得访问令牌以与资源服务器进行通话。

I'm able to set up everything on my machine, but not sure how to register a user using username & password. I know I'm missing something very subtle. How do I exactly register a user and get an access token in return to talk to my resource servers.

OR

是否要先使用常规Django机制注册用户,然后获得相同的令牌?

Is it like that I've to first register the user using normal Django mechanism and then get the token of the same?

推荐答案

您可以做自己想做的事情,这就是您的幸运日。当我第一次开始使用 django oauth-toolkit 时,我遇到了这个问题。

You can do what you are asking, and its your lucky day. I faced that problem when I first started working with django and oauth-toolkit.

以下是我使用 django-rest-framework 的实现。

The following is my implementation using django-rest-framework. It will register the user, authenticate and return an oauth response.

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

The thought is this: Using django models we save the new user using the proper serializers and models. In the same response, we create a new oauth token and return it to the user.

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



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



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

这篇关于Django OAuth Toolkit-注册用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆