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

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

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

两个步骤:

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

  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。

  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中加入该验证后台:

  1. AUTHENTICATION_BACKENDS = (  
  2.   
  3.     'coocaca.myauth.auth.MyCustomBackend',   
  4.   
  5. )  

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

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


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值