2012-12-19 27 views
7

मैं एक प्रमाणीकरण बैकएंड बनाना चाहता हूं जो उपयोगकर्ताओं को केवल अपने ईमेल (कोई उपयोगकर्ता नाम, पासवर्ड नहीं) का उपयोग करके लॉग_इन करने की अनुमति देता है।कस्टम प्रमाणीकरण बैकएंड। Django

यहां मैंने कोशिश की है।

backends.py:

from django.conf import settings 
from django.contrib.auth.models import User 

class EmailAuthBackend(object):  
    def authenticate(self, username=None, password=None): 
     try: 
      user = User.objects.get(email=username) 
      if user: 
       return user 
     except User.DoesNotExist: 
      return None 

settings.py:

AUTHENTICATION_BACKENDS = (
     'path_to.backends.EmailAuthBackend', 
     'django.contrib.auth.backends.ModelBackend', 
    ) 

एचटीएमएल:

<form method="post" action="{% url myproject.views.test %}"> 
    {% csrf_token %} 

     <input type="text" name="email" value=""/> 

    <button type="submit">Valider</button> 

    </form> 

दृश्य:

def test(request): 
    email = '' 
    if 'email' in request.POST: 
     email = request.POST.get('email') 
     if not User.objects.filter(email=email): 
      User.objects.create(email=email) 
     user = authenticate(username=email) 
     if user is not None: 
      if user.is_active: 
       auth_login(request, user) 
    return HttpResponseRedirect(reverse('home')) 

यह काम नहीं करता है, उपयोगकर्ता प्रमाणीकृत नहीं है। और मैं भी यह त्रुटि है जब मैं/व्यवस्थापक पर जाएँ:

AttributeError at /admin/logout/ 
    'EmailAuthBackend' object has no attribute 'get_user' 

उत्तर

11

Django में प्रत्येक कस्टम बैकएंड के लिए, आप get_user समारोह निर्दिष्ट करने के लिए की जरूरत है। the documentation देखें। get_user कार्यान्वयन बस, मौजूदा उपयोगकर्ता तालिका का उपयोग कर सकते है जैसे आप कर रहे हैं:

def get_user(self, user_id): 
     try: 
      return User.objects.get(pk=user_id) 
     except User.DoesNotExist: 
      return None 

कारण यह आवश्यक है स्थितियों में, जहां आप एक अलग स्रोत से अपनी प्राथमिक कुंजी के माध्यम से उपयोगकर्ता को लाने के लिए आवश्यकता होगी के लिए है।

+0

धन्यवाद। मैं जवाब asap स्वीकार करते हैं। – Marcolac

2

जबकि स्वीकृत उत्तर सही है, मैं मॉडलबैकेंड को विरासत में हल करने के लिए समस्या को हल करने के लिए एक और तरीका प्रदान करूंगा।

from django.contrib.auth.backends import ModelBackend 

class EmailAuthBackend(ModelBackend): 
    def authenticate(self, username=None, password=None, **kwargs): 
     try: 
      user = User.objects.get(email=username) 
      if user.check_password(password): 
       return user 
     except ObjectDoesNotExist: 
      # Run the default password hasher once to reduce the timing 
      # difference between an existing and a non-existing user (#20760). 
      User().set_password(password) 

get_user पहले से ही मॉडलबैकेंड द्वारा कार्यान्वित किया गया है और आपको इसके साथ अनुमति विधियां मिलती हैं।

संबंधित मुद्दे