django 自定义auth的中间件的验证

          今天在做django的用户验证这块的功能,想用django自带的auth的验证等现有的方法。从网上查到,auth的使用,详见:http://my.oschina.net/u/569730/blog/369144 

from django.contrib.auth import authenticate, login 
def login_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        # 转到成功页面
    else:        # 返回错误信息
        但是,我用户的验证,是调用别的系统的接口,我这边的用户表只有用户名,并没有密码。这样,django自身的验证变没法使用。后来,从网上查到可以自定义django的authenticate验证。原文:http://www.redicecn.com/html/blog/Django/2012/0325/385.html

        于是自己写了auth的验证,具体步骤如下:

        1、自定义用户表

       创建模型 Account继承AbstractBaseUser(from django.contrib.auth.models import AbstractBaseUser)


注:1、创写了objectsManager,在使用createsuperuser时会用到,否则汇报错。

        2、集成PermissionsMixin,使用django自身的权限系统。

class AccountManager(BaseUserManager):
    def create_user(self, user_name, is_active, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not user_name:
            raise ValueError('Users must have an user_name')

        user = self.model(
            user_name = user_name,
            is_active = is_active
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, user_name, is_active,  password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(user_name, is_active,
            password=password
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

#AbstractBaseUser, PermissionsMixin
class Account(PermissionsMixin):
#class Account(models.Model):
    """用户表"""
    user_name = models.CharField(u'用户名',max_length=50,unique=True)
    #user_pwd = models.CharField(u'密码',max_length=50,blank=True,null=True)
    user_reg_time = models.DateTimeField(u'注册时间',blank=True,null=True,auto_now_add=True)
    user_tel = models.CharField(u'电话',blank=True,null=True,max_length=20)
    user_email = models.EmailField(u'邮箱',blank=True,null=True)
    #user_active = models.BooleanField(u'是否激活',default=False)
    rout = models.ManyToManyField(u'Rout',blank=True)
    last_login = models.DateTimeField(u'上次登录时间', blank=True,null=True,default=timezone.now())
    is_active = models.BooleanField(u'是否激活',default=True)
    is_admin = models.BooleanField(u'是否可以登录后台',default=False)

    def __unicode__(self):
        return "username:%s"%(self.user_name)

    class Meta:
        verbose_name="用户"
        verbose_name_plural = "用户"

    objects = AccountManager()

    REQUIRED_FIELDS = ('is_active',)
    USERNAME_FIELD = 'user_name'

    def get_full_name(self):
        # The user is identified by their email address
        return self.user_name

    def get_short_name(self):
        # The user is identified by their email address
        return self.user_name

    #权限检查函数 无需重写使用django自带权限模型
    #def has_perm(self, perm, obj=None):
    #    "Does the user have a specific permission?"
    #    # Simplest possible answer: Yes, always
    #    return True
    #def has_module_perms(self, app_label):
    #    "Does the user have permissions to view the app `app_label`?"
    #    # Simplest possible answer: Yes, always
    #    return True
    #def has_perms(self,perms):
    #    return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

    def get_username(self):
        "Return the identifying username for this User"
        return getattr(self, self.USERNAME_FIELD)

    def set_password(self, raw_password):
        self.password = make_password(raw_password)

    def __str__(self):
        return self.get_username()

    def natural_key(self):
        return (self.get_username(),)

    def is_anonymous(self):
        """
        Always returns False. This is a way of comparing User objects to
        anonymous users.
        """
        return False

    def is_authenticated(self):
        """
        Always return True. This is a way to tell if the user has been
        authenticated in templates.
        """
        return True


        2、编写验证auth的类

class OaAccountBackend(object):

    def authenticate(self, username=None, password=None):
        try:
            #用户验证
            client = suds.client.Client(URL)
            #print client
            result = json.loads( client.service.Login(username,password) )
            if result.get('logintype','0')=='1':
                return Account.objects.get(username=username)
            else:
                return None
        except Account.DoesNotExist:
            return None
        return None

其中suds 是调用webservice的第三方模块。         

3、在settings.py 中添加如下代码:

#自定义用户验证
AUTHENTICATION_BACKENDS = (
    'core.backends.autoAccount.OaAccountBackend',
)

完整的实例,见官方文档:https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#a-full-example        

 这样编写完成后,在使用auth验证时,和普通使用一样。django会自动调用我们重写的用户表急方法来进行验证。



你可能感兴趣的:(python,django)