Django 擴展User 編寫本身的認證後臺

前言

今天用django寫web平臺,須要用到帳號管理,固然第一時間就想到Django的強大的User模型,各類權限的控制,session的管理都速度解決了。可是Django的管理系統與本身的後臺數據庫User對象是緊密相連的,而我又不但願用Django User數據庫做爲個人後臺數據庫,查了相關資料,發現能夠編寫本身的認證後臺解決。python

實現

實現方法就是,編寫本身的認證後臺,每次登錄的時候在 authenticate 方法中把本身的後臺數據中的用戶都插入一個相應的Django User對象。這樣就能夠無縫結合到Django的認證中,享受Django強大的認證後臺功能web

1.建立本身的後臺模塊

myauth/
├── admin.py
├── auth.py
├── __init__.py
└── models.py

2.models.py

# -*- coding: utf-8 -*-
from django.db import models
import hashlib
#本身的後臺數據庫表.account
class Account(models.Model):
    username = models.CharField(u"用戶名",blank=True,max_length=32)
    password = models.CharField(u"密碼",blank=True,max_length=50)
    domain = models.CharField(u"可操做域名",blank=True,max_length=256,help_text='填寫多個域名,以,號分隔')
    is_active = models.IntegerField(u"is_active",blank=True)
    phone = models.CharField(u"電話",max_length=50)
    mail = models.CharField(u"郵箱",max_length=50) 

    def __unicode__(self):
        return self.username 

    def is_authenticated(self):
        return True 

    def hashed_password(self, password=None):
        if not password:
            return self.password
        else:
            return hashlib.md5(password).hexdigest()
    def check_password(self, password):
        if self.hashed_password(password) == self.password:
        #if password == self.password:
            return True
        return False
    class Meta:
        db_table = "account"

 

3.auth.py

一個認證後臺其實就是一個實現了以下兩個方法的類: get_user(id)authenticate(**credentials),我也就是在authenticate中動手腳數據庫

# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from myauth.models import Account
class MyCustomBackend: 

    def authenticate(self, username=None, password=None):
        try:
            user = Account.objects.get(username=username)
        except Account.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                try:
                    django_user = User.objects.get(username=user.username)
                except User.DoesNotExist:
                    #當在django中找不到此用戶,便建立這個用戶
                    django_user = User(username=user.username,password=user.password)
                    django_user.is_staff = True
                    django_user.save()
                return django_user
            else:
                return None
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


4.admin.py

把本身的後臺數據庫表也加到django的管理系統裏面django

from myauth.models import Account
from django.contrib import admin 

admin.site.register(Account)

 

5.最後在settings.py中添加本身的認證後臺,完成

AUTHENTICATION_BACKENDS = (
    'myauth.auth.MyCustomBackend' ,
)
相關文章
相關標籤/搜索