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' ,
)
相关文章
相关标签/搜索