实现方法就是,编写自己的认证后台,每次登陆的时候在 authenticate 方法中把自己的后台数据中的用户都插入一个相应的Django User对象。这样就可以无缝结合到Django的认证中,享受Django强大的认证后台功能 1.创建自己的后台模块 myauth/ ├── admin.py ├── auth.py ├── __init__.py └── models.py2.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 None4.admin.py 把自己的后台数据库表也加到django的管理系统里面 from myauth.models import Account from django.contrib import admin admin.site.register(Account)5.最后在settings.py中添加自己的认证后台,完成 AUTHENTICATION_BACKENDS = ( 'myauth.auth.MyCustomBackend' , )from:lxcong 转载请保留固定链接: https://linuxeye.com/program/1836.html |