路飞项目多方式登录、手机号短信验证注册接口

登录注册页面分析

用户板块需要写的接口

  1. 用户名密码登录(多方式登录)
  2. 获取手机验证码接口
  3. 手机号+验证码登录
  4. 注册接口
  5. 验证手机号是否存在接口

验证手机号是否存在

视图类
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from .models import User
from luffy01.utils.common_response import APIResponse
class MobileView(ViewSet):
    @action(methods=['GET'], detail=False)
    def check_mobile(self, request, *args, **kwargs):
        try:
            mobile = request.query_params['mobile']
            User.objects.get(mobile=mobile)
        except Exception as e:
            # 报错就说明没有查到
            raise Exception('手机号不存在')

        return APIResponse(msg='手机号存在')
路由分发
from django.urls import path, include
urlpatterns = [
    path('api/v1/user/', include('luffy01.apps.user.urls'))
]
路由
from rest_framework.routers import SimpleRouter
from .views import MobileView

router = SimpleRouter()
# 127.0.0.1:8000/api/v1/user/mobile/check_mobile/   ---get 请求
router.register('mobile', MobileView, 'mobile')

urlpatterns = []
urlpatterns += router.urls

后端多方式登录接口

分析

前端

前端携带的数据:{username:用户名,手机号,邮箱,password:md5(密码)}

注册的时候:密码也是md5加密后带过来的

我们登录的时候,带的密码是md5加密的 ⇢ \dashrightarrow 后端校验通不过

后端
  • request.data中取出来
  • 校验用户名密码是否正确 ⇢ \dashrightarrow 逻辑写到 序列类中
  • 配合序列化类 ⇢ \dashrightarrow 全局钩子中写逻辑,签发token
  • 返回给前端
总结
  1. 序列化类实例化得到对象时要

代码

序列化类
from rest_framework import serializers
import re
from .models import User
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
from django.conf import settings


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def _get_user(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        if re.match(r'^1[3-9][0-9]{9}$', username):
            user = User.objects.filter(mobile=username).first()
        elif re.match(r'[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$', username):
            user = User.objects.filter(email=username).first()
        else:
            user = User.objects.filter(username=username).first()

        if user and user.check_password(password):
            return user
        else:
            raise Exception('用户密码错误')

    def _get_token(self, user):
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token

    def validate(self, attrs):
        user = self._get_user(attrs)
        token = self._get_token(user)
        self.context['username'] = user.username
        self.context['token'] = token
        self.context['icon'] = settings.BACKEND_URL + '/media/' + str(user.icon)
        return attrs

视图函数
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from luffy01.utils.common_response import APIResponse
from .serializer import UserLoginSerializer

class UserLoginView(GenericViewSet):
    serializer_class = UserLoginSerializer

    @action(methods=['POST'], detail=False)
    def mul_login(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        username = ser.context.get('username')
        token = ser.context.get('token')
        icon = ser.context.get('icon')
        return APIResponse(username=username, token=token, icon=icon)

发送短信封装

创建目录

在libs中创建包

tx_sms
	__init__.py
	settings.py
	sms.py
在settings中
SECRET_ID=''
SECRET_KEY=''
APPID=''
SIGN_NAME=''
TEMPLATE_ID=''
sms.py
# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.sms.v20210111 import sms_client, models
# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
import random
import settings
import json
# 1. 生成一个 固定长度的随机验证码(数字)
def get_code(number=4):
    code = ''
    for i in range(number):
        r = random.randint(0, 9)
        code += str(r)
    return code

# 2 传入手机号和验证,发送短信功能函数
def send_sms(code, mobile):
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
        # 您也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
        # 以免泄露密钥对危及您的财产安全。
        # SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential("settings.SECRET_ID", "settings.SECRET_KEY")

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        # 如果需要指定proxy访问接口,可以按照如下方式初始化hp(无需要直接忽略)
        # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口")
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30    # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        # 您可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
        # 属性可能是基本类型,也可能引用了另一个数据结构
        # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
        req = models.SendSmsRequest()

        # 基本类型的设置:
        # SDK采用的是指针风格指定参数,即使对于基本类型您也需要用指针来对参数赋值。
        # SDK提供对基本类型的指针引用封装函数
        # 帮助链接:
        # 短信控制台: https://console.cloud.tencent.com/smsv2
        # 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81

        # 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666
        # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
        req.SmsSdkAppId = "settings.APPID"
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
        # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
        req.SignName = settings.SIGN_NAME
        # 模板 ID: 必须填写已审核通过的模板 ID
        # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
        req.TemplateId = settings.TEMPLATE_ID
        # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
        req.TemplateParamSet = [code, '1']
        # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
        # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = ["+86" + mobile]
        # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = ""
        # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手]
        req.ExtendCode = ""
        # 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId,无需填写该字段。注:月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。
        req.SenderId = ""

        resp = client.SendSms(req)

        # 输出json格式的字符串回包
        print(resp.to_json_string(indent=2))

        response_data_dict = json.loads(resp.to_json_string(indent=2))

        if response_data_dict.get('SendStatusSet')[0].get('Code') == 'Ok':
            return True
        else:
            # 失败了,可以拿出message---》正常发送失败
            return False

    except Exception as err:
        # 发送过程中出了错误,失败
        return False
在init中
from .sms import get_code, send_sms

短信验证码接口

from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from luffy01.utils.common_response import APIResponse
from luffy01.libs.tx_sms import get_code, send_sms as send_sms_mobile
from django.core.cache import cache
from threading import Thread


class MobileView(ViewSet):
    @action(methods=['POST'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        mobile = request.data.get('mobile')
        code = get_code()

		# 数字验证码保存  放到缓存中
        cache.set('cache_mobile_%s' % mobile, code)

		# 发送短信 异步操作,使用多线程,无法知道短信是否成功了,不需要关注是否成功
        t = Thread(target=send_sms_mobile, args=[code, mobile])
        t.start()
        return APIResponse(msg='短信已发送')

短信登录接口

分析

前端携带的数据 ⇢ \dashrightarrow {mobile:11111,code:8888}

后端
  • 取出手机号验证码,验证验证码是否正确,如果正确
  • 签发token
  • 返回给前端

代码

视图类
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from .models import User
from luffy01.utils.common_response import APIResponse
from .serializer import UserLoginSerializer,SmsLoginSerializer
from django.core.cache import cache

class UserLoginView(GenericViewSet):
    serializer_class = UserLoginSerializer

    def _login(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        username = ser.context.get('username')
        token = ser.context.get('token')
        icon = ser.context.get('icon')
        return APIResponse(username=username, token=token, icon=icon)

    def get_serializer_class(self):
        if self.action == 'mul_login':
            return UserLoginSerializer
        elif self.action == 'sms_login':
            return SmsLoginSerializer
        else:
            return super().get_serializer_class()

    @action(methods=['POST'], detail=False)
    def sms_login(self, request, *args, **kwargs):
        return self._login(request, *args, **kwargs)
序列化类
from rest_framework import serializers
import re
from .models import User
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
from django.conf import settings
from django.core.cache import cache


class LoginSerializer(serializers.Serializer):
    def _get_user(self, attrs):
        pass

    def _get_token(self, user):
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token

    def validate(self, attrs):
        user = self._get_user(attrs)
        token = self._get_token(user)
        self.context['username'] = user.username
        self.context['token'] = token
        self.context['icon'] = settings.BACKEND_URL + '/media/' + str(user.icon)
        return attrs

class SmsLoginSerializer(LoginSerializer):
    mobile = serializers.CharField()
    code = serializers.CharField()

    def _get_user(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get('cache_mobile_%s' % mobile)
        if code == old_code or '8888':
            user = User.objects.filter(mobile=mobile).first()
            if user:
                return user
            else:
                raise Exception('手机号不存在')
        else:
            raise Exception('验证码错误')


短信注册接口

分析

  • 前端:携带数据格式
  • 后端:
    • 视图类:视图类 ⇢ \dashrightarrow 注册方法
    • 序列化类 ⇢ \dashrightarrow 校验,保存(表中字段多,传的少 ⇢ \dashrightarrow 随机,按某种格式生成 ⇢ \dashrightarrow 后期修改)

代码

序列化类
from rest_framework import serializers
from .models import User

class UserRegisterSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=4, min_length=4, write_only=True)

    class Meta:
        model = User
        fields = ['mobile', 'code', 'password']

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get('cache_mobile_%s' % mobile)
        if code == old_code or code == '8888':
            attrs['username'] = mobile
            attrs.pop('code')
            return attrs
        else:
            raise Exception('验证码错误')

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

试图类
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from .models import User
from luffy01.utils.common_response import APIResponse
from .serializer import UserRegisterSerializer
from rest_framework.mixins import CreateModelMixin

class UserRegisterView(GenericViewSet, CreateModelMixin):
    serializer_class = UserRegisterSerializer
    @action(methods=['POST'], detail=False)
    def register(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return APIResponse(msg='注册成功')

你可能感兴趣的:(路飞项目,python,django)