其余的Django框架:使用电子邮件,而不是用户名获得身份验证令牌 [英] Django rest framework: Obtain auth token using email instead username

查看:316
本文介绍了其余的Django框架:使用电子邮件,而不是用户名获得身份验证令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个项目,以便为移动设备Django的休息框架认证。我使用的是默认令牌认证为从一个POST请求用户令牌发送用户名和密码。

I'm working on a project to enable the django rest framework authentication for mobile devices. I'm using the default token authentication for get the user token from a post request sending username and password.

curl --data "username=username&password=password" http://127.0.0.1:8000/api/api-token-auth/

(API / API-令牌认证/与obtain_auth_token视图下的URL)

(api/api-token-auth/ is the url configured with the obtain_auth_token view)

urlpatterns = [
    url(r'^api/api-token-auth/', obtain_auth_token),
    url(r'^', include(router.urls)),
]

和响应是用户令牌

{"token":"c8a8777aca969ea3a164967ec3bb341a3495d234"}

我需要在后使用电子邮件,密码,而不是用户名,密码,或两者来获取用户令牌身份验证。我在读自定义验证的http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication...但实际上,对我来说并不很清楚。
这对我来说非常有帮助...谢谢。)

I need to obtain the user token auth using email-password on the post instead username-password, or both. I was reading the documentation of custom authentication http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication... but really, isn't very clear to me. It's very helpful to me... thanks :).

推荐答案

好吧,我发现了使用电子邮件或用户名获得身份验证令牌的方式......这是串行:

Ok,I found a way for get the auth token using email or username... This is the serializer:

class AuthCustomTokenSerializer(serializers.Serializer):
    email_or_username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, attrs):
        email_or_username = attrs.get('email_or_username')
        password = attrs.get('password')

        if email_or_username and password:
            # Check if user sent email
            if validateEmail(email_or_username):
                user_request = get_object_or_404(
                    User,
                    email=email_or_username,
                )

                email_or_username = user_request.username

            user = authenticate(username=email_or_username, password=password)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise exceptions.ValidationError(msg)
            else:
                msg = _('Unable to log in with provided credentials.')
                raise exceptions.ValidationError(msg)
        else:
            msg = _('Must include "email or username" and "password"')
            raise exceptions.ValidationError(msg)

        attrs['user'] = user
        return attrs

在EMAIL_OR_USERNAME字段,用户可发送电子邮件或用户名,以及使用该功能<一href=\"http://stackoverflow.com/questions/3217682/checking-validity-of-email-in-django-python\">validateEmail(),我们可以检查,如果用户尝试使用电子邮件或用户名进行登录。然后,我们可以使查询获得用户来说,如果是有效的,并验证它

In the email_or_username field, the user can send the email or the username, and using the function validateEmail(), we can check if the user is trying to login using email or username. Then, we can make the query for get the user instance if is valid, and authenticate it.

这是该视图。

class ObtainAuthToken(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (
        parsers.FormParser,
        parsers.MultiPartParser,
        parsers.JSONParser,
    )

    renderer_classes = (renderers.JSONRenderer,)

    def post(self, request):
        serializer = AuthCustomTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)

        content = {
            'token': unicode(token.key),
        }

        return Response(content)

和则:

curl --data "email_or_username=emailorusername&password=password" http://127.0.0.1:8000/api/my-api-token-auth/.

这是准备好了。

这篇关于其余的Django框架:使用电子邮件,而不是用户名获得身份验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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