使用美味馅饼授权限制数据

时间:2014-12-18 12:50:21

标签: python django authentication tastypie

我正在Tutorial on tasty pie implem.跟随关于美味馅饼的教程 以下是models.py

#models.py

from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.utils.text import slugify


class Entry(models.Model):
    user = models.ForeignKey(User)
    pub_date = models.DateTimeField(default=now)
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    body = models.TextField()

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        # For automatic slug generation.
        if not self.slug:
            self.slug = slugify(self.title)[:50]

        return super(Entry, self).save(*args, **kwargs)

这是app文件夹blogapp中的api.py

from django.contrib.auth.models import User
from tastypie import fields
from tastypie.authorization import Authorization
from tastypie.resources import ModelResource
from blogapp.models import Entry
from tastypie.authentication import BasicAuthentication


class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
# Add it here.
        authentication = BasicAuthentication()

class EntryResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')

    class Meta:
        queryset = Entry.objects.all()
        resource_name = 'entry'

我成功获取身份验证浏览器窗口,询问用户名和密码 当我把这个网址。

http://x.x.x.x:xxxx/blogapp/api/v1/user/?format=json

验证后,它以json格式显示所有用户的数据

  1. 如何限制json数据仅显示特定于仅经过身份验证的用户特定的信息。例如,只有“用户”是经过身份验证的“条目”

  2. 一旦验证了如何断开用户连接。重新启动服务器并清除cookie无效。一旦通过身份验证,我就无法再次进入密码窗口

1 个答案:

答案 0 :(得分:1)

对于问题1:在您的UserResource上,您需要覆盖get_object_list方法,以便它返回一个过滤的查询集,如下所示:

def get_object_list(self, request):
    return super(UserResource, self).get_object_list(request).filter(username=request.user)

对于问题2:您需要使用prepend_urls手动添加登录/注销端点并调用正确的django登录/注销功能,如下所示:

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
        authentication = SessionAuthentication()

    def get_object_list(self, request):
        return super(UserResource, self).get_object_list(request).filter(username=request.user)

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

    def login_user(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        data = self.deserialize(request, request.body)
        user = authenticate(username=data.get('username'), password=data.get('password'))
        if user:
            login(request, user)
            return self.create_response(request, {'success': True})
        return self.create_response(request, {'success': False})

    def logout_user(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        logout(request)
        return self.create_response(request, {'success': True})

所以基本上是:

  1. 添加&#34;固定&#34;你的资源的网址
  2. 将它们链接到您的功能
  3. 从Django正确登录/注销
  4. 在函数中返回回复
  5. 此资源正确返回并在cookie上设置正确的csfr和sessionid。

    顺便说一句,你应该使用curl或类似的东西来测试它并进行测试。您无法注销的原因是因为您没有从django执行正确的注销()。要正确使用tastypie,您应该只使用休息呼叫而不是浏览。