一、验证码登录功能(接口)
1、后台
将验证码校验 封装成方法:如下图的 标红处
总的
# 自定义 手机验证码登录 序列化类 import re from django.core.cache import cache class MobileLoginViewSet(serializers.ModelSerializer): # 覆盖数据库中的mobile字段 mobile = serializers.CharField(required=True,write_only=True) # code 是不入库的。所以要这这个序列化类中 写code字段,进行序列化 # required=True表示:。。。 write_only=True 表示 :前端到后端 # 自定义 code字段 code = serializers.CharField(min_length=4,max_length=4,required=True,write_only=True) class Meta: model = models.User fields = ( 'id', 'username','icon','mobile','code') # id username icon 的校验规则 extra_kwargs = { 'id': { 'read_only': True, }, 'username': { 'read_only': True, }, 'icon': { 'read_only': True, }, } # 局部钩子 用来校验 mobile字段(手机号) 的格式是否正确 def validate_mobile(self, value): if not re.match(r'^1[3-9][0-9]{9}$',value): raise exceptions.ValidationError('mobile field error') return value # 用全局钩子 来校验 用户提交给后端的验证码是否 过期了 def validate(self, attrs): mobile=self._check_code(attrs) user = self._get_user(mobile) # 调用_get_user()方法 得到user token = self._get_token(user) # user签发token self.context['token'] = token # token用context属性 携带给视图类。 self.context['user'] = user # 把 user给外界 将登录用户对象直接传给视图 return attrs def _check_code(self,attrs): mobile = attrs.get('mobile') code = attrs.pop('code') # pop表示弹出列表/字典里 最后一个元素。 # 这里用pop是因为 code 不往数据库中存呀 old_code = cache.get(settings.SMS_CACHE_KEY % {'mobile': mobile}) # SMS_CACHE_KEY 是暂存在django内嵌的缓存数据库的 验证码 if code != old_code: raise exceptions.ValidationError({'code': 'double code error'}) else: # 验证码的时效性:一旦验证码校验通过,就代表该验证码已使用,需要立即失效(用来测试的) # cache.set(settings.SMS_CACHE_KEY % {'mobile': mobile}, '', -1) # -1或0表示立即失效
pass
return mobile def _get_user(self, mobile): # 拿到用户登录时 输入的用户信息(手机号) try: return models.User.objects.get(mobile=mobile) # 在数据库中 拿出user对象 except: raise exceptions.ValidationError({'mobile': 'user not exist'}) def _get_token(self, user): # user 是对象 # 从jwt认证 插件中的 序列化组件 中 导入 jwt_payload_handler,jwt_encode_handler from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler payload = jwt_payload_handler(user) # user 是对象 token = jwt_encode_handler(payload) return token
二、前台
js 中正则的 语法:
‘字符串’.match(/正则语法/)
登录按钮的 点击事件。
注意:下面的$axios的data 错了,应该写成params 因为:get请求用params
修改后台 频率文件