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

查看:104
本文介绍了如何使用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:列用户名不唯一。我在数据库中只有一个用户名,它是我正在尝试验证的用户。

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?

感谢您的帮助。

推荐答案

您的方法将尝试使用您要验证的用户名创建一个新用户。你会注意到,这个用户已经存在,这样就会在数据库层出现。

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)

现在您可以发送POST到 http:// hostname / api / user / login with data
{'username':'me','密码':'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天全站免登陆