2020/11/05:三方登录

2020/11/05:三方登录

思路整理:

在这里插入图片描述

  • 创建第三方app:在这里插入图片描述

  • 创建表:

from django.db import models
from users.models import User


# Create your models here.

class OauthUser(models.Model):
    OAUTHTYPE = (
        ('1', 'weibo'),
        ('2', 'weixin'),
    )
    uid = models.CharField('三方用户ID', max_length=64)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    oauth_type = models.CharField('认证类型', max_length=10, choices=OAUTHTYPE)

  • 拼接url:

# 前端请求,将微博的url进行拼接
class WeiBoView(APIView):
    def post(self, request):
        # 微博授权的url地址
        url = 'https://api.weibo.com/oauth2/authorize?'
        data = {
            'client_id': "977471988",
            'response_type': 'code',
            # vue的回调地址
            'redirect_uri': 'http://127.0.0.1:8888/oauth/callback',
        }
        weibo_url = url + urlencode(data)
        return Response({
            'code': 200,
            'msg': '成功!',
            'data': {
                'url': weibo_url
            }
        })

  • 回调:

# 回调
class WeiBoCallback(APIView):
    def post(self, request):
        code = request.data.get('code')
        print(code, "-------------------------post!")
        data = {
            'client_id': '977471988',
            'client_secret': 'e31ef496080542c04bdf5a7ea92c2f6b',
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': 'http://127.0.0.1:8888/oauth/callback',
        }
        url = 'https://api.weibo.com/oauth2/access_token'
        # 需要一个http请求微博准备信息--------requests
        weibo_data = requests.post(url=url, data=data)
        print(type(weibo_data))
        json_weibo_data = weibo_data.json()
        print(json_weibo_data)
        uid = json_weibo_data.get('uid')
        if uid:
            try:
                oauth_obj = OauthUser.objects.get(uid=uid)
                return Response({
                    'code': 200,
                    'msg': "授权成功!",
                    'data': {
                        "uid": uid,
                        'type': "0",
                        'username': oauth_obj.username,
                        'token': create_token(oauth_obj.user)
                    }
                })
            except Exception as e:
                return Response({
                    'code': 200,
                    'msg': '授权成功!',
                    'data': {
                        'type': '1',
                        'uid': uid,
                    }
                })
        else:
            return Response({
                'code': 500,
                'msg': '获取失败!',
            })

  • 绑定用户:

# 绑定用户
class WeiBoBindUser(APIView):
    def post(self, request):
        oauth_type = 1
        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': 500,
                'msg': '参数不完整!',
            })
        # 判断username是否存在
        try:
            # 已注册用户
            user_obj = User.objects.get(username=username)
            oauth_info = OauthUser.objects.get(
                uid=weibo_uid,
                oauth_type=oauth_type,
                user=user_obj,
            )
            data = {
                'authenticated': True,
                'id': user_obj.id,
                'role': None,
                'name': user_obj.nick_name,
                'username': username,
                'email': user_obj.email,
                'token': create_token(user_obj),
                'type': 0
            }
            return Response({
                'code': 200,
                'msg': "登陆成功!",
                'data': data
            })
        except Exception as e:
            # 未注册用户,先注册,再登录
            password = make_password(password)
            user_obj = User.objects.create(
                username=username,
                password=password
            )
            oauth_info = OauthUser.objects.create(
                uid=weibo_uid,
                oauth_type=oauth_type,
                user=user_obj,
            )
            data = {
                'authenticated': True,
                'id': user_obj.id,
                'role': None,
                'name': user_obj.nick_name,
                'username': username,
                'email': user_obj.email,
                'token': create_token(user_obj),
                'type': 0
            }
            return Response({
                'code': 200,
                'msg': "登陆成功!",
                'data': data
            })

  • urls.py配置路由:

from oauthapp.views import *
from django.urls import path, re_path, include

urlpatterns = [
    path('weibo/', WeiBoView.as_view()),

    path('weibo/callback/', WeiBoCallback.as_view()),

    path('weibo/binduser/', WeiBoBindUser.as_view()),
]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值