flask 使用三方登录《微博》

解释全在注释里

# 三方登录
@user_bp.route('/weibo')
def weibo_login():
    # 微博唯一标识
    clientid = "3674019597"
    # 回调地址
    url = "http://127.0.0.1:8000/user/weiboCallback/"

    reUrl = "https://api.weibo.com/oauth2/authorize?client_id=" + clientid + "&redirect_uri=" + url + "&response_type=code"
    return jsonify({'code': 200, 'url': reUrl})


# 回调接口
@user_bp.route('/user/weiboCallback/')
def weiboCallback():
    code = request.args.get('code')
    geturl = "https://api.weibo.com/oauth2/access_token"
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post(geturl, data=data)
    # 获取token uid
    reponse = res.json()
    try:
        token = reponse['access_token']
        uid = reponse['uid']
    except Exception as e:
        print(e)
        token = ''
        uid = ''

    # 通过 uid去三方登录表中查询是否存在
    user_info = ThreeLogin.query.filter_by(uid=uid).first()

    # 如果存在用userid生成token,redirect到vue页面
    if user_info:
        # 生成token
        payload = {
            'id': user_info.user_id,
            'exp': time.time() + 86400
        }
        token = myjwt.jwt_encode(payload)
        return redirect("http://localhost:8080/is?token=" + token + "&uid=" + str(user_info.user_id))
    else:
        return redirect("http://localhost:8080/bindMobile?token=" + token + "&uid=" + uid)


# 绑定手机号
@user_bp.route('/bindMobile', methods=['POST'])
def bindMobile():
    # 获取参数
    data = user.bindMobile()
    # 查看用户表中手机号是否存在
    user_info = User.query.filter_by(mobile=data['mobile']).first()
    if user_info:
        # 生成token
        payload = {
            'name': user_info.name,
            'mobile': user_info.mobile,
            'id': user_info.id,
            'exp': time.time() + 86400
        }
    else:
        db.session.add(User(
            name='鹿友' + data['mobile'][-4:],
            mobile=data['mobile']
        ))
        db.session.commit()
        # 生成token
        user_info = User.query.filter_by(user_id=data['uid']).first()
        payload = {
            'name': user_info.name,
            'mobile': user_info.mobile,
            'id': user_info.id,
            'exp': time.time() + 86400
        }
    token = myjwt.jwt_encode(payload)

    # 写入三方登录表
    db.session.add(ThreeLogin(
        token=data['token'],
        user_id=user_info.id,
        uid=data['uid'],
        three_name='weibo',
    ))
    db.session.commit()

    return jsonify({'code': 200, 'msg': '登录成功', 'token': token, 'userid': user_info.id})

                                                                                                                  就这么多了没了 

flask 使用三方登录《微博》_第1张图片

 

你可能感兴趣的:(flask,python,后端)