如何使用tastypie登录django [英] How can I login to django using tastypie

查看:23
本文介绍了如何使用tastypie登录django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的自定义身份验证中覆盖 is_authenticated.我有一些简单的(开始)这样的:

I'm trying to override is_authenticated in my custom authentication. I have something simple (to start with) like this:

class MyAuthentication(BasicAuthentication):
    def __init__(self, *args, **kwargs):
        super(MyAuthentication, self).__init__(*args, **kwargs)

    def is_authenticated(self, request, **kwargs):
        return True

然后在我的 ModelResource 中

then in my ModelResource I have

class LoginUserResource(ModelResource):

    class Meta:
        resource_name = 'login'
        queryset = User.objects.all()
        excludes = ['id', 'email', 'password', 'is_staff', 'is_superuser']
        list_allowed_methods = ['post']

        authentication = MyAuthentication()
        authorization = DjangoAuthorization()

我不断收到 500 错误,"error_message": "column username is not unique".我在数据库中只有一个用户名,它是我要验证的用户.

I keep getting a 500 error back with "error_message": "column username is not unique". I only have one username in the db and it's the user I am trying to authenticate.

关于为什么返回此错误的任何想法?我如何允许 api 客户端登录?

Any ideas as to why it's returning this error? How would I allow an api client to login?

感谢您的帮助.

推荐答案

您的方法将尝试使用您进行身份验证的用户名创建一个新用户.这将在 DB 层冒泡,正如您已经注意到的那样,这样的用户已经存在.

Your approach will try to create a new user with the username that you are authenticating with. This will bubble up at the DB layer, as you've noticed, that such a user already exists.

您想要的是创建一个 UserResource,在其上添加一个方法,用户可以使用传递用户名/密码的数据发布和登录.

What you want is to create a UserResource, add a method on it that users can post to and login with data passing in username/password.

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from tastypie.http import HttpUnauthorized, HttpForbidden
from django.conf.urls import url
from tastypie.utils import trailing_slash

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        fields = ['first_name', 'last_name', 'email']
        allowed_methods = ['get', 'post']
        resource_name = 'user'

    def override_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/login%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('login'), name="api_login"),
            url(r'^(?P<resource_name>%s)/logout%s$' %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('logout'), name='api_logout'),
        ]

    def login(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))

        username = data.get('username', '')
        password = data.get('password', '')

        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request, user)
                return self.create_response(request, {
                    'success': True
                })
            else:
                return self.create_response(request, {
                    'success': False,
                    'reason': 'disabled',
                    }, HttpForbidden )
        else:
            return self.create_response(request, {
                'success': False,
                'reason': 'incorrect',
                }, HttpUnauthorized )

    def logout(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        if request.user and request.user.is_authenticated():
            logout(request)
            return self.create_response(request, { 'success': True })
        else:
            return self.create_response(request, { 'success': False }, HttpUnauthorized)

现在您可以使用数据向 http://hostname/api/user/login 发送 POST{ 'username' : 'me', 'password' : 'l33t' }.

Now you can do send a POST to http://hostname/api/user/login with data { 'username' : 'me', 'password' : 'l33t' }.

这篇关于如何使用tastypie登录django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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