Exemple #1
0
def login_with_google():
    # STEP 1 - Parse the auth code
    auth_code = request.json.get('auth_code')

    print("Step 1 - Complete, received auth code %s" % auth_code)
    # STEP 2 - Exchange for a token

    try:
        oauth_flow = flow_from_clientsecrets(filename='client_secret.json',
                                             scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(auth_code)

    except FlowExchangeError:
        print(FlowExchangeError.__dict__)
        return (jsonify({'data': 'Failed to upgrade the authorization code.',
                         'error': 401}), 401)

    access_token = credentials.access_token
    url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={}'.format(
        access_token)
    http = httplib2.Http()
    result = json.loads(http.request(url, 'GET')[1])

    if result.get('error'):
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(json.dumps(
            "Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(json.dumps(
            "Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
        
    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')

    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps(
            'Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    print("Step 2 Complete! Access Token : %s " % credentials.access_token)

    # STEP 3 - Find User or make a new one
    http = httplib2.Http()
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    data = answer.json()

    name = data['name']
    picture = data['picture']
    email = data['email']

    user = session.query(User).filter_by(email=email).first()
    if not user:
        user = User(name=name, email=email)
        session.add(user)
        session.commit()

    # STEP 4 - Make token
    token = user.generate_auth_token(600)

    # STEP 5 - Send back token to the client
    return jsonify({'token': token.decode('ascii')})