django认证系统和itsdangerous
django内置认证系统
- create_user:创建用户
- authenticate:登录验证,用户名密码正确返回user对象,返回none
- login: 记录登录状态
- logout: 退出用户登录
- is_authenticated: 判断用户是否登录, 主语是request.user
- login_required装饰器: 进行登录判断
django内置中间件: django.contrib.sessions.middleware.SessionMiddleware 就是用来给request加一个user属性的,所以在后端views的request.user总有内容
自定义权限认证系统
models.py
from django.contrib.auth.models import User, Group
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
class PoliceManager(BaseUserManager):
def create_user(self, number, name, department,password='1234qwer'):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not number:
raise ValueError('Users must have an email address')
user = self.model(
number=number,
name=name,
department=department
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, number, name, department,password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
number,
password=password,
name=name,
department=department
)
user.is_superuser = True
user.save(using=self._db)
return user
class Police(AbstractBaseUser, PermissionsMixin):
number = models.CharField(
verbose_name='编号',
max_length=255,
unique=True,
)
name = models.CharField(max_length=64, verbose_name="姓名")
department = models.CharField(max_length=64, verbose_name="部门")
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True)
#is_admin = models.BooleanField(default=False)
# role = models.ManyToManyField("Role", blank=True, null=True)
objects = PoliceManager()
USERNAME_FIELD = 'number'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
# The user is identified by their email address
return self.name
def get_short_name(self):
# The user is identified by their email address
return self.name
def __str__(self): # __unicode__ on Python 2
return self.name
class Meta:
db_table = 'police'
settings.py
AUTH_USER_MODEL = "phone_call.Police"
LOGIN_URL = '/account/login/'
itsdangerous
我们发送邮件的时候,可以把邮件和用户关联的信息放到数据库存起来,也可以把用户信息放到url里面,而且这个信息又得满足时间会失效的问题,itsdangerous模块可以完成这个功能。
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
serializer = Serializer(settings.SECRET_KEY, 3600)
try:
info = serializer.loads(token)
# 获取待激活用户的id
user_id = info['confirm']
# 根据id获取用户信息
user = User.objects.get(id=user_id)
user.is_active = 1
user.save()
# 跳转到登录页面
return redirect(reverse('user:login'))
except SignatureExpired as e:
# 激活链接已过期
return HttpResponse('激活链接已过期')