application.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:flaskbooks 作者: omaralbeik 项目源码 文件源码
def gConnect():

    # Validate state token
    if request.args.get('state') != login_session['state']:
        return h.json_response('Invalid state parameter.', 401)

    # Obtain authorization code
    code = request.data

    # Upgrade the authorization code into a credentials object
    try:
        oaht_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oaht_flow.redirect_uri = 'postmessage'
        credentials = oaht_flow.step2_exchange(code)

    except FlowExchangeError:
        return h.json_response('Failed to upgrade the authorization code.', 401)

    # Check that the access token is valid
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
           %access_token)
    http = httplib2.Http()
    result = json.loads(http.request(url, 'GET')[1].decode())

    # If there was an error in the access token info, abort.
    error = result.get('error')
    if error:
        return h.json_response(error, 500)

    gplus_id = credentials.id_token['sub']

    # Verify that the access token is used for the intended user.
    if result['user_id'] != gplus_id:
        return h.json_response("Token's user ID doesn't match given user ID.", 401)

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        return h.json_response("Token's client ID does not match app's.", 401)

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')

    if stored_access_token is not None and gplus_id == stored_gplus_id:
        return h.json_response('Current user is already connected.', 200)

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    # Store the access token and user data in the session for later use.
    h.save_current_user_info(credentials, data)

    user = dbh.create_or_update_current_user_from_login_session()
    if user:
        return h.redirect_books()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号