new_candy

导航

django登录逻辑

django-restframework中已经实现了登录逻辑,只需要安装配置就可以使用

pip install djangorestframework-jwt
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),  # 指明token的有效期
  'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.utils.jwt_response_payload_handler',  # 指定自定义jwt_token签发应用
}
AUTHENTICATION_BACKENDS = [
    'users.utils.UsernameMobileAuthBackend',  # 指定自定义用户登录认证
]

使用:Django REST framework JWT提供了登录签发JWT的视图,可以直接使用,但是默认的返回值仅有token,我们还需在返回值中增加username和user_id。

1、注册路由

url(r'^authorizations/$', obtain_jwt_token),

2、自定义jwt签发函数

def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

3、编辑视图函数,可以允许用户以手机号或者用户名进行登录

import re
from django.contrib.auth.backends import ModelBackend

from users.models import User

class
UsernameMobileAuthBackend(ModelBackend): """ 自定义用户名或手机号认证 """ def authenticate(self, request, username=None, password=None, **kwargs):
      try:
          if re.match('^1[3-9]\d{9}$', account):
              # 帐号为手机号
              user = User.objects.get(mobile=username)
          else:
              # 帐号为用户名
              user = User.objects.get(username=username)
      except User.DoesNotExist:
          return None
  if user is not None and user.check_password(password): 
    return user

 

posted on 2018-09-20 20:53  new_candy  阅读(355)  评论(0编辑  收藏  举报