【Django】Django Auth认证组件详述

1、Django Auth介绍

官方文档:https://docs.djangoproject.com/en/1.10/topics/auth。 Django内置了用户认证系统,处理用户账户、用户组、权限,基于cookie的session,并且内置了一些快捷函数。Auth App有自己的数据库系统,有自己的ORM。

Requirements
  • INSTALLED_APPS
    • “django.contrib.auth”
    • “django.contrib.contenttypes”
  • MIDDLEWARE need
    • “SessionMiddleware”
    • “AuthenticationMiddleware”

2、Django Auth中的数据库表和对象

User Objects
  • fields 字段
    • username
    • password
    • email
    • first_name
    • last_name
    • groups
    • user_permission
    • is_staff
    • is_active
    • is_superuser
    • last_login
    • date_joined
  • attr 属性
    • is_authenticated
    • is_anonymous
    • username_validator
  • method 方法
    • get_username
    • get_full_name
    • get_short_name
    • set_password
    • check_password
    • set_unusable_password
    • has_usable_password
    • get_group_permissions
    • get_all_permissions
    • has_perm
    • has_module_perms
    • email_user
AnonymousUser

django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface, with these differences:

  • id is always None.
  • username is always the empty string.
  • get_username() always returns the empty string.
  • is_anonymous is True instead of False.
  • is_authenticated is False instead of True.
  • is_staff and is_superuser are always False.
  • is_active is always False.
  • groups and user_permissions are always empty.
  • set_password(), check_password(), save() and delete() raise NotImplementedError.

3、权限管理

Permission model

Permission objects have the following fields:

  • class models.Permission.name Required. 255 characters or fewer. Example: ‘Can vote’.
  • content_type Required. A reference to the django_content_type database table, which contains a record for each installed model.
  • codename Required. 100 characters or fewer. Example: ‘can_vote’.
Group model

fields

  • name
  • permissions Many-to-many field to Permission:
group.permissions.set([permission_list])  group.permissions.add(permission, permission, ...)  group.permissions.remove(permission, permission, ...)  group.permissions.clear()
创建用户
>>> from django.contrib.auth.models import User  >>> user = User.objects.create_user('john', '[email protected]', '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.last_name = 'Lennon'  >>> user.save()    $ python manage.py createsuperuser --username=joe [email protected]
更改密码
>>> from django.contrib.auth.models import User  >>> u = User.objects.get(username='john')  >>> u.set_password('new password')  >>> u.save()    $ python manage.py changepassword joe
认证、登录和登出
from django.contrib.auth import authenticate, login, logout    def my_view(request):  	username = request.POST['username']  	password = request.POST['password']  	user = authenticate(username=username, password=password)  	if user is not None:  		login(request, user)  		# Redirect to a success page.  		...  	else:  		# Return an 'invalid login' error message.    def logout_view(request):  	logout(request)  	# Redirect to a success page.

4、Authentication Web

普通方式
from django.conf import settings  from django.shortcuts import redirect    def my_view(request):  	if not request.user.is_authenticated:  		return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))  	else:  		do_something()
使用装饰器
from django.contrib.auth.decorators import login_required    @login_required  def my_view(request):  	...
  • 如果用户没有登录,会重定向到settings.LOGIN_URL,如/accounts/login/?next=/polls/3/
  • next后面跟的是登录成功后跳转的URL
  • next的名字可以自定义
  • 重定向的登录URL可以自定义
@login_required(redirect_field_name='go', login_url="/user/login/")  def my_view(request):  	...

5、授权

Permission model

Fields:

  • name(‘Can vote’)
  • content_type (A reference to the django_content_type database table)
  • codename(‘can_vote’)
The ContentType model

Fields:

  • app_label
  • model

参考数据库默认添加的Permission和Content type,了解每张表的作用。

用户权限
>>> from django.contrib.auth.models import User, Permission, ContentType  >>> user = User.objects.create_user(username='ibuler', email='[email protected]'  >>> permission = Permission.objects.get(codename='add_question')  >>> user.user_permissions.add(permission)  >>> user.has_perm('polls.add_question')  >>> content_type = ContentType.objects.get(app_label='polls', model='choice')  >>> permission = Permission.objects.create(name='Can vote', codename='can_vote', content_type=content_type)  >>> user.user_permissions.add(permission)  >>> user.have_perm('polls.can_vote')
  • has_perm(‘app_label.codename’)
用户组权限
>>> sa = Group.objects.create(name='sa')  >>> sa.user_set.add(user)  >>> sa.save()  >>> permission = Permission.objects.get(codename='add_user')  >>> sa.permissions.add(permission)  >>> user.has_perm('auth.add_user')
  • 用户会继承用户组的权限
view使用
from django.contrib.auth.decorators import permission_required    @permission_required('polls.can_vote', login_url='/loginpage/')  def my_view(request):  	...

6、Cookie and Session

http协议没有状态,cookie让http请求的时候携带状态,cookie保存在浏览器缓存中,和域名有关。 Request Headers:

...  Connection:keep-alive  Cookie:csrftoken=7YeO6nvnQMWEtreWglxBhJfQ4NT2SO5yBmsp73ZcuL5TBCBIeXDcznADfGXuhqHV; sessionid=j7sg4b9iis8pjh075s303uelm01jydn8  ...

cookie based sessions:session是基于cookie来做的,只不过保存了一个session id,所有其他内容都在服务器端存储,用来鉴别用户是否登录,以及其他信息,session要比完全cookie安全。 cookie和session相关函数、属性和model:

  • request.set_cookie:设置当前请求的cookie
  • request.cookie
  • request.session:设置当前请求的session
  • django.contrib.sessions.models.Session

7、Django Admin

Django强大的功能之一就是提供了Admin后台管理界面,简单配置就可以对数据库内容做管理。

Requirement
  • 添加’django.contrib.admin’到INSTALLED_APPS设置中。
  • admin有四个依赖:
    • django.contrib.auth
    • django.contrib.contenttypes
    • django.contrib.messages
    • django.contrib.sessions 如果这些应用没有在INSTALLED_APPS列表中,那你要把它们添加到该列表中。
  • 把django.contrib.messages.context_processors.messages添加到TEMPLATES中DjangoTemplates后台的 ‘context_processors’ 选项中,同样把django.contrib.auth.middleware.AuthenticationMiddleware和django.contrib.messages.middleware.MessageMiddleware添加到MIDDLEWARE_CLASSES.(这些默认都是激活的,所以如果你手工操作过的话就需要按照以上方法进行设置)
  • URLconf包含url(r’^admin/’, admin.site.urls)
  • 修改${app_dir}/admin.py,给每个模型创建一个ModelAdmin类,封装模型自定义的Admin功能和选项。
  • 注册ModelAdmin。做了这些步骤之后,你将能够通过你已经绑定的URL来访问Django管理站点(默认是/admin/)。
登录Admin后台管理界面
  • 创建管理员用户
  • 访问http://$host/admin/
创建ModelAdmin并注册
from django.contrib import admin  from .models import Author, Book, Publisher    # version 1  admin.site.register(Author)    # version 2  class AuthorAdmin(admin.ModelAdmin):  	pass    admin.site.register(Author, AuthorAdmin)    #version 3  @admin.register(Author)  class AuthorAdmin(admin.ModelAdmin):  	pass    @admin.register(Book)  class BookAdmin(admin.ModelAdmin):  	pass    @admin.register(Publisher)  class PublisherAdmin(models.ModelAdmin):  	pass

说明:

  • 会自动去app下寻找admin模块
  • 自动根据model的Field类型设置Form类型
配置ModelAdmin
  • label名称,定义Model Field时指定verbose_name
  • 排除某些字段exclude
  • 显示某字段fields
  • 搜索某列search_fields
  • 添加日期标签过滤date_hierarchy
  • 排序ordering
  • 列表显示更多列list_display
@admin.register(Book)  class BookAdmin(admin.ModelAdmin):  	fields = ('title', 'authors', 'publisher')  	search_fields = ('title', 'authors')  	date_hierarchy = 'publication_date'  	ordering = ('publication_date',)    @admin.register(Publisher)  class PublisherAdmin(admin.ModelAdmin):  	list_display = ('name', 'country', 'city', 'address')    def display_book_authors(obj):			# 多对多关系  	return ', '.join([author.first_name for author in obj.authors.all()])    display_book_authors.short_description = 'Authors'    class BookAdmin(admin.ModelAdmin):  	list_display = ['title', 'publisher', display_book_authors, 'publication_date']
配置Action
def make_book_pub_date_to_now(modeladmin, request, queryset):  	queryset.update(publication_date=timezone.now())    make_book_pub_date_to_now.short_description = 'Mark selected book pub_date as now'    @admin.register(Book)  class BookAdmin(admin.ModelAdmin):  	list_display = ['title', 'publisher', 'publication_date']  	actions = [make_book_pub_date_to_now]

8、Django Settings

详见:https://docs.djangoproject.com/en/1.10/ref/settings/