曝華為 Mate 40 系列將提供新的黃色配色
阿新 • • 發佈:2020-10-12
1.微博回撥介面
1.1 oauth/urls.py 中新增路由
1 2 3 4 |
urlpatterns = [
path( 'weibo/callback/' , views.OauthWeiboCallback.as_view()), #
/ oauth / weibo / callback /
]
|
1.2 oauth/views.py 中新增試圖函式
http://192.168.56.100:8888/oauth/weibo/callback/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
from .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' : '3516473472' ,
'client_secret' : '7862ee35a0dc6f0345d0464dc34f14fc' ,
'grant_type' : 'authorization_code' ,
'code' : code,
'redirect_uri' : 'http://127.0.0.1:8888/oauth/callback/' ,
}
url = 'https://api.weibo.com/oauth2/access_token'
data = requests.post(url = url, data = data).json() # 拿取請求的返回結果
access_token = data.get( 'uid' ) # 獲取到的微博token
weibo_uid = data.get( 'access_token' ) # 獲取到少碼使用者的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. 如果沒繫結, 返回標誌, 讓前端跳轉到繫結頁面
return Response({ 'code' : 0 , 'msg' : '授權成功' , 'data' : { 'type' : '1' ,
'uid' : weibo_uid}})
|