##用户认证
django自带用户认证系统,包括认证和授权。用户认证系统由用户,权限,用户组,密码,cookie和session给组成。
###用户认证系统设置
#settings.py
INSTALLED_APPS中设置 django.contrib.auth
django.contrib.contenttypes
MIDDLEWARE 中设置
AuthenticationMiddleware ###用户默认功能
1)私有属性
username
password
email
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-用户认证,授权,自定义用户认证的更多相关文章

  1. Taurus.MVC 微服务框架 入门开发教程:项目集成:4、默认安全认证与自定义安全认证。

    系列目录: 本系列分为项目集成.项目部署.架构演进三个方向,后续会根据情况调整文章目录. 本系列第一篇:Taurus.MVC V3.0.3 微服务开源框架发布:让.NET 架构在大并发的演进过程更简单 ...

  2. drf框架中jwt认证,以及自定义jwt认证

    0909自我总结 drf框架中jwt 一.模块的安装 官方:http://getblimp.github.io/django-rest-framework-jwt/ 他是个第三方的开源项目 安装:pi ...

  3. django学习日志之自定义用户扩展

    django 为我们提供了强大的用户认证系统,并且提供了基于该系统的User模型,所以,很多时候,我们有必要对自己的user进行业务扩展,得到满足我们自己业务需求的user.借此,写下自己的感悟. u ...

  4. VSCode添加用户代码片段,自定义用户代码片段

    在使用VScode开发中经常会有一些重复使用的代码块,复制粘贴也很麻烦,这时可以在VScode中添加用户代码片段,输入简写即可快捷输入. VScode中添加用户自定义代码片段很简单. 1.在VScod ...

  5. Django自定义用户认证系统之自定义用户模型

    参考文档:http://python.usyiyi.cn/django/topics/auth/customizing.html Django 自带的认证系统足够应付大多数情况,但你或许不打算使用现成 ...

  6. SpringSecurity(1)---认证+授权代码实现

    认证+授权代码实现 Spring Security是 一种基于 Spring AOP 和 Servlet 过滤器的安全框架.它提供全面的安全性解决方案,同时在 Web 请求级和方法调用级处理身份确认和 ...

  7. mysql新建数据库、新建用户及授权操作

    1.创建数据库create database if not exists test176 default charset utf8 collate utf8_general_ci; #utf8_gen ...

  8. vertica创建新用户并授权

    1.创建用户,并设置密码: create user user1 identified by 'pwd1'; 2.把角色授权给用户(dbduser是普通角色): grant dbduser to use ...

  9. CentOS7 添加新用户并授权 root 权限

    参考文章:CentOS 7中添加一个新用户并授权 # root 用户操作 $ 普通用户操作 创建用户 # adduser USERNAME # passwd USERNAME (输入密码) 授权 ro ...

随机推荐

  1. 添加Glide图片加载框架依赖

    1.添加依赖implementation 'com.github.bumptech.glide:glide:4.7.1' 2.放置一个ImageView.3.加载,ivGif是ImageView实例 ...

  2. 服务器中同一个【ip:port】可以多次accept的问题

    一.多次bind的问题 服务器的[ip:port]被某套接字绑定成功后,在该绑定解除之前,同一个[ip:port],不能再次被其他套接字绑定,否则绑定失败 二.多次accept的问题 有外来连接时,若 ...

  3. leetcode 90. subsets

    解题思路: 要生成子集,对于vector 中的每个数,对于每个子集有两种情况,加入或不加入. 因此代码: class Solution { public: void subsetG(vector< ...

  4. pyqt5-QWidget-窗口状态(最大化最小化等)

    setWindowState(state)          #设置窗口状态 Qt.WindowNoState  无状态-正常状态 Qt.WindowMinimized     最小化 Qt.Wind ...

  5. [C++]PAT乙级1003. 我要通过!(17/20)

    /* 1003. 我要通过!(20) “答案正确”是自动判题系统给出的最令人欢喜的回复.本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错 ...

  6. :target方法实现切换

    <!DOCTYPE HTML><html><head> <title>:target切换</title> <meta charset= ...

  7. luogu P4931 情侣?给我烧了!

    双倍经验 传送门 首先坐在一起的cp和不坐在一起的cp是相对独立的,可以分开考虑,然后方案数相乘 坐在一起的cp,方案为\(\binom{n}{k}*\binom{n}{k}*k!*2^k\).首先选 ...

  8. python基础类知识~pymysql封装类

    一简介:咱们来介绍下 DBA常用的几个类 二 具体代码 #!/usr/bin/python3import pymysqlimport sysclass DBHelper: def __init__(s ...

  9. Callable的用法示例

    //Runnable是执行工作的独立任务,但是它不返回任何值.在JavaSE5中引入的Callable是一种具有类型参数的泛型,它的类型参数表的是从方法call()中返回的值,并且必须使用Execut ...

  10. Android插件化技术简介

    https://blog.csdn.net/io_field/article/details/79084630 可以通过反射 事先定义统一接口的方式,访问插件中的类和方法 还可以在AndroidMan ...