Flask接入第三方(Facebook)登录

前端需要登录的页面添加按钮html

<a href="javascript:;" id="fb_login">facebook</a>

 

前端需要登录的页面添加以下js

<script>
        window.fbAsyncInit = function () {
            FB.init({
                appId: '{Facebook申请的appid}',
                cookie: true,
                xfbml: true,
                version: '{FacebookSDK版本}'
            });

            FB.AppEvents.logPageView();

        };

        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {
                return;
            }
            js = d.createElement(s);
            js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

    </script>
        <script>
        $("#fb_login").click(function () {
            FB.login(function (response) {
                statusChangeCallback(response);  //登录回调函数
            }, {scope: 'public_profile,email'});  //需要获取的信息scope
        });

        var statusChangeCallback = function (response) {
            if (response.status === 'connected') {
                var accessToken = response.authResponse.accessToken; //取得 accessToken

                FB.api('/me?fields=name,email', function (response) { // /me为API指定的调用方法,用于获取登陆用户相关信息
                    if (response.email != null) {
                        $.ajax({
                            url: "{{ url_for('mall.fb_login') }}",
                            data: {
                                fb_status: 'connected',
                                nickname: response.name,
                                fb_email: response.email,
                                fb_token: accessToken,
                                userType: 'Facebook'
                            },
                            dataType: "json",
                            type: "post",
                            success: function (data) {
                                if (data.code === 200) {
                                    window.location.reload(true);
                                }
                            },
                            error: function (data) {
                                if (data.code === 400){
                                    alert(data.msg);
                                    window.location.reload(true);
                                }
                            }
                        });
                    } else {
                        alert("请同意授权!");
                    }
                });
            }
        };

    </script>

 

后端接收处理

@mall_bp.route('/fb_login', methods=['POST'])
def fb_login():
    token = session.get('token')
    if token:
        return redirect(url_for('mall.index'))
    next_url = request.values.get('next', url_for('mall.index'))
    fb_status = request.form.get('fb_status')
    if fb_status == 'not_authorized':
        flash('您必须授权才能登录!')
        return redirect(url_for('mall.login'))
    elif fb_status == 'connected':
        fb_email = request.form.get('fb_email')
        # 验证第三方token是否正确
        fb_token = request.form.get('fb_token')
        fb_check_url = 'https://graph.facebook.com/debug_token?access_token=【FACEBOOK申请的appid】%7Ca56e2a174b69202ebfa04aa62663fb34&input_token=' + fb_token
        response = requests.get(url=fb_check_url)
        data = response.json().get('data')

        if fb_email and data['is_valid']:
            user_obj = User.query.filter_by(bind_facebook=fb_email).first()
            if user_obj is None:
                email = fb_email
                try:
                    user_obj = User()
                    user_obj.email = email
                    user_obj.bind_facebook = email
                    user_obj.user_login_type = 'Facebook'
                    db.session.add(user_obj)
                    db.session.commit()
                except Exception as e:
                    Config.logger.info('注册失败—>%s' % e)
                    flash('服务器繁忙,请稍后再试!')
                    print(e)
                    return redirect(url_for('mall.index'))
            user_obj = User.query.filter_by(bind_facebook=fb_email).first()
            session['uid'] = user_obj.id
            session['email'] = user_obj.email
            # 生成token
            token = uuid.uuid4().hex + str(round(time() * 1000))
            session['token'] = token
            # 创建集合
            cache_set_value = {token}
            # redis保存token
            cache.set(str(user_obj.id), cache_set_value, timeout=5120)
            send_email_obj = SendEmail.query.filter_by(use_type='REGISTER').first()
            send_email(user_obj.id, send_email_obj.sender, send_email_obj.subject, user_obj.email, '/foreground/accounts/verification_email.html')
            flash('Welcome to login!', 'success')
            return jsonify({'code': 200, 'msg': '登录成功'})
        else:
            flash('您必须授权您的邮箱账号')
            return jsonify({'code': 400, 'msg': '登录失败'})

 

posted @ 2021-09-26 12:07  嘆世殘者——華帥  阅读(221)  评论(0编辑  收藏  举报