路飞项目实战篇:注册登录

1、注册页面前端设计

# 登录注册版本,设计
	-用户表,没有其他表
    -写哪些接口?
    	-1 用户名密码登录---》多方式登录(可以使用  用户名+密码,手机号+密码,邮箱+密码)
        -2 校验手机号是否存在的接口
        -3 手机号+验证码登录  ---》后期改成如果没注册,直接注册并登录
        -4 发送验证码接口  ---》使用第三方发送短信
        -5 注册接口(手机号,验证码,密码)
        
        
   -目前可以先写出来
		-多方式登录
    	-校验手机号是否存在
        
  -如果发送短信---》第三方平台---》阿里大于短信,腾讯云短信,容联云通信----》花钱买短信条数---》调用它的接口---》给固定的人发送短信

2、多方式登录接口

# 前端传入的数据---》post请求
	{username:lqz,password:123}
    {username:18953675221,password:123}
    {username:33@qq.com,password:123}

# 咱们现在把逻辑写在序列化类中
	-写在全局钩子中

2.1 序列化类

from .models import User
from rest_framework import serializers
import re
from rest_framework.exceptions import ValidationError
from rest_framework_jwt.settings import api_settings
from rest_framework.exceptions import APIException

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class MulLoginSerializer(serializers.ModelSerializer):
    username = serializers.CharField()  # 必须重写该字段,否则会做唯一性校验,如果数据库存在,就抛异常了,没法往下走了

    class Meta:
        model = User
        fields = ['username', 'password']  # 字段自己的规则没有校验通过,从表模型映射过来的username是unique的

    def _check_user(self, attrs):  # 公司里约定俗称,隐藏属性 __,这个方法只想在内部使用,万一外部真要用,也可以用
        try:
            username = attrs.get('username')
            password = attrs.get('password')
            if re.match(r'^1[3-9][0-9]{9}$', username):  # 手机号登录
                user = User.objects.get(mobile=username)
            elif re.match(r'^.+@.+$', username):  # 邮箱登录
                user = User.objects.get(email=username)
            else:
                user = User.objects.get(username=username)
            if user.check_password(password):
                return user
            else:
                # 使用ValidationError抛异常,一定要写成字典形式,或者直接抛APIException
                # raise ValidationError({'detail':'用户名或密码错误'})
                raise APIException()
        except APIException:
            # raise ValidationError({'detail':'用户名或密码错误'})
            raise APIException(detail='密码错误')
        except Exception:
            raise APIException(detail='用户不存在')

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

    def validate(self, attrs):  # 在全局钩子中,校验用户是否登录成功,如果登录成功直接签发token
        # 1 多方式得到user---》用户名,手机号,邮箱
        user = self._check_user(attrs)  # 如果登录失败,就抛异常了
        # 2 user签发token---》签发token
        token = self._get_token(user)
        # 3 把token放到 self 对象中得context属性中
        self.context['token'] = token
        host = self.context.get('request').META['HTTP_HOST']
        self.context['icon'] = 'http://%s/media/%s' % (host, str(user.icon))

        return attrs

2.2 视图类

class LoginView(GenericViewSet):
    queryset = User.objects.all()
    serializer_class = MulLoginSerializer

    @action(methods=['POST'], detail=False)
    def mul_login(self, request):
        ser = self.get_serializer(data=request.data)
        # 这一句,会校验字段自己的规则,还会校验局部钩子,还会校验全局钩子
        ser.is_valid(raise_exception=True)  # 这样写,我们已经处理了全局异常,如果校验不通过,会抛异常
        # 生成token---->从序列化类中取出来
        token = ser.context.get('token')
        return APIResponse(token=token)

2.3 路由

from rest_framework.routers import SimpleRouter


from .views import MobileView,LoginView

# 向这个地址发送get请求,# 127.0.0.1:8000/api/v1/user/    mobile  ---get  就能校验手机号是否存在
router = SimpleRouter()

router.register('mobile', MobileView, 'mobile')
router.register('login', LoginView, 'login')

urlpatterns = [
]
urlpatterns += router.urls

3 手机号是否存在接口

3.1 urls.py

#总路由
path('api/v1/user/', include('user.urls')),

# user 的app下的urls.py
from .views import MobileView
router = SimpleRouter()
router.register('mobile', MobileView, 'mobile')
urlpatterns = [
]
urlpatterns += router.urls

3.2 视图类

class MobileView(ViewSet):
    def list(self, request):
        try:
            mobile = request.query_params.get('mobile')
            User.objects.get(mobile=mobile)  # 有且只有一条才正常
            return APIResponse()
        except:
            raise APIException(detail='手机号不存在')
            # return APIResponse(code=101, msg='手机号不存在')

3.3 访问路径

http://127.0.0.1:8000/api/v1/user/mobile/?mobile=189536745211

4 登录注册前端页面

4.1 登录注册模态框分析

# 如果登录注册是新的页面,比较好做
	-只需要新建两个页面组件---》点击某个按钮--->跳转到页面

4.2 组件通信之 子传父

<template> 
    <div class="login"><span @click="close_login">X</span>
</div> 

</template> 
<script> 
    export default {
        name: "Login", 
        methods: {
            close_login() { 
                // 控制父组件中的is_login变量编程false this.$emit('close_login') 
            } } } 
</script> 

    <style scoped> 
        .login { width: 100vw; 
            height: 100vh; 
            position: fixed; top: 0; left: 0;
            z-index: 10; 
            background-color: rgba(0, 0, 0, 0.3); } 
    </style>

4.3 登录注册前端页面复制

4.3.1 Header.vue

<template>
  <div class="header">
    <div class="slogan">
      <p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
    </div>
    <div class="nav">
      <ul class="left-part">
        <li class="logo">
          <router-link to="/">
            <img src="../assets/img/head-logo.svg" alt="">
          </router-link>
        </li>
        <li class="ele">
          <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">实战课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
        </li>
      </ul>

      <div class="right-part">
        <div>
          <span @click="put_login">登录</span>
          <span class="line">|</span>
          <span @click="put_register">注册</span>
        </div>
      </div>
      <Login v-if="is_login" @close="close_login" @go="put_register"></Login>
      <Register v-if="is_register" @close="close_register" @go="put_login"></Register>

    </div>
  </div>

</template>

<script>
import Login from "@/components/Login";
import Register from "@/components/Register";

export default {
  name: "Header",
  data() {
    return {
      url_path: sessionStorage.url_path || '/', // 定义了一个变量标志当前所在的路径
      is_login: false,
      is_register: false,
    }
  },
  methods: {
    goPage(url_path) {
      // 判断当前路径是不是要跳转的路由,如果不是,就跳转
      if (this.url_path !== url_path) {
        this.$router.push(url_path); // 跳转到相应路径
      }
      sessionStorage.url_path = url_path; // 当前路径存起来   好处是:点刷新后,还是在当前路径下
    },
    put_login() {
      this.is_login = true;
      this.is_register = false;
    },
    put_register() {
      this.is_login = false;
      this.is_register = true;
    },
    close_login() {
      this.is_login = false;
    },
    close_register() {
      this.is_register = false;
    }
  },
  created() {
    sessionStorage.url_path = this.$route.path;
    this.url_path = this.$route.path;
  },
  components: {
    Login, Register
  }
}
</script>

<style scoped>
.header {
  background-color: white;
  box-shadow: 0 0 5px 0 #aaa;
}

.header:after {
  content: "";
  display: block;
  clear: both;
}

.slogan {
  background-color: #eee;
  height: 40px;
}

.slogan p {
  width: 1200px;
  margin: 0 auto;
  color: #aaa;
  font-size: 13px;
  line-height: 40px;
}

.nav {
  background-color: white;
  user-select: none;
  width: 1200px;
  margin: 0 auto;

}

.nav ul {
  padding: 15px 0;
  float: left;
}

.nav ul:after {
  clear: both;
  content: '';
  display: block;
}

.nav ul li {
  float: left;
}

.logo {
  margin-right: 20px;
}

.ele {
  margin: 0 20px;
}

.ele span {
  display: block;
  font: 15px/36px '微软雅黑';
  border-bottom: 2px solid transparent;
  cursor: pointer;
}

.ele span:hover {
  border-bottom-color: orange;
}

.ele span.active {
  color: orange;
  border-bottom-color: orange;
}

.right-part {
  float: right;
}

.right-part .line {
  margin: 0 10px;
}

.right-part span {
  line-height: 68px;
  cursor: pointer;
}
</style>

4.3.2 Login.vue

<template>
    <div class="login">
        <div class="box">
            <i class="el-icon-close" @click="close_login"></i>
            <div class="content">
                <div class="nav">
                    <span :class="{active: login_method === 'is_pwd'}"
                          @click="change_login_method('is_pwd')">密码登录</span>
                    <span :class="{active: login_method === 'is_sms'}"
                          @click="change_login_method('is_sms')">短信登录</span>
                </div>
                <el-form v-if="login_method === 'is_pwd'">
                    <el-input
                            placeholder="用户名/手机号/邮箱"
                            prefix-icon="el-icon-user"
                            v-model="username"
                            clearable>
                    </el-input>
                    <el-input
                            placeholder="密码"
                            prefix-icon="el-icon-key"
                            v-model="password"
                            clearable
                            show-password>
                    </el-input>
                    <el-button type="primary">登录</el-button>
                </el-form>
                <el-form v-if="login_method === 'is_sms'">
                    <el-input
                            placeholder="手机号"
                            prefix-icon="el-icon-phone-outline"
                            v-model="mobile"
                            clearable
                            @blur="check_mobile">
                    </el-input>
                    <el-input
                            placeholder="验证码"
                            prefix-icon="el-icon-chat-line-round"
                            v-model="sms"
                            clearable>
                        <template slot="append">
                            <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                        </template>
                    </el-input>
                    <el-button type="primary">登录</el-button>
                </el-form>
                <div class="foot">
                    <span @click="go_register">立即注册</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "Login",
        data() {
            return {
                username: '',
                password: '',
                mobile: '',
                sms: '',
                login_method: 'is_pwd',
                sms_interval: '获取验证码',
                is_send: false,
            }
        },
        methods: {
            close_login() {
                this.$emit('close')
            },
            go_register() {
                this.$emit('go')
            },
            change_login_method(method) {
                this.login_method = method;
            },
            check_mobile() {
                if (!this.mobile) return;
                if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                    this.$message({
                        message: '手机号有误',
                        type: 'warning',
                        duration: 1000,
                        onClose: () => {
                            this.mobile = '';
                        }
                    });
                    return false;
                }
                this.is_send = true;
            },
            send_sms() {

                if (!this.is_send) return;
                this.is_send = false;
                let sms_interval_time = 60;
                this.sms_interval = "发送中...";
                let timer = setInterval(() => {
                    if (sms_interval_time <= 1) {
                        clearInterval(timer);
                        this.sms_interval = "获取验证码";
                        this.is_send = true; // 重新回复点击发送功能的条件
                    } else {
                        sms_interval_time -= 1;
                        this.sms_interval = `${sms_interval_time}秒后再发`;
                    }
                }, 1000);
            }
        }
    }
</script>

<style scoped>
    .login {
        width: 100vw;
        height: 100vh;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 10;
        background-color: rgba(0, 0, 0, 0.3);
    }

    .box {
        width: 400px;
        height: 420px;
        background-color: white;
        border-radius: 10px;
        position: relative;
        top: calc(50vh - 210px);
        left: calc(50vw - 200px);
    }

    .el-icon-close {
        position: absolute;
        font-weight: bold;
        font-size: 20px;
        top: 10px;
        right: 10px;
        cursor: pointer;
    }

    .el-icon-close:hover {
        color: darkred;
    }

    .content {
        position: absolute;
        top: 40px;
        width: 280px;
        left: 60px;
    }

    .nav {
        font-size: 20px;
        height: 38px;
        border-bottom: 2px solid darkgrey;
    }

    .nav > span {
        margin: 0 20px 0 35px;
        color: darkgrey;
        user-select: none;
        cursor: pointer;
        padding-bottom: 10px;
        border-bottom: 2px solid darkgrey;
    }

    .nav > span.active {
        color: black;
        border-bottom: 3px solid black;
        padding-bottom: 9px;
    }

    .el-input, .el-button {
        margin-top: 40px;
    }

    .el-button {
        width: 100%;
        font-size: 18px;
    }

    .foot > span {
        float: right;
        margin-top: 20px;
        color: orange;
        cursor: pointer;
    }

    .sms {
        color: orange;
        cursor: pointer;
        display: inline-block;
        width: 70px;
        text-align: center;
        user-select: none;
    }
</style>

4.3.3 Register.vue

<template>
    <div class="register">
        <div class="box">
            <i class="el-icon-close" @click="close_register"></i>
            <div class="content">
                <div class="nav">
                    <span class="active">新用户注册</span>
                </div>
                <el-form>
                    <el-input
                            placeholder="手机号"
                            prefix-icon="el-icon-phone-outline"
                            v-model="mobile"
                            clearable
                            @blur="check_mobile">
                    </el-input>
                    <el-input
                            placeholder="密码"
                            prefix-icon="el-icon-key"
                            v-model="password"
                            clearable
                            show-password>
                    </el-input>
                    <el-input
                            placeholder="验证码"
                            prefix-icon="el-icon-chat-line-round"
                            v-model="sms"
                            clearable>
                        <template slot="append">
                            <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                        </template>
                    </el-input>
                    <el-button type="primary">注册</el-button>
                </el-form>
                <div class="foot">
                    <span @click="go_login">立即登录</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "Register",
        data() {
            return {
                mobile: '',
                password: '',
                sms: '',
                sms_interval: '获取验证码',
                is_send: false,
            }
        },
        methods: {
            close_register() {
                this.$emit('close', false)
            },
            go_login() {
                this.$emit('go')
            },
            check_mobile() {
                if (!this.mobile) return;
                if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                    this.$message({
                        message: '手机号有误',
                        type: 'warning',
                        duration: 1000,
                        onClose: () => {
                            this.mobile = '';
                        }
                    });
                    return false;
                }
                this.is_send = true;
            },
            send_sms() {
                if (!this.is_send) return;
                this.is_send = false;
                let sms_interval_time = 60;
                this.sms_interval = "发送中...";
                let timer = setInterval(() => {
                    if (sms_interval_time <= 1) {
                        clearInterval(timer);
                        this.sms_interval = "获取验证码";
                        this.is_send = true; // 重新回复点击发送功能的条件
                    } else {
                        sms_interval_time -= 1;
                        this.sms_interval = `${sms_interval_time}秒后再发`;
                    }
                }, 1000);
            }
        }
    }
</script>

<style scoped>
    .register {
        width: 100vw;
        height: 100vh;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 10;
        background-color: rgba(0, 0, 0, 0.3);
    }

    .box {
        width: 400px;
        height: 480px;
        background-color: white;
        border-radius: 10px;
        position: relative;
        top: calc(50vh - 240px);
        left: calc(50vw - 200px);
    }

    .el-icon-close {
        position: absolute;
        font-weight: bold;
        font-size: 20px;
        top: 10px;
        right: 10px;
        cursor: pointer;
    }

    .el-icon-close:hover {
        color: darkred;
    }

    .content {
        position: absolute;
        top: 40px;
        width: 280px;
        left: 60px;
    }

    .nav {
        font-size: 20px;
        height: 38px;
        border-bottom: 2px solid darkgrey;
    }

    .nav > span {
        margin-left: 90px;
        color: darkgrey;
        user-select: none;
        cursor: pointer;
        padding-bottom: 10px;
        border-bottom: 2px solid darkgrey;
    }

    .nav > span.active {
        color: black;
        border-bottom: 3px solid black;
        padding-bottom: 9px;
    }

    .el-input, .el-button {
        margin-top: 40px;
    }

    .el-button {
        width: 100%;
        font-size: 18px;
    }

    .foot > span {
        float: right;
        margin-top: 20px;
        color: orange;
        cursor: pointer;
    }

    .sms {
        color: orange;
        cursor: pointer;
        display: inline-block;
        width: 70px;
        text-align: center;
        user-select: none;
    }
</style>
posted @ 2022-07-11 20:53  马氵寿  阅读(114)  评论(0)    收藏  举报