1. 程式人生 > 實用技巧 >應用(1)——同一頁面調取data和示例:資料儲存呼叫

應用(1)——同一頁面調取data和示例:資料儲存呼叫

1 微博三方登入

1.1 圖解微博三方登入

1.2 具體流程

1.2.1 前端獲取認證code

1)在Vue頁面載入時 動態傳送請求獲取微博授權url

2)django收到請求的url後,通過微博 應用ID(client_id)和回撥地址(redirect_uri) 動態 生成授

權url返回給Vue

3)當用戶點選上面的url進行掃碼,授權成功會 跳轉我們的回撥介面並附加code引數

4)Vue獲取到微博返回的code後,會 將code傳送給django後端 (上面的redirect_uri)

1.2.2 獲取微博 access_token

後端獲取code後,結合client_id、client_secret、redirect_uri引數進行傳遞,獲取微博 access_token

1.2.3 獲取微博使用者基本資訊並儲存到資料庫

使用獲得的access_token呼叫獲取使用者基本資訊的介面, 獲取使用者第三方平臺的基本資訊
使用者基本資訊 儲存到資料庫,然後關聯本地使用者 ,然後將使用者資訊返回給前端

1.2.4 生成token給Vue

django後端藉助微博認證成功後,可以 使用JWT生成token ,返回給Vue
Vue將token儲存到localStorage中 ,以便使用者訪問其他頁面進行身份驗證

1.3 第三方登入與本地登入的關係

1.3.1 本地未登入,第一次登入第三方

此時相當於註冊,直接把第三方資訊拉取來並註冊成本地使用者就可以了,並建立本地使用者與第三方使用者的繫結關係。

1)跳轉頁面

2)使用者表添加了資訊

3)三方表增添了資料

1.3.2 本地登入,並繫結第三方

此時使用者已註冊,獲取到uid後直接找出對應的本地使用者即可

  • 只生成三方表資料,繫結使用者id

1.3.3 本地未登入,再次登入第三方

這個只需要通過微博code查詢使用者資訊和三方表是否有值,成功就直接跳轉登入成功

1.4 .oauth認證原理

  • OAuth是一個開放標準,允許使用者讓第三方應用訪問該使用者在某一網站上儲存的私密的資源,而無需將使用者名稱和密碼提供給第三方應用。
  • OAuth允許使用者提供一個令牌,而不是使用者名稱和密碼來訪問他們存放在特定服務提供者的資料。
  • 這個code如果能出三方換取到資料就證明這個使用者是三方真實的使用者。

1.5 使用三方登入的原因

  • 服務方希望使用者註冊, 而使用者懶得填註冊時的各種資訊(主要是為了保證使用者的唯一性,各種使用者名稱已佔用,密碼格式限制)。
  • 而像微信, QQ, 微博等幾乎每個人都會安裝的應用中使用者肯定會在其中某一個應用中已經註冊過,證明該使用者在已經註冊的應用中的唯一性。
  • 第三方登入的實質就是在授權時獲得第三方應用提供的代表了使用者在第三方應用中的唯一性的uid,並將uid儲存在第三方服務控制的本地儲存。

2 三方登入準備工作

2.1 OAuth2.0授權認證

  • OAuth2/authorize文件瞭解

  • 我的應用中獲取應用資訊找到
App Key:1685526621
App Secret:71a62fe7cb582143aaf8e05dd4a0fc0c

2.2 路由拼接

# 後端路由拼接示例
https://api.weibo.com/oauth2/authorize?client_id=1685526621&redirect_uri=http://127.0.0.1:8888/callback

2.3 應用資訊授權設定

  授權回撥頁面:http://127.0.0.1:8888/oauth/callback/

取消授權回撥頁:http://127.0.0.1:8888/oauth/callback/

2.4 應用高階設定

3 三方登入實戰

3.1 生成微博授權URL介面

3.1.1 在apps資料夾下建立應用oauth
cd syl/apps
python ../manage.py startapp oauth		
3.1.2 新增子路由
from django.urls import path
from . import views
urlpatterns = [
    
]
3.1.3 在syl/settings.py中註冊應用
INSTALLED_APPS = [
    'oauth.apps.OauthConfig',
]
3.1.4 在syl/urls.py主路由中新增
urlpatterns = [
    path('oauth/', include('oauth.urls'))
]

3.2 生成微博授權URL介面

3.2.1 新增子路由oauth/urls.py
# -*- coding: utf-8 -*-
from django.urls import path
from . import views
urlpatterns = [
    path('weibo/', views.WeiboUrl.as_view()),   # /oauth/weibo/ 返回微博登入地址
]
3.2.2 sul/settings.py中配微博地址
# 微博
WEIBO_CLIENT_ID = '1685526621'
WEIBO_REDIRECT_URL = 'http://127.0.0.1:8888/oauth/callback/'
WEIBO_CLIENT_SECRET = '71a62fe7cb582143aaf8e05dd4a0fc0c'
3.2.3 檢視函式oauth/views.py
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from urllib.parse import urlencode

# 生成前端跳轉到微博掃碼頁面的url

from syl import settings
from user.models import User


class WeiboUrl(APIView):
    '''
        生成微博的登陸頁面路由地址
        https://api.weibo.com/oauth2/authorize?         # 微博oauth認證地址
        client_id=4152203033&                           # 註冊開發者id
        response_type=code& redirect_uri=http:/``/127.0.0.1:8888/oauth/callback/  # 獲取code後將code回 調給後端地址
    '''

    # 自定義許可權類
    permission_classes = (AllowAny,)

    def post(self, request):
        url = 'https://api.weibo.com/oauth2/authorize?'     # 微博授權的 url地址
        data = {
            'client_id': settings.WEIBO_CLIENT_ID,                 # settings.WEIBO_CLIENT_ID
            'response_type': 'code',
            'redirect_uri': settings.WEIBO_REDIRECT_URL,    # VUE的回撥,微博後臺授權的回撥地址
        }
        print(urlencode(data))
        weibo_url = url + urlencode(data)

        # https://api.weibo.com/oauth2/authorize? client_id=4152203033&response_type=code&redirect_uri=http://127.0.0.1:8000/api/we ibo_back/

        # return Response({'weibo_url': weibo_url})
        return Response({'code': '0', 'msg': '成功', 'data': {'url': weibo_url}})
3.2.4 測試生成微博售前URL介面

1)測試結果

2)測試網頁

  • 利用獲取到的url,在瀏覽器中開啟
https://api.weibo.com/oauth2/authorize?client_id=1685526621&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A8888%2Foauth%2Fcallback%2F

3.3 Vue獲取微博授權URL

3.3.1 在 components\common\lab_header.vue 中寫oauth動態獲取微博授權URL
<tamplate>
	<div>
         <a @click="oauth"><i class="fa fa-weibo"></i></a>
    </div>
</tamplate>

<script>
import { oauth_post } from '../axios_api/api'
export default{
      methods: {
            // 獲取微博登入地址
            oauth() {
              // 從後端獲取 微博登入地址
              oauth_post().then((resp) => {
                console.log(resp)
                //{'code': '0', 'msg': '成功', 'data': {'url': url}}
                let url = resp.data.url;
                this.weibo_url = url;
              })
    },
}	
</script>
3.3.2 在vue的mounted函式中呼叫獲取微博授權url函式
mounted() { 
	this.oauth() 
},
3.3.3 點選"登入"彈出的form表單中加入url
<form 
      action="/login" 
      method="post" 
> 
    <div class="form-group widget-signin"> 
        <a :href="weibo_url"><i class="fa fa-weibo"></i></a> 
    </div> 
</form>

3.4 微博回撥介面

3.4.1 oauth/urls.py
# -*- coding: utf-8 -*-
from django.urls import path
from . import views
urlpatterns = [
    path('weibo/callback/', views.OauthWeiboCallback.as_view()),    # /oauth/weibo/callback/查詢三方表,有繫結資訊返回登入成功,沒有繫結資訊返還uid
]
3.4.2 oauth/models.py
from django.db import models

# Create your models here.
# 把三方的使用者資訊,和本地的使用者資訊進行繫結
#
class OauthUser(models.Model):
    OAUTHTYPE = (
        ('1', 'weibo'),
        ('2', 'weixin'),
    )

    uid = models.CharField('三方使用者id', max_length=64)     # 三方使用者id
    user = models.ForeignKey('user.User', on_delete=models.CASCADE)     # 本地使用者外來鍵,關聯User表
    oauth_type = models.CharField('認證型別', max_length=10, choices=OAUTHTYPE)         # 1,2 ...

# 遷移資料庫
# python manage.py makemigrations
# python manage.py migrate
3.4.3 oauth/views.py
from oath.models import OauthUser
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
from user.utils import jwt_response_payload_handler

# 通過vue前端傳入的code,微博身份驗證

class OauthWeiboCallback(APIView):

    # 自定義許可權類
    permission_classes = (AllowAny,)

    def post(self, request):
        # 接收vue端傳過來的code(微博的使用者code)
        # 1.使用微博使用者code+微博開發者賬號資訊換取微博的認證access_token
        code = request.data.get('code')
        data = {
            'client_id': settings.WEIBO_CLIENT_ID,
            'client_secret': settings.WEIBO_CLIENT_SECRET,
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': settings.WEIBO_REDIRECT_URL,
        }
        url = 'https://api.weibo.com/oauth2/access_token'
        data = requests.post(url=url, data=data).json()
        print(data)
        # 拿取請求的返回結果
        # access_token = data.get('access_token')
        # 獲取到的微博token
        weibo_uid = data.get('uid')
        # 獲取到掃碼使用者的id
        # 2. 根據uid 查詢繫結情況
        try:
            oauth_user = OauthUser.objects.get(uid=weibo_uid, oauth_type='1')
        except Exception as e:
            oauth_user = None           # 返回動作, 登入成功/需要繫結使用者 type 0 登入成功, 1, 授權成功, 需要繫結
        if oauth_user:
            # 4. 如果綁定了, 返回token, 登入成功
            user = oauth_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            # jwt_response_payload_handler為user模組定義的jwt返回的資訊
            data = jwt_response_payload_handler(token, user)
            data['type'] = '0'          # 指定為登入成功
            return Response({'code': 0, 'msg': '登入成功', 'data': data})
        else:
            # 5. 如果沒繫結, 返回標誌, 讓前端跳轉到繫結頁面
            print(weibo_uid)
            return Response({'code': 0, 'msg': '授權成功', 'data': {'type': '1', 'uid': weibo_uid}})

前端效果

前端網頁跳轉

3.5 Vue微博回撥空頁面

<template>
  <div>
    <div v-show='visiable'>
      繫結使用者
      使用者名稱: <input
      type="text"
      v-model="username"
      @blur="check_username"
    >
      <span>{{username_message}}</span>
      密碼: <input
      type="password"
      v-model="password"
    >
      <button @click="bindUser">繫結</button>
    </div>
  </div>
</template>
<script>
  import { oauth_callback_post, oauth_binduser_post, user_count } from './axios_api/api'
  export default {
    data() {
      return {
        visiable: false, // 繫結使用者視窗
        uid: '', // weibo_uid
        username: '',
        password: '',
        username_message: '',
        username_error: false
      }
    },
    mounted() {
      this.getCode()
    },
    methods: {
      // 2.判斷使用者名稱是否合法
      check_username() {
        console.log('判斷使用者名稱')
        console.log(this.username == '')
        var reg = new RegExp(/^[a-zA-Z0-9_-]{3,16}$/); //字串正則表示式 4到14位(字母,數字,下劃線,減號)
        if (this.username == '') {
          this.username_message = '使用者名稱不能為空'
          this.username_error = true
          return false
        }
        if (!reg.test(this.username)) {
          this.username_message = '使用者名稱格式不正確'
          this.username_error = true
          return false
        } else {
          // 去後端檢查使用者名稱使用數量
          user_count({ type: 'username', data: this.username }).then((res) => {
            console.log(res)
            if (res.data.count > 0) {
              this.username_message = '使用者名稱已存在, 請輸入密碼'
              this.username_error = false
            } else {
              this.username_message = '使用者名稱可用, 將建立新使用者,請輸入密碼'
              this.username_error = false
            }
          })
        }
      },
      // 1.1當頁面被掛載時就自動呼叫,通過url獲取微博的code,傳送code給django端
      // 1.2 如果已經繫結,返回 type='0',登入成功,直接跳轉到首頁
      // 1.3 如果未繫結,返回type='1',顯示繫結使用者的頁面
      getCode() {
        // 獲取url中的code 資訊,code資訊是微博端返回的
        // 當前url 是  http://127.0.0.1:8888/oauth/callback/?code=424db5805abb50ed5e0ba97325f54d0f
        let code = this.$route.query.code
        console.log(this.$route.query)
        // 給後端傳送code
        let params = { code: code }
        oauth_callback_post(params).then((resp) => {
          console.log(resp)
          // code: 0
          // msg: "授權成功"
          // data: {type: "1", uid: "7410919278"}
          // 如果type=0代表以前已經繫結過,直接登入成功
          if (resp.data.type == '0') {
            // code: 0
            // msg: "登入成功"
            // data: {
            // authenticated: "true"
            // email: ""
            // id: 1
            // name: "admin"
            // role: null
            // token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTk3OTAwNTcyLCJlbWFpbCI6IiIsIm9yaWdfaWF0IjoxNTk3ODE0MTcyfQ.aQT7GSR_xQBPMlB4_k8-zTHnx0ow3OC2KHa3C8MgilY"
            // type: "0"
            // username: "admin"}
            let res = resp.data
            localStorage.setItem('username', res.username)
            // localStorage.setItem('img', res.img)
            localStorage.setItem('token', res.token)
            localStorage.setItem('uid', res.id)
            this.login_username = res.username
            this.opened = false
            // alert(res.message)
            this.$router.push('/')  // 跳轉到首頁

          }
          // 如果使用者·沒有繫結過,顯示繫結頁面
          if (resp.data.type == '1') {
            this.visiable = true
            this.uid = resp.data.uid
          }
        })
      },

      // 3.繫結微博使用者與實驗樓本地使用者
      bindUser() {
        if(this.username_error){
          return
        }
        // 傳送  使用者名稱, 密碼, weibo_uid 到後端介面, 進行繫結
        let params = { username: this.username, password: this.password, weibo_uid: this.uid }
        oauth_binduser_post(params).then((resp) => {
          console.log(resp)
          let res = resp.data
          localStorage.setItem('username', res.username)
          // localStorage.setItem('img', res.img)
          localStorage.setItem('token', res.token)
          localStorage.setItem('uid', res.id)
          this.login_username = res.username
          this.opened = false
          // alert(res.message)
          this.$router.push('/')
        })
      }
    }
  }
</script>

3.6 微博繫結使用者介面

3.6.1 oauth/urls.py
urlpatterns = [ 
    path('weibo/binduser/', views.OauthWeiboBindUser.as_view()), 	# /oauth/weibo/callbac
]
3.6.2 oauth/views.py
class OauthWeiboBindUser(APIView):

    permission_classes = (AllowAny,)

    def post(self, request):
        # 繫結使用者, 1. 已註冊使用者, 2. 未註冊使用者
        # 1.1 獲取使用者名稱, 密碼, weibo_uid
        username = request.data.get('username')
        password = request.data.get('password')
        weibo_uid = request.data.get('weibo_uid')
        if not all([username, password, weibo_uid]):
            return Response({'code': 999, 'msg': '引數不全'})
            # 0.判斷是否存在此使用者
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            user = None
        # 1. 已註冊使用者
        if user:
            # 1.2 , 如果存在就驗證 密碼, 驗證通過,就繫結, 返回token,登入成功
            if user.check_password(password):
                ou = OauthUser(uid=weibo_uid, user=user, oauth_type='1')
                ou.save()
                payload = jwt_payload_handler(user)
                # 通過user物件獲取到jwt的 payload資訊
                token = jwt_encode_handler(payload)
                # 生成token
                data = jwt_response_payload_handler(token, user)
                data['type'] = '0'
                # 指定為登入成功
                return Response({'code': 0, 'msg': '登入成功', 'data': data})
            else:
                return Response({'code': 999, 'msg': '密碼錯誤'})
        else:
            # 2. 未註冊使用者
            # 2.1 生成新使用者, 設定使用者名稱密碼, 儲存, 然後繫結, 返回token, 登入成功
            user = User(username=username)
            user.set_password(password)
            user.save()
            ou = OauthUser(uid=weibo_uid, user=user, oauth_type='1')
            ou.save()
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            data = jwt_response_payload_handler(token, user)
            data['type'] = '0'

            # 指定為登入成功
            return Response({'code': 0, 'msg': '登入成功', 'data': data})

3.7 Vue繫結使用者頁面

  • 同回撥空頁面

·