在线聊天室,处理OAuth2授权,没有获取用户邮箱的bug


#1

在下面这段代码中,没有考虑没有获取到用户email的情况。我用自己的GitHub账号试了一下,我的email是保密的,在获取远程应用资源的时候,就没有获取到email,从而报错了。

@oauth_bp.route('/callback/<provider_name>')
def oauth_callback(provider_name):
    if provider_name not in providers.keys():
        abort(404)

    provider = providers[provider_name]
    response = provider.authorized_response()

    if response is not None:
        if provider_name == 'twitter':
            access_token = response.get('oauth_token'), response.get('oauth_token_secret')
        else:
            access_token = response.get('access_token')
    else:
        access_token = None

    if access_token is None:
        flash('Access denied, please try again.')
        return redirect(url_for('auth.login'))

    username, website, github, email, bio = get_social_profile(provider, access_token)

    user = User.query.filter_by(email=email).first()
    if user is None:
        user = User(email=email, nickname=username, website=website,
                    github=github, bio=bio)
        db.session.add(user)
        db.session.commit()
        login_user(user, remember=True)
        return redirect(url_for('chat.profile'))
    login_user(user, remember=True)
    return redirect(url_for('chat.home'))


#2

感谢反馈!之前有读者反馈过这个 Bug,还没来得及修复。写的时候我以为 GitHub 固定会返回邮箱,没考虑到邮箱保密的问题。:sweat_smile: