Tastypie:用于GET的身份验证和用于POST的匿名身份验证

时间:2012-10-24 14:40:51

标签: python django api rest tastypie

我使用Django / Tastypie来管理我的用户集合。

是否可以允许匿名用户在API中进行POST(在某个端点创建新用户时)并限制经过身份验证的用户仅限他们自己的用户,但不是所有用户?

感谢您的帮助。

2 个答案:

答案 0 :(得分:19)

我发现最简单的事情是继承我正在使用的Authentication类。当方法为POST时,只需覆盖is_authenticated方法即可返回True

class AnonymousPostAuthentication(BasicAuthentication):
    """ No auth on post / for user creation """

    def is_authenticated(self, request, **kwargs):
        """ If POST, don't check auth, otherwise fall back to parent """

        if request.method == "POST":
            return True
        else:
            return super(AnonymousPostAuthentication, self).is_authenticated(request, **kwargs)

我将验证放在Validation的子类中并覆盖is_valid

我按照Sampson上面所做的那样进行GET过滤。

答案 1 :(得分:3)

是的,可以同时做到这两点。

这是一个简单的示例,说明如何让经过身份验证的用户只获取自己的用户JSON,而不是来自所有其他用户:(假设您使用的是Django的内置用户基础结构):

# In api.py (or resource.py):
...
from tastypie.resources import ModelResource
from tastypie import fields
from models import *
from django.contrib.auth.models import User, Group
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization
...

# REST endpoint for authenticating user accounts
class UserResource(ModelResource):

    class Meta:
        queryset = User.objects.all()
        resource_name = 'auth/user'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(username=request.user)

以下是一个简单的示例,说明如何让匿名用户POST创建新用户(警告:严格来说,这不使用Tastypie)

# In views.py:
...
from django.http import HttpResponse
from django.contrib.auth.models import User, Group
from django.contrib.auth import authenticate
from django.http import Http404
from django.utils import timezone
from models import *
from api import *
from django.utils import simplejson
...

# REST endpoint for user registration
# Enforces server-side mediation (input validation)
# On failure, raises Http404
# On success, redirects to registration success page
def register_user(request):
    if request.method != 'POST':
        raise Http404('Only POSTs are allowed')

    # acquire params
    username = request.POST['username']
    password = request.POST['password']
    repeatpw = request.POST['repeatpw']
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']

    # Server-side mediation to check for invalid input
    if username == '' or username is None:
        raise Http404('Server-side mediation: Invalid Username')

    if len(username) > 30:
        raise Http404('Server-side mediation: username must be 30 characters or fewer')

    if len(first_name) > 30:
        raise Http404('Server-side mediation: first name must be 30 characters or fewer')

    if len(last_name) > 30:
        raise Http404('Server-side mediation: last name msut be 30 characters or fewer')

    if len(password) < 4:
        raise Http404('Server-side mediation: Password too short')

    if password != repeatpw:
        raise Http404('Server-side mediation: Password Mismatch')

    # This try-except block checks existence of username conflict
    try:
        test_user_exists = User.objects.get(username__exact=username)
        if test_user_exists != None:
            raise Http404('Server-side mediation: Username exists')
    except User.DoesNotExist:
        pass

    # Input passes all tests, proceed with user creation
    user = User.objects.create_user(username, 'default@nomail.com', password)
    group = Group.objects.get(name='Standard')
    user.first_name = first_name
    user.last_name = last_name
    user.groups.add(group)
    user.is_staff = False    
    user.save()

    # Build confirmation JSON
    confirmation = {
            'action': 'register_user',
            'username': username,
            'success': 'yes',
    }

    json_return = simplejson.dumps(confirmation)

    # return JSON of the success confirmation
    return HttpResponse(json_return, mimetype='application/json')

基于此,这是一个脚本,说明如何使用curl通过REST端点创建新用户:

#!/bin/bash
echo "Usage: ./register_user username password repeatpw first_name last_name"
curl -v -d "username=$1&password=$2&repeatpw=$3&first_name=$4&last_name=$5" http://127.0.0.1:8000/register_user/ > result