zoukankan      html  css  js  c++  java
  • 自定义登录后台(authentication backend)[转]

    学习http://docs.djangoproject.com/en/dev/topics/auth/?from=olddocs#writing-an-authentication-backend记录
    
    authetication backend是一个类,实现了两个方法:get_user(user_id)与authenticate(**credentials).get_user函数有一个参数user_id,它可以是username,database ID或其他,返回一个User对象实例。authenticate方法有一个名为credentials的关键字参数。一般情况,它如下:
    class MyBackend:
      def authenticate(self,username=None,password=None):
        #检测username与password,然后返回一个User实例
    但也可以是身份验证令牌,如下:
    class MyBackend:
      def authenticate(self,token=None):
        #检测token返回一个User实例
    
    下面的例子实现功能为:username与password是在自己的settings.py文件中定义的,利用这个信息实现登录,返回一个Django User.
    from django.conf import settings
    from django.contrib.auth.models import User,check_password
    
    class SettingsBackend:
        """
        Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
    
        Use the login name, and a hash of the password. For example:
    
        ADMIN_LOGIN = 'admin'
        ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
        """
        def authenticate(self, username=None, password=None):
            login_valid = (settings.ADMIN_LOGIN == username)
            pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
            if login_valid and pwd_valid:
                try:
                    user = User.objects.get(username=username)
                except User.DoesNotExist:
                    # Create a new user. Note that we can set password
                    # to anything, because it won't be checked; the password
                    # from settings.py will.
                    user = User(username=username, password='get from settings.py')
                    user.is_staff = True
                    user.is_superuser = True
                    user.save()
                return user
            return None
    
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    
    在自定义backend中处理授权
    自定义认证后台提供了自己的权限。
    user model将通过委托实现了(get_group_permissions(),get_all_permission(),has_perm()与has_module_perms())这些函数authentication backend处理权限查询。
    代码如下:
    class SettingsBackend:
      ...
      def has_perm(self.user_obj,perm):
        if user_obj.username == settings.ADMIN_LOGIN:
          return True
        else:
          return False

    原文:http://plq168.blog.163.com/blog/static/53101462201092711170704/

  • 相关阅读:
    在eclipse中API的封装和调用
    冒泡排序
    java中阻止类的继承
    java中数组复制的两种方式
    ssh框架搭建出现的异常: class com.my.entity.user not found while looking for property: id
    ssh框架中struts.xml 的配置参数详解
    线程的五种状态
    Sql Server 分页
    window.opener 子窗体操作父窗体
    贪心算法--汽车加油问题
  • 原文地址:https://www.cnblogs.com/yiki/p/3042686.html
Copyright © 2011-2022 走看看