2012-12-19 24 views
7

私はユーザが自分の電子メール(ユーザ名なし、パスワードなし)だけを使ってlog_inできる認証バックエンドを作成したいと思います。カスタム認証バックエンド。 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', 
    ) 

HTML:

<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

を、あなたはget_user関数を指定する必要があります。 the documentationを参照してください。これが必要になる

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

理由はあなたが別のソースからの主キーを介してユーザを取得する必要があるだろう状況にある:あなたがしているようget_user実装は単に、既存のユーザのテーブルを使用することができます。

+0

ありがとうございます。私はすぐに答えを受け入れる。 – Marcolac

2

受け入れられた回答は正しいですが、ModelBackendを継承することで問題を解決する別の方法の例を提供します。

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はすでにModelBackendによって実装されており、それに沿って許可メソッドを取得しています。