43)django-用户认证,授权,自定义用户认证
- ##用户认证
- django自带用户认证系统,包括认证和授权。用户认证系统由用户,权限,用户组,密码,cookie和session给组成。
- ###用户认证系统设置
- #settings.py
- INSTALLED_APPS中设置
- django.contrib.auth
- django.contrib.contenttypes
- MIDDLEWARE 中设置
- AuthenticationMiddleware
- ###用户默认功能
- 1)私有属性
- username
- password
- first_name
- last_name
- 2)创建普通用户
- from django.contrib.auth.models import User
- user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
- 3)创建管理员
- python manage.py createsuperuser --username=joe --email=joe@example.com
- 4)修改密码
- from django.contrib.auth.models import User
- u = User.objects.get(username='john')
- u.set_password('new password')
- u.save()
- 5)验证用户
- from django.contrib.auth import authenticate
- user = authenticate(username='john', password='secret')
- if user is not None:
- #验证成功
- else:
- # 验证失败
- 6)权限和授权
- has_add_permission() #增加权限
- has_change_permission()#修改权限
- has_delete_permission()#删除权限
- myuser.groups.set([group_list])
- myuser.groups.add(group, group, ...)
- myuser.groups.remove(group, group, ...)
- myuser.groups.clear()
- myuser.user_permissions.set([permission_list])
- myuser.user_permissions.add(permission, permission, ...)
- myuser.user_permissions.remove(permission, permission, ...)
- myuser.user_permissions.clear()
- 7)默认权限在python manage.py migrate创建
- 8)添加自定义权限
- 比如应用名:foo 模板名: Bar
- 添加: user.has_perm('foo.add_bar')
- 修改: user.has_perm('foo.change_bar')
- 删除: user.has_perm('foo.delete_bar')
- 9)验证成功登陆
- from django.contrib.auth import authenticate, login
- def my_view(request):
- username = request.POST['username']
- password = request.POST['password']
- user = authenticate(request, username=username, password=password)
- if user is not None:
- login(request, user)
- # Redirect to a success page.
- ...
- else:
- # Return an 'invalid login' error message.
- ...
- 10)检查是登陆成功(session)
- if request.user.is_authenticated:
- # Do something for authenticated users.
- ...
- else:
- # Do something for anonymous users.
- 11)登出
- from django.contrib.auth import logout
- def logout_view(request):
- logout(request)
- 12)用装饰器验证是否登陆成功
- from django.contrib.auth.decorators import login_required
- @login_required
- def my_view(request):
- #如果没有设置settings.LOGIN_URL,就验证没有成功,默认会跳转
- 比如 /accounts/login/?next=/polls/3/ next是你验证的页面,如果页面验证成功会还回next页面
- from django.contrib.auth.decorators import login_required
- #验证成功跳到指定的页面
- @login_required(login_url='/accounts/login/')
- @login_required(redirect_field_name='my_redirect_field')
- def my_view(request):
- 13)限制某些用户登陆
- from django.shortcuts import redirect
- def my_view(request):
- if not request.user.email.endswith('@example.com'):
- return redirect('/login/?next=%s' % request.path)
- 14)修改密码
- from django.contrib.auth import update_session_auth_hash
- def password_change(request):
- if request.method == 'POST':
- form = PasswordChangeForm(user=request.user, data=request.POST)
- if form.is_valid():
- form.save()
- update_session_auth_hash(request, form.user)
- else:
- ...
- ##
- <form method="post" action="{% url 'login' %}">
- {% csrf_token %}
- <table>
- <tr>
- <td>{{ form.username.label_tag }}</td>
- <td>{{ form.username }}</td>
- </tr>
- <tr>
- <td>{{ form.password.label_tag }}</td>
- <td>{{ form.password }}</td>
- </tr>
- </table>
- <input type="submit" value="login" />
- <input type="hidden" name="next" value="{{ next }}" />
- </form>
- 15)默认URL
- accounts/login/ [name='login']
- accounts/logout/ [name='logout']
- accounts/password_change/ [name='password_change']
- ###定制用户认证
- 示例:
- #在model里面写入,字段可以该成需要的
- from django.db import models
- from django.contrib.auth.models import (
- BaseUserManager, AbstractBaseUser
- )
- class MyUserManager(BaseUserManager):
- def create_user(self, email, date_of_birth, password=None):
- """
- Creates and saves a User with the given email, date of
- birth and password.
- """
- if not email:
- raise ValueError('Users must have an email address')
- user = self.model(
- email=self.normalize_email(email),
- date_of_birth=date_of_birth,
- )
- user.set_password(password)
- user.save(using=self._db)
- return user
- def create_superuser(self, email, date_of_birth, password):
- """
- Creates and saves a superuser with the given email, date of
- birth and password.
- """
- user = self.create_user(
- email,
- password=password,
- date_of_birth=date_of_birth,
- )
- user.is_admin = True
- user.save(using=self._db)
- return user
- class MyUser(AbstractBaseUser):
- email = models.EmailField(
- verbose_name='email address',
- max_length=255,
- unique=True,
- )
- date_of_birth = models.DateField()
- is_active = models.BooleanField(default=True)
- is_admin = models.BooleanField(default=False)
- objects = MyUserManager()
- USERNAME_FIELD = 'email'
- REQUIRED_FIELDS = ['date_of_birth']
- def __str__(self):
- return self.email
- def has_perm(self, perm, obj=None):
- "Does the user have a specific permission?"
- # Simplest possible answer: Yes, always
- return True
- def has_module_perms(self, app_label):
- "Does the user have permissions to view the app `app_label`?"
- # Simplest possible answer: Yes, always
- return True
- @property
- def is_staff(self):
- "Is the user a member of staff?"
- # Simplest possible answer: All admins are staff
- return self.is_admin
- #注册admin
- from django import forms
- from django.contrib import admin
- from django.contrib.auth.models import Group
- from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
- from django.contrib.auth.forms import ReadOnlyPasswordHashField
- from customauth.models import MyUser
- class UserCreationForm(forms.ModelForm):
- """A form for creating new users. Includes all the required
- fields, plus a repeated password."""
- password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
- password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
- class Meta:
- model = MyUser
- fields = ('email', 'date_of_birth')
- def clean_password2(self):
- # Check that the two password entries match
- password1 = self.cleaned_data.get("password1")
- password2 = self.cleaned_data.get("password2")
- if password1 and password2 and password1 != password2:
- raise forms.ValidationError("Passwords don't match")
- return password2
- def save(self, commit=True):
- # Save the provided password in hashed format
- user = super().save(commit=False)
- user.set_password(self.cleaned_data["password1"])
- if commit:
- user.save()
- return user
- class UserChangeForm(forms.ModelForm):
- """A form for updating users. Includes all the fields on
- the user, but replaces the password field with admin's
- password hash display field.
- """
- password = ReadOnlyPasswordHashField()
- class Meta:
- model = MyUser
- fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')
- def clean_password(self):
- # Regardless of what the user provides, return the initial value.
- # This is done here, rather than on the field, because the
- # field does not have access to the initial value
- return self.initial["password"]
- class UserAdmin(BaseUserAdmin):
- # The forms to add and change user instances
- form = UserChangeForm
- add_form = UserCreationForm
- # The fields to be used in displaying the User model.
- # These override the definitions on the base UserAdmin
- # that reference specific fields on auth.User.
- list_display = ('email', 'date_of_birth', 'is_admin')
- list_filter = ('is_admin',)
- fieldsets = (
- (None, {'fields': ('email', 'password')}),
- ('Personal info', {'fields': ('date_of_birth',)}),
- ('Permissions', {'fields': ('is_admin',)}),
- )
- # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
- # overrides get_fieldsets to use this attribute when creating a user.
- add_fieldsets = (
- (None, {
- 'classes': ('wide',),
- 'fields': ('email', 'date_of_birth', 'password1', 'password2')}
- ),
- )
- search_fields = ('email',)
- ordering = ('email',)
- filter_horizontal = ()
- # Now register the new UserAdmin...
- admin.site.register(MyUser, UserAdmin)
- # ... and, since we're not using Django's built-in permissions,
- # unregister the Group model from admin.
- admin.site.unregister(Group)
- #在setting中设置使用那个认证类
- settings.py:
- AUTH_USER_MODEL = 'customauth.MyUser'
43)django-用户认证,授权,自定义用户认证的更多相关文章
- Taurus.MVC 微服务框架 入门开发教程:项目集成:4、默认安全认证与自定义安全认证。
系列目录: 本系列分为项目集成.项目部署.架构演进三个方向,后续会根据情况调整文章目录. 本系列第一篇:Taurus.MVC V3.0.3 微服务开源框架发布:让.NET 架构在大并发的演进过程更简单 ...
- drf框架中jwt认证,以及自定义jwt认证
0909自我总结 drf框架中jwt 一.模块的安装 官方:http://getblimp.github.io/django-rest-framework-jwt/ 他是个第三方的开源项目 安装:pi ...
- django学习日志之自定义用户扩展
django 为我们提供了强大的用户认证系统,并且提供了基于该系统的User模型,所以,很多时候,我们有必要对自己的user进行业务扩展,得到满足我们自己业务需求的user.借此,写下自己的感悟. u ...
- VSCode添加用户代码片段,自定义用户代码片段
在使用VScode开发中经常会有一些重复使用的代码块,复制粘贴也很麻烦,这时可以在VScode中添加用户代码片段,输入简写即可快捷输入. VScode中添加用户自定义代码片段很简单. 1.在VScod ...
- Django自定义用户认证系统之自定义用户模型
参考文档:http://python.usyiyi.cn/django/topics/auth/customizing.html Django 自带的认证系统足够应付大多数情况,但你或许不打算使用现成 ...
- SpringSecurity(1)---认证+授权代码实现
认证+授权代码实现 Spring Security是 一种基于 Spring AOP 和 Servlet 过滤器的安全框架.它提供全面的安全性解决方案,同时在 Web 请求级和方法调用级处理身份确认和 ...
- mysql新建数据库、新建用户及授权操作
1.创建数据库create database if not exists test176 default charset utf8 collate utf8_general_ci; #utf8_gen ...
- vertica创建新用户并授权
1.创建用户,并设置密码: create user user1 identified by 'pwd1'; 2.把角色授权给用户(dbduser是普通角色): grant dbduser to use ...
- CentOS7 添加新用户并授权 root 权限
参考文章:CentOS 7中添加一个新用户并授权 # root 用户操作 $ 普通用户操作 创建用户 # adduser USERNAME # passwd USERNAME (输入密码) 授权 ro ...
随机推荐
- 【由浅入深理解java集合】(三)——集合 List
第一篇文章中介绍了List集合的一些通用知识.本篇文章将集中介绍List集合相比Collection接口增加的一些重要功能以及List集合的两个重要子类ArrayList及LinkedList. 一. ...
- VS Resharper正常代码显示红色处理
点击重启VS即可.
- hadoop3.x的安装
请看https://www.cnblogs.com/garfieldcgf/p/8119506.html
- Spring使用事务增加的注解实现方
以下是我的文件结构 步骤1:配置数据源 <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDa ...
- python 学习 argparse
1. argparse python 中用于解析命令行参数和选项的标准模块 创建一个解析器对象,解析器类ArgumentParser add_argument() 方法用来指定程序接受那些命令行参数, ...
- BN_batch normalization
参考: https://zhuanlan.zhihu.com/p/27938792 做法 设,每个batch输入是 (其中每个 都是一个样本, 是batch size) 假如在第一层后加入Batch ...
- VS中ipch文件夹和sdf文件的处理方式
ipch文件夹和sdf是VS产生的预编译头文件和智能提示信息,对编码没有影响,可存放在固定的位置,定期进行清理
- plsql 根据sid连接oracle
ORCL73 = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.10.73)(PORT = 152 ...
- Frameset 框架
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.c ...
- [C++]2-2 韩信点兵
/* 韩信点兵 相传韩信才智过人,从不直接清点自己军队的人数,只要让士兵先后以三人一排.五人一排.七人一排地变换队 形,而他每次只掠一眼队伍的排尾就知道总人数了.输入多组数据,每组数据包含3个非负整数 ...