Django认证系统处理用户、分组和权限的问题。参考文档:
https://docs.djangoproject.com/es/1.9/topics/auth/
https://docs.djangoproject.com/es/1.9/topics/auth/default/#using-the-django-authentication-system
我看的不是很全面,如果理解的有问题希望大家能够指出。
1 安装
认证系统包含在django.contrib.auth模块里。使用的时候可以在django项目的settings.py文件里进行设置:
在INSTALLED_APPS:
1 'django.contrib.auth' contains the core of the authentication framework, and its default models.
2 'django.contrib.contenttypes' is the Django content type system, which allows permissions to be associated with models you create.
在 MIDDLEWARE_CLASSES里添加:
1 SessionMiddleware manages sessions across requests.
2 AuthenticationMiddleware associates users with requests using sessions.
3 SessionAuthenticationMiddleware logs users out of their other sessions after a password change.
默认情况下该模块已经在使用django-admin.py startproject进行设置了。
2 User对象
user分为superusers,staff和普通用户三种类型。
- superusers是指具有一些特定权限的用户,可以由staff来进行指定。
- staff是指员工账户,staff账户可以登录admin站点,对站点进行管理
- 普通员工是指通过普通注册流程注册的员工,只能使用站点,没有其他管理权限
- 创建用户
from django.contrib.auth.models import User
user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
user.last_name = 'Lennon'
user.save()
- 创建superuser
python manage.py createsuperuser --username=joe --email=joe@example.com
- 修改密码
form django.contrib.auth.models import User
u=User.objects.get(username='example')
u.set_password('new')
u.save()
- 用户认证
form django.contrib.auth.models import User
u=User.objects.authenticate(username='example',password='pass')
if u is not None:
if u.is_active
print("User is valid, active and authenticated")
else:
print("The password is valid, but the account has been disabled!")
else:
print("The username and password were incorrect.")
3 权限和认证
Django系统不同角色的用户具有不同的权限,staff可以在在admin站点进行管理。User对象中有两个多对多的属性:group和user_permissions
myuser.groups = [group_list]
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()
myuser.user_permissions = [permission_list]
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()
- 默认的权限
- Group
- 用程序创建权限
from myapp.models import BlogPost
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(codename='can_publish', name='Can Publish Posts',content_type=content_type)
- 权限缓存
4 Web请求认证
Django使用会话和中间件来拦截request 对象到认证系统中。 它们在每个请求上提供一个request.user属性,表示当前的用户。如果当前的用户没有登入,该属性将设置成AnonymousUser的一个实例,否则它将是User的实例。
- 登录用户
from django.contrib.auth import authenticate,login
def my_view(request):
username=request.POST['username']
password=request.POST['password']
u=authenticate(username,password)
if u is not None:
if u.is_active:
login(request,u)
else:
print("user is not active")
else:
print("Illegal user!")
- 登出用户
from django.contrib.auth import logout
def log_out(request)
logout(request)
- 只允许登录的访问
- 使用authenticate()验证
- 使用@login_required装饰器。login_required做了如下事情:
- 使用authenticate()验证
- 如果用户没有登入,则重定向到settings.LOGIN_URL,并传递当前查询字符串中的绝对路径。例如:/accounts/login/?next=/polls/3/。
- 如果用户已经登入,则正常执行视图。视图的代码可以安全地假设用户已经登入。
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
- 给已登录的用户增加访问限制
- 直接运行request.user测试
- user_passes_test装饰器:user_passes_test(func[, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME])要求一个以User对象为参数的回调函数,若用户允许访问此视图返回True否则返回False执行一个重定向操作。
- UserPassesTestMixin(Django1.9)
- 直接运行request.user测试
from django.contrib.auth.mixins import UserPassesTestMixin
class MyView(UserPassesTestMixin, View):
def test_func(self):
return self.request.user.email.endswith('@example.com')
- permission_required装饰器