2013-09-27 22 views
5

Obecnie pracuję nad projektem, który wymaga Api, wybieram Tastypie i zaimplementowałem następujące. Chcę użyć domyślnych opcji tastypie Like ApiKeyAuthentication, DjangoAuthorization etc ... w moim koduJak zaimplementować moduł logowania w Tastypie w projekcie Django

class UserResource(ModelResource): 
    class Meta: 
     queryset = User.objects.all()`enter code here` 
     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) 

Odpowiedz

4

kod skorzystać z poniższego

from django.contrib.auth.models import User 
from tastypie.authentication import ApiKeyAuthentication 
from tastypie.authorization import DjangoAuthorization 
from tastypie.resources import ModelResource 


class UserResource(ModelResource): 
    class Meta: 
     queryset = User.objects.all() 
     resource_name = 'auth/user' 
     excludes = ['email', 'password', 'is_superuser'] 
     # Add it here. 
     authentication = ApiKeyAuthentication() 
     authorization = DjangoAuthorization() 
+0

dzięki, to mój problem rozwiązany –