自定义登录后台(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/

posted @ 2013-04-25 15:44  M'  阅读(515)  评论(0编辑  收藏  举报