19

我将构建一个 iOS 应用程序,其功能将基于 Django REST 应用程序提供的访问权限。

Django 管理 iOS 应用程序中活动的权限。如果允许,用户 A 可以做工作 A。权限将通过 ASIHTTPRequest 查询到由 Django Tastypie 提供的 REST API。

没有注册。用户将只能通过 Twitter 登录。XAuth 将用于为用户呈现登录屏幕。

有2种用户。例如,类型 1 和类型 2。类型 1 是普通用户,只能在 iOS 应用程序中浏览数据。

类型 2 用户可以提交/编辑数据。

理论上就是这样。但是......我不知道从哪里开始!

最大的障碍:

如何通过 Tastypie 将 Twitter XAuth 与 Django 的用户后端挂钩?

如果我知道这一点,那么我可以查询必要的权限。

提前致谢!

4

2 回答 2

1

我用 django + sweetpie 和 iOS 的 Facebook 登录做了类似的事情。

验证

  1. 使用您将使用的任何方式登录用户,获取access_token

  2. 创建一个 GET 请求 sweetpie 端点,您将把 accesstoken 作为查询字符串传递给该端点。

  3. 在服务器端验证等...然后创建您自己的内部“tastypie”令牌并在对 get 请求的响应中返回它,例如:

class GetToken(ModelResource):
    """
    Authenticates the user via facebook and returns an APIToken for them.
    """

class Meta(object):
    queryset = ApiKey.objects.all()
    resource_name = 'authenticate'
    fields = ['user', 'key']
    allowed_methods = ['get']
    authorization = Authorization()
    authentication = FacebookAuthentication()

def prepend_urls(self):
    """We override this to change default behavior
    for the API when using GET to actually "create" a resource,
    in this case a new session/token."""

    return [
        url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()),
            self.wrap_view('_create_token'), name="api_get_token"),
        ]

def _create_token(self, request, **kwargs):
    """Validate using FacebookAuthentication, and create Api Token if authenticated"""
    self.method_check(request, allowed=['get'])
    # This checks that the user is authenticated on facebook and also creates the user
    # if they have not been created.
    self.is_authenticated(request)
    self.throttle_check(request)

    bundle = self.build_bundle(obj=None, request=request)
    bundle = self.obj_create(bundle, request, **kwargs)
    bundle = self.full_dehydrate(bundle)

    self.log_throttled_access(request)
    return self.create_response(request, bundle.data)


def obj_create(self, bundle, request=None, **kwargs):
    """Create a new token for the session"""
    bundle.obj, created = ApiKey.objects.get_or_create(user=request.user)
    return bundle

  1. 在所有后续调用中传递返回的 API 密钥,可以再次作为查询字符串参数,也可以在每次调用的 Authorization 标头上设置它。

  2. 确保您想要对其进行身份验证的所有ApiKeyAuthentication()其他资源都已在 Meta.xml 中设置。

class ThingResource(ModelResource):
    class Meta:
        queryset = Thing.objects.all()
        resource_name = 'thing'
        authentication = ApiKeyAuthentication()

授权

所以现在你在服务器端知道用户就是他们所说的那个用户,这个用户可以做什么?这就是授权元的全部内容。

您可能需要Django 授权,在这种情况下,您可以只为用户使用正常的权限方案,或者您可以自己滚动。这很简单。

于 2012-11-10T00:31:08.763 回答
0

amrox 有一个很好的例子,说明如何将支持 xAuth 的django-oauth-plus的自定义分支挂钩到 sweetpie。我想可以对其进行调整以适应您的目的。

于 2012-06-22T19:58:19.543 回答