微博三方登录的流程

第三方微博登录流程图

第三方登录流程图

后端使用微博完成三方登录代码展示:

  1. 配置
# setting配置文件里面配置  微博登录用到的相关配置
	CLIENT_ID = "2775107052"	# 申请应用时分配的AppKey
	CLIENT_SECRET = "718b38b04fc387700cc1595b30875b19"	# 	申请应用时分配的AppSecret
	GRANT_TYPE = "authorization_code"	# 	请求的类型,填写authorization_code
	REDIRECT_URL = "http://127.0.0.1:8080/weibo"	# 回调地址,需需与注册应用里的回调地址一致
  1. 功能实现
import requests
from flask import Blueprint, current_app
from flask_restful import Api, Resource, reqparse
from werkzeug.security import check_password_hash

from common.models import db
from common.models.user import OAuthUserModel, UserModel
from common.utils.my_output_json import custom_output_json
from common.utils.jwt_util import _generate_token

oauth_user_bp = Blueprint("oauth_user_bp", __name__, url_prefix="/oauth")
api = Api(oauth_user_bp)

# 统一返回格式
@api.representation("application/json")
def output_json(data, code, headers=None):
    resp = custom_output_json(data, code)
    return resp
 
"""
1. 前端页面点击微博图片, 后端返回给用户一个扫码登录的页面
2. 用户扫码登录, 确认登录后,返回给用户一个:http://127.0.0.1:8080/weibo?code=4a58baf6e6fc28086b1d99f27560b9a7
3. 前端要把url中code的值获取到传递后端, 后端根据code 的值获取微博账号的信息
4. 根据微博账号的信息,判断是否和后台中的账号是否绑定
    1. 绑定直接登录
    2.没有绑定, 返回给前端一个绑定账号的页面,
    3. 用户输入后台的账号信息,进行绑定
5. 返回绑定后的token, 用户信息
"""

class OauthWeiboLogin(Resource):
    def get_weibo_user(self, code):
        data_ = {
            "client_id": current_app.config.get('CLIENT_ID'),
            "client_secret": current_app.config.get('CLIENT_SECRET '),
            "grant_type": current_app.config.get('GRANT_TYPE'),
            "redirect_uri": current_app.config.get('REDIRECT_URL'),
            "code": code,
        }
        base_url = "https://api.weibo.com/oauth2/access_token"
        try:
        	# 获取微博用户信息
            resp = requests.post(url=base_url, data=data_).json()
        except Exception as e:
            return {"message": "获取微博用户信息失败", "code": 400}

        if not resp["access_token"]:
            return {"message": "根据code获取钉钉用户信息失败", "code": 400}
        else:
            user_dict = resp
            return user_dict

    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("code")
        args = parser.parse_args()
        code = args["code"]
        # 根据code获取微博用户信息
        user_dict = self.get_weibo_user(code)
        # 获取微博的access_token 
        access_token = user_dict["access_token"]
        # 根据access_token 判定是否绑定账号
        oauth_user = OAuthUserModel.query.filter_by(oauth_id=access_token, oauth_type="weibo").first()
        if oauth_user:
        	# 查询到用户,已经绑定过,返回绑定成功的用户token 及id
            user = UserModel.query.filter_by(uid=oauth_user.user).first()
            payload = {"uid": user.uid}
            token = _generate_token(payload)
            data_ = {
                "account": user.account,
                "id": user.uid,
                "token": token
            }
            return {"message": "登录成功", "code": 200, "data": data_}
        else:
            return {"message": "用户没有绑定,请先绑定", "code": 500, "uid": access_token}


class WeiboBindUser(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("account")
        parser.add_argument("password")
        parser.add_argument("unid")
        args = parser.parse_args()
        account = args["account"]
        password = args["password"]
        unid = args["unid"]
        # 判断账号是否注册过,没有注册过去注册
        user = UserModel.query.filter_by(account=account).first()
        if not user:
            return {"message": "用户未注册,请先注册", "code": 400}
        else:
        	# 校验密码
            if not check_password_hash(user.password, password):
                return {"message": "密码错误", "code": 400}
            else:
            	# 根据user 查询OAuthUserModel表中的数据, 绑定第三方账号
                oauth_user = OAuthUserModel(oauth_id=unid, user=user.uid, oauth_type="weibo")
                db.session.add(oauth_user)
                db.session.commit()
                # 返回绑定成功的用户token 及id
                payload = {"uid": user.uid}
                token = _generate_token(payload)
                data_ = {
                    "id": user.uid,
                    "account": user.account,
                    "token": token,
                }
                return {"message": "绑定成功", "code": 200, "data": data_}
           
api.add_resource(WeiboBindUser, "/weibo/bind")
api.add_resource(OauthWeiboLogin, "/weibo")

版权声明:本文为weixin_58959719原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。