Example #1
0
def gconnect():

    # validate the STATE
    if request.args.get('state') != login_session['state']:
        response = create_json_response('Invalid state parameter.', 401)
        return response

    # Get one-time code from the request
    auth_code = request.data

    # exchange access token with the one-time code
    credentials = client.credentials_from_clientsecrets_and_code(
        'client_secrets.json', [
            'https://www.googleapis.com/auth/userinfo.profile', 'profile',
            'email'
        ], auth_code)

    # check that the access is valid
    token_status = valid_token(credentials)

    # if access token not valid, abort
    if token_status['valid'] == False:
        response = create_json_response(token_status['error_message'],
                                        token_status['code'])
        return response

    # check whether the user is already connected to Google
    if is_user_logged_in_google(login_session, credentials.id_token['sub']):
        response = create_json_response('Current user is already connected',
                                        200)
        return response

    # store credentials in the session for later use
    login_session['credentials'] = client.OAuth2Credentials.to_json(
        credentials)
    login_session['google_id'] = credentials.id_token['sub']

    # use access token to get user profile
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    user_info = answer.json()

    # check whether the user exists in the DB. If not, create new user.
    user = User.by_email(email=user_info['email'])
    if user:
        user_id = user.id
    else:
        # create new user and get the user_id
        new_user = User.new(username=user_info['name'],
                            email=user_info['email'],
                            picture=user_info['picture'])
        user_id = User.get_id_by_email(new_user.email)

    # store user info in the session
    login_session['username'] = user_info['name']
    login_session['user_id'] = user_id
    login_session['picture'] = user_info['picture']
    login_session['email'] = user_info['email']

    # output to the client
    output = ""
    output += "<h3>"
    output += "Welcome, "
    output += login_session['username']
    output += "</h3>"
    return output