django自定义配置auth登录功能
1.在users用户下创建utils.py ,其代码如下
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from . import models
from django.contrib import auth # 导入auth模块
from django.contrib.auth.models import User # 导入auth_user表对象
from django.contrib.auth.decorators import login_required # 校验用户是否登陆的装饰器
def get_user_by_account(username):
"""用于验证用户是否存在"""
try:
user=models.User.objects.get(Q(username=username) | Q(mobile=username))
except models.User.DoesNotExist:
return None
else:
return user
class UsernameMobileAuthBackend(ModelBackend):
"""自定义登录功能"""
def authenticate(self, request, username=None, password=None, **kwargs):
user=get_user_by_account(username)
print(user.username,user.id)
if user is not None and user.check_password(password):
# auth.login(request,user)
return user #如果登录成功返回该用户对象
else:
return None #如果登录失败则返回None
def jwt_response_payload_handler(token, user=None, request=None):
"""
自定义jwt认证成功返回数据
"""
return {
'token': token,
'id': user.id,
'username': user.username
}
2.settings/dev 中配置如下参数
#配置自己写的登录认证
# 配置自定义认证机制
AUTHENTICATION_BACKENDS = [
'users.utils.UsernameMobileAuthBackend',
]
3.登录认证路由
-
总路由urls.py配置
urlpatterns = [ path('admin/', admin.site.urls), #配置xadmin的路由 path('xadmin/', xadmin.site.urls), #配置xadmin上传轮播图 re_path(r'media/(?P<path>.*)',serve,{'document_root':settings.MEDIA_ROOT}), #将路由转发给home应用 path(r'home/',include('home.urls')), #将路由转发给user应用,用于登录认证 path(r'users/',include('users.urls')), #将路由转发给course这个应用 path(r'course/',include('course.urls')), ]
-
users 应用路由配置
from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ path(r'login/', obtain_jwt_token), ]