2014-12-04 97 views
0

我想將我們的應用程序(基於PHP)之一移動到Django。我無法解決如何做到以下要求。Django使用電子郵件和IP地址進行自定義用戶身份驗證

我不想使用用戶名字段。我甚至不需要數據庫上的這個字段,當然我需要一些額外的數據庫領域,如「職位」等。我在登錄過程中使用電子郵件字段作爲唯一值。

此外,應用程序必須檢出用戶的IP地址,每個用戶可能有一個或多個IP地址。我曾經在另一個名爲user_ip的表中存儲用戶IP地址。但我不知道如何在認證過程中檢查這一點。

任何想法和示例代碼?

謝謝

回答

0

你可以繼承django的真棒認證系統模型。例如用戶模型

from django.contrib.auth.models import User 

class CustomUser(models.Model): 
    user = models.OneToOneField(User) #<-- Django's User 
    # other extra fields you want 

class User_IP(models.Model): 
    user = models.ForeignKey(CustomUser) 
    u_ip = models.CharField(max_length=20) 

登錄cicle:

def my_view(request): 
    username = request.POST['username'] 
    password = request.POST['password'] 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      customuser = user.get_profile() 
      # check for IP etc.. then: 
      login(request, user) 
      # Redirect to a success page. 
     else: 
      # Return a 'disabled account' error message 
    else: 
     # Return an 'invalid login' error message. 

文檔:https://docs.djangoproject.com/en/1.6/topics/auth/customizing/

+0

謝謝您的回答。我可以使用user_ip字段作爲FK到另一個包含用戶ip地址的表。我如何在登錄過程中使用它? – 2014-12-04 15:59:19

0

我建議採取看看文檔創建自定義認證後端。 https://docs.djangoproject.com/en/dev/topics/auth/customizing/#writing-an-authentication-backend

如果我採取什麼這看起來像你的情況猜測,這將是這樣的......

models.py

class IPAddress(models.Model): 
    ip_address = models.GenericIPAddressField() 

class CustomUser(models.Model): 
    user = models.OneToOneField(User) 
    ip_address = models.ManyToManyField(IPAddress) 

authentication_backends.py

class EmailIPAuthBackend(object): 
    def authenticate(self, email=None, ip_address=None): 
     try: 
      return CustomUser.objects.get(user__email=email, ip_address=ip_address).user 
     except CustomUser.DoesNotExist: 
      return None 

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

然後,您可以將此身份驗證後端插入settings.py ...

AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend', 'path.to.your.custom.authetication_backends.EmailIPAuthBackend') 

當在現在登錄用戶時,Django會首先嚐試它的默認身份驗證功能,當失敗時它會嘗試您的自定義身份驗證功能。

如果你真的需要從你的基地刪除用戶的用戶名,那麼你就需要在這裏看一看,https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model

相關問題