Django自定义User模型和登录验证

来源:互联网 发布:sql between 编辑:程序博客网 时间:2024/05/21 10:49

http://www.redicecn.com/html/blog/Django/2012/0325/385.html

用户表已存在(与其他App共用),不能再使用Django内置的User模型和默认的登录认证。但是还想使用Django的认证框架(真的很方便啊)。

两个步骤:

1)自定义Use模型,为了区分系统的User模型,命名为Account。

view plaincopy to clipboardprint?
  1. class Account(models.Model):  
  2.     business_email = models.EmailField()  
  3.     business_password = models.CharField(max_length=20)  
  4.     contact_first_name = models.CharField(max_length=30)  
  5.     contact_last_name = models.CharField(max_length=30)  
  6.     is_active = models.BooleanField()  
  7.   
  8.     def is_authenticated(self):  
  9.         return True  
  10.   
  11.     def hashed_password(self, password=None):  
  12.         if not password:  
  13.             return self.business_password  
  14.         else:  
  15.             return hashlib.md5(password).hexdigest()  
  16.           
  17.     def check_password(self, password):  
  18.         if self.hashed_password(password) == self.business_password:  
  19.             return True  
  20.         return False  
  21.       
  22.     class Meta:  
  23.         db_table = "bussinesses"  

2)自定义登录验证后台,并加入AUTHENTICATION_BACKENDS。

view plaincopy to clipboardprint?
  1. # auth.py  
  2.   
  3. from coocaca.myauth.models import Account  
  4.    
  5. class MyCustomBackend:  
  6.   
  7.     def authenticate(self, business_email=None, business_password=None):  
  8.         try:  
  9.             user = Account.objects.get(business_email=business_email)  
  10.         except Account.DoesNotExist:  
  11.             pass  
  12.         else:  
  13.             if user.check_password(business_password):  
  14.                 return user  
  15.         return None  
  16.    
  17.     def get_user(self, user_id):  
  18.         try:  
  19.             return Account.objects.get(pk=user_id)  
  20.         except Account.DoesNotExist:  
  21.             return None  

在settings.py中加入该验证后台:

view plaincopy to clipboardprint?
  1. AUTHENTICATION_BACKENDS = (  
  2.   
  3.     'coocaca.myauth.auth.MyCustomBackend',   
  4.   
  5. )  

这样Django就会使用MyCustomBackend作为登录验证后台。

验证通过后返回的是我们自定义的Account模型,并且request.user中获取的也是我们的Account模型(这正是MyCustomBackend中get_user方法的功能)。


原创粉丝点击