django user 权限

 Django中的Users权限系统 2011-05-21 15:04:33

分类: Python/Ruby

 

权限系统包含
1.用户
2.权限(判断一个用户是否有特定的操作权限yes/no)
3.组
4.消息A simple way to queue messages for given users

安装
必须要INSTALLED_APPS = (
    'django.contrib.auth',)
然后运行manage.py syncdb  将相应的表创建起来


用户Users
class models.User
具备了以下的字段属性
username 
Required. 30 characters or fewer. Alphanumeric characters only 
(letters, digits and underscores).

first_name 
Optional. 30 characters or fewer.

last_name 
Optional. 30 characters or fewer.

email 
Optional. E-mail address.

password 
Required. A hash of, and metadata about, the password

is_staff 
Boolean. Designates whether this user can access the admin site.

is_active 
Boolean. Designates whether this user account should be considered active. 
Set this flag to False instead of deleting accounts.

is_superuser 
Boolean. Designates that this user has all permissions without explicitly assigning them.

last_login 
A datetime of the user’s last login. Is set to the current date/time by default.


这个表示的是auth_user表里面的字段。系统自带的用户表!

其实打开其自带的表发现其权限是比较简单的。
用户表、用户组、用户-组关联、日志表、组-权限表、用户-权限表、权限表

发现用户表与组还有权限是多对多关联。
所以可以有这样的ORM层方法
myuser.groups = [group_list]
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()        因为是多对多的models关系
myuser.user_permissions = [permission_list]
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()

这个类的自带的model里面的方法
is_anonymous() 
is_authenticated() 
get_full_name() 
set_password(raw_password) 
check_password(raw_password) 
set_unusable_password() 
has_usable_password() 
get_group_permissions() 
get_all_permissions() 
has_perm(perm) 
has_module_perms(package_name) 
get_and_delete_messages() 
email_user(subject, message, from_email=None) 
get_profile() 

管理的方法
create_user(username, email, password=None) 
make_random_password(length=10, allowed_chars='RSTUVWXYZ23456789')

使用示例
1.创建用户
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.is_staff = True
>>> user.save()
2.修改密码
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username__exact='john')
>>> u.set_password('new password')
>>> u.save()
创建超级管理员
manage.py createsuperuser --username=joe --email=joe@example.com

现在应用它来做WEB的校验
首先必须要安装两个中间件
SessionMiddleware and AuthenticationMiddleware 
安装好了之后就可以应用request.user在views里面了如果用户未登录那
request.user就是一个匿名用户
if request.user.is_authenticated():
    # Do something for authenticated users.认证过的用户如何处理
else:
    # Do something for anonymous users.匿名用户如何处理


def index(request):
    common_dict={
    "sitename":"我的网站测试中。。。",
    "sitedomain":"127.0.0.1",
    'app_label':'',
    }
    content='fffffffff'
    username='amouysuser'
    if request.user.is_authenticated():
        username = request.session.get('username', None)
        content=' 认证的用户'
    else:
        content='  匿名用户'        
    return render_to_response('index.html',common_dict)

那用户如何进行校验是不是合法用户呢?
可以使用authenticate() 方法
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret') #校验处理
if user is not None:#表示校验成功了
    if user.is_active:
        print "You provided a correct username and password!"
    else:
        print "Your account has been disabled!"
else:
    print "Your username and password were incorrect."


调用两个示例。先校验是不是合法用户然后调用login方法存储用户的ID到session里面
from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
    else:
        # Return an 'invalid login' error message.
用户如何退出本系统?
from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    # Redirect to a success page.
Note that logout() doesn't throw any errors if the user wasn't logged in.

一般后台管理的话都需要用户事先登录过系统这样怎么保证用户的每一个方法都是在登录状态下呢
原始方法
def my_view(request):
    if not request.user.is_authenticated():
        return render_to_response('myapp/login_error.html')
做一个判断
高级的一种做法
做一个装饰器login_required()
from django.contrib.auth.decorators import login_required
def my_view(request):
    # ...
my_view = login_required(my_view)  装饰器实现

还可以这样
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):

装饰器还可以带参数
from django.contrib.auth.decorators import login_required

@login_required(redirect_field_name='redirect_to')
def my_view(request):
    # ...
表示一旦失败抛到哪个URL去
其他的内建视图
django.contrib.auth.views.logout_then_login() 
直接退出到登录页



感受:是不是可以不用自己再做一套权限了直接用它了得了
posted @ 2013-07-16 12:38  smallcoderhujin  阅读(1341)  评论(0编辑  收藏  举报