首页 > 其他分享 >登录注册

登录注册

时间:2022-11-13 19:35:34浏览次数:47  
标签:code 登录 get mobile self user 注册 import

登录注册

登录功能分析

1.登录方式为多方式登录,可以使用 用户名/邮箱/手机号+密码的形式完成登录

2.在使用手机号登陆前,需要校验手机号是否存在

3.使用手机号+验证码的方式登录

4.发送手机验证嘛

5.手机号的注册接口

登录模块

将逻辑写入序列化模块中,不在视图类中增添校验逻辑功能

序列化模块 serializer.py

from rest_framework import serializers
from .models import UserInfo
import re
from django.contrib.auth import authenticate
from rest_framework.exceptions import ValidationError, APIException
from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class UserLoginSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ['username','password','mobile','code']
         # 封装之隐藏属性  __表示隐藏, _并不是隐藏,公司里约定俗成用 _ 表示只在内部用,如果外部想用,也可以用

        def _get_token(self,user):
            try:
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                return token
            except Exception as e:
                raise ValidationError(str(e))
            
 """将序列化重复使用的模块封装成一个类,下面需使用的时候直接使用super调用父类即可"""           
            

# 这个序列类,只用来做登录校验,不做序列化,不做反序列化
class UserMulLoginSerializer(UserLoginSerializer):
    username = serializers.CharField()  # 重写,优先用现在的,就没有unique的限制了

    def _get_user(self, attrs):
        # attrs 是校验过后的数据:字段自己的规则【字段自己有规则:坑】和局部钩子
        username = attrs.get('username')
        password = attrs.get('password')
        # username可能是用户名,邮箱,手机号---》使用正则判断
        if re.match(r'^1[3-9][0-9]{9}$', username):
            user = UserInfo.objects.filter(mobile=username).first()
        elif re.match(r'^.+@.+$', username):  # adsa@adsf  会有bug,用户名中如果有@,登录不了了
            user = UserInfo.objects.filter(email=username).first()
        else:
            user = UserInfo.objects.filter(username=username).first()

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


    # 还要写别的
    def validate(self, attrs):
        # 1  取出用户名和密码,校验用户是否存在
        user = self._get_user(attrs)
        # 2 签发token
        token = super()._get_token(user)
        # 3 把token放到序列化类对象中
        self.context['token'] = token
        self.context['username'] = user.username
        self.context['icon'] = 'http://127.0.0.1:8000/media/'+str(user.icon) # 这是个对象,可能会有问题
        # self.context['icon'] = user.icon  # 这是个对象,可能会有问题
        # 以后如果有问题,都抛异常
        # 如没有问题,返回attrs
        return attrs

class UserMobileLoginSerializer(UserLoginSerializer):
    code = serializers.CharField()  # code 不是UserInfo表的字段,一定要重写一下
    mobile = serializers.CharField()

    def _get_user(self,attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get('sms_code_%s' % mobile)
        cache.set('sms_code_%s' % mobile, '')  # 验证码用过了要清除
        if code == old_code:  # 万能验证码,在测试阶段,测试用的
            user = UserInfo.objects.filter(mobile=mobile).first()
            return user
        raise APIException('验证码错误')

        def validate(self, attrs):
            # 1  手机号和code
            user = self._get_user(attrs)
            # 2 签发token
            token = self._get_token(user)
            # 3 把token放到序列化类对象中
            self.context['token'] = token
            self.context['username'] = user.username
            self.context['icon'] = 'http://127.0.0.1:8000/media/' + str(user.icon)
            return attrs

视图类user.view.py

登录方式有两种,一种常规的账号密码登录,另一种是手机号验证码登录

import re

from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import ViewSet, GenericViewSet, ViewSetMixin
from rest_framework.decorators import action
from .models import UserInfo
from .serializer import UserMulLoginSerializer,UserMobileLoginSerializer

from utils.response import APIResponse
from rest_framework.exceptions import APIException,ValidationError
from libs.send_phone_sms.sms import get_code,send_sms_by_phone
from django.core.cache import cache


class UserView(ViewSet):
    def get_serializer(self,data):
        if self.action == 'mul_login':
            return UserMulLoginSerializer(data=data)
        elif self.action == 'mobile_login':
            return UserMobileLoginSerializer(data=data)
        else:
            return ValidationError()

    def common_login(self,request):
        ser = UserMulLoginSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        username = ser.context.get('username')
        icon = ser.context.get('icon')
        return APIResponse(token=token, username=username, icon=icon)

    @action(methods=['POST'],detail=False)
    def mul_login(self,request):
        return self.common_login(request)

    @action(methods=['POST'], detail=False)
    def mobile_login(self, request):
        return self.common_login(request)

    @action(methods=['GET'],detail=False)
    def mobile(self,request):
        try:
            mobile = request.query_params.get('mobile')
            UserInfo.objects.get(mobile=mobile)
            return APIResponse(msg='手机号存在')
        except Exception as e:
            raise APIException('手机号不存在')
            
            
# 短信验证码接口
    @action(methods=['GET'], detail=False)
    def send_sms(self,request):
        mobile = request.query_params.get('mobile')
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            code = get_code()
            print(code)  # 保存验证码---》能存,不能丢,后期能取---》缓存--》django自带缓存框架
            # 放在内存中了,只要重启就没了----》后期学完redis,放到redis中,重启项目,还在
            cache.set('sms_code_%s' % mobile, code)
            # cache.get('sms_code_%s'%mobile)
            res = send_sms_by_phone(mobile, code)
            if res:
                return APIResponse(msg='发送短信成功')
            else:
                # raise APIException('发送短信失败')
                return APIResponse(msg='发送短信失败', code=101)
        else:
            return APIResponse(msg='手机号不合法', code=102)

路由 user.urls.py

from . import views

from rest_framework.routers import SimpleRouter

router = SimpleRouter()
# 127.0.0.1:8080/api/v1/userinfo/user/mul_login
router.register('user', views.UserView, 'user')

urlpatterns = [
]
urlpatterns += router.urls

总路由

from django.contrib import admin
from django.urls import path, re_path,include

from django.views.static import serve
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    # path('test/', views.TestView.as_view()),
    path('api/v1/home/', include('home.urls')),
    path('api/v1/userinfo/', include('user.urls')),
    # 开启media的访问
    path('media/<path:path>', serve, kwargs={'document_root': settings.MEDIA_ROOT}),
    # re_path('^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT})

]

验证码的发送

封装成 v3版本

# sdk:https://cloud.tencent.com/document/product/382/43196#
# 使用步骤:
	-下载模块:pip3 install tencentcloud-sdk-python

验证码测试 scripts/sms.py

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

try:
    cred = credential.Credential("AKIDmBPQGtLbR6Whew3xeAD9wc4LPFtMsNl0", "82jCRSFoBUfqoZ91lMluqY2Yt4oRr4EK")
    httpProfile = HttpProfile()
    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
    client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
    req = models.SendSmsRequest()
    req.SmsSdkAppId = "1400763623" # 腾讯短信创建app把app的id号复制过来https://console.cloud.tencent.com/smsv2/app-manage
    # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
    # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
    req.SignName = "日常交流吐槽公众号"
    # 模板 ID: 必须填写已审核通过的模板 ID
    # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
    req.TemplateId = "1605117"
    # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
    req.TemplateParamSet = ["8888",'100']
    # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
    # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
    req.PhoneNumberSet = ["+8615294791769"]
    # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
    req.SessionContext = ""
    req.ExtendCode = ""
    req.SenderId = ""

    resp = client.SendSms(req)

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

except TencentCloudSDKException as err:
    print(err)

把发送短信封装成包

创建 libs/send_phone_sms将短信封装成包

settings.py

# 发送短信相关的配置信息

SECRET_ID = 'AKIDmBPQGtLbR6Whew3xeAD9wc4LPFtMsNl0'
SECRET_KEY = '82jCRSFoBUfqoZ91lMluqY2Yt4oRr4EK'
APP_ID = '1400763623'
SIGN_NAME='日常交流吐槽公众号'
TEMPLATE_ID='1605117'

这里是包中调用的自己公众号极其验证码的配置信息

sys.py

# 核心代码
import random

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
from . import settings


# 获取n位随机数组验证码的函数
def get_code(num=4):
    code = ''
    for i in range(num):
        random_num = random.randint(0, 9)
        code += str(random_num)
    return code


# 发送短信函数
def send_sms_by_phone(mobile, code):
    try:
        cred = credential.Credential(settings.SECRET_ID, settings.SECRET_KEY)
        httpProfile = HttpProfile()
        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
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
        req = models.SendSmsRequest()
        req.SmsSdkAppId = settings.APP_ID  # 腾讯短信创建app把app的id号复制过来https://console.cloud.tencent.com/smsv2/app-manage
        # 短信签名内容: 使用 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 = ""
        req.SenderId = ""

        resp = client.SendSms(req)

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

        return True
    except TencentCloudSDKException as err:

        return False

标签:code,登录,get,mobile,self,user,注册,import
From: https://www.cnblogs.com/nirvana001/p/16886695.html

相关文章