03-02 多方式登录

一. 后台

1. 插件

pip install djangorestframework-jwt

2. urls.py

router = SimpleRouter()
router.register('', views.LoginAPIView, 'login')

urlpatterns = [
    path('', include(router.urls)),
]

3. dev.py

import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
}

4. views.py

from rest_framework.viewsets import ViewSet  # ViewSetMixin+APIView
from rest_framework.decorators import action

import utils
from . import serializer


class LoginAPIView(ViewSet):
    authentication_classes = ()
    permission_classes = ()
    
    @action(methods=('post',), detail=False)
    def login(self, request, *args, **kwargs):
        ser = serializer.UserModelSerilaizer(data=request.data)
        ser.is_valid(raise_exception=True)

        token = ser.context['token']
        user = ser.context['user']
        return utils.APIResponse(token=token, username=user.username)

5. serializers.py

import re
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from . import models


class UserModelSerilaizer(serializers.ModelSerializer):
    # 提示: 因为继承了AbstractUser的表源码中username字段指定的是unique字段. 在视图中进行序列化data=request.data时, 如果不重定义
    # 在序列化中就会被认为时存储数据, 因为data本质就是存储数据, 而我们这里因该重定义该字段, 去除这种影响
    username = serializers.CharField()

    class Meta:
        model = models.User
        fields = ('username', 'password', 'id')

    def _verify_username(self, username):
        """校验用户多方式登录用户名"""
        if re.search(r'^1[3-9][0-9]{9}$', username):
            user = models.User.objects.filter(telephone=username).first()
        elif re.search(r'^.+@.+\.com$', username):
            user = models.User.objects.filter(email=username).first()
        else:
            user = models.User.objects.filter(username=username).first()

        if user:
            return user
        raise ValidationError('用户名不存在!')

    def _verify_password(self, user, password):
        """校验用户密码"""
        is_correct = user.check_password(raw_password=password)
        if not is_correct:
            raise ValidationError("密码不正确!")

    def _sign_token(self, user):
        """签发token"""
        import jwt
        import datetime
        from django.conf import settings
        headers = {
            'typ': 'jwt',
            'alg': 'HS256',
        }
        payload = {
            'user_id': user.pk,
            'username': user.username,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=7),
        }
        # 盐
        slat = settings.SECRET_KEY
        token = jwt.encode(payload, key=slat, headers=headers)
        return token

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        # 校验用户多方式登录用户名
        user = self._verify_username(username)
        # 校验用户密码
        self._verify_password(user, password)
        # 签发token
        token = self._sign_token(user)

        self.context['token'] = token
        self.context['user'] = user
        return attrs

一. 前台(cookies修改页面登陆状态)

1. 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" @click="login">登录</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);
            },
            login() {
                if (this.username && this.password) {
                    this.$axios.post(this.$settings.base_url + '/user/login/', {
                        'username': this.username,
                        'password': this.password,
                    }).then(response => {
                        console.log(response.data);
                        // 把用户信息保存到cookie中
                        // this.$cookies.set('key','value','过期时间,按s计')
                        this.$cookies.set('token', response.data.token, '7d');
                        this.$cookies.set('username', response.data.username, '7d');

                        // 关闭登录窗口(子传父)
                        // 给父组件,Head传递一个事件,让它从cookie中取出token和username
                        this.$emit('close');
                        this.$emit('loginSuccess');
                    }).catch(error => {
                        console.log(error.response);
                    })
                } else {
                    this.$message({
                        message: '用户名或密码输入不能为空!',
                        type: 'warning',
                    });
                }
            }
        }
    }
</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>

2. 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 v-if="!username">
                    <span @click="put_login">登录</span>
                    <span class="line">|</span>
                    <span @click="put_register">注册</span>
                </div>
                <div v-else>
                    <span>{{username}}</span>
                    <span class="line">|</span>
                    <span @click="logout">注销</span>
                </div>
                <Login v-if="is_login" @close="close_login" @go="put_register" @loginSuccess="loginSuccess"/>
                <Register v-if="is_register" @close="close_register" @go="put_login"/>
            </div>
        </div>
    </div>

</template>

<script>
    import Login from './Login'
    import Register from './Register'

    export default {
        name: "Header",
        data() {
            return {
                url_path: sessionStorage.url_path || '/',
                is_login: false,
                is_register: false,
                token: '',
                username: ''
            }
        },
        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;
            },
            loginSuccess() {
                this.username = this.$cookies.get('username');
                this.token = this.$cookies.get('token');
            },
            logout() {
                // 把两个变量值为空
                this.username = '';
                this.token = '';

                // 清除cookie
                this.$cookies.remove('username');
                this.$cookies.remove('token');
            }
        },
        created() {
            sessionStorage.url_path = this.$route.path;
            this.url_path = this.$route.path;

            // 当页面一创建,我就去cookie中取token和username
            this.username = this.$cookies.get('username');
            this.token = this.$cookies.get('token');
        },
        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>
posted @ 2020-07-23 16:52  给你加马桶唱疏通  阅读(142)  评论(0编辑  收藏  举报