def connect(): code = request.data app.logger.debug("connect - code: {0}".format(code)) try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) app.logger.debug("credentials: {0}".format(credentials.to_json())) # Store the access token in the session for later use. session['credentials'] = pickle.dumps(credentials) gplus_id = credentials.id_token['sub'] http = credentials.authorize(httplib2.Http()) try: # load the existing user user = UserModel.get(gplus_id) app.logger.debug("user found: {0}".format(gplus_id)) except UserModel.DoesNotExist: # create a new record for this user google_request = SERVICE.people().get(userId='me') profile = google_request.execute(http=http) #app.logger.debug('profile: %s' % profile) user = UserModel(gplus_id) user.populate_from_profile(profile) app.logger.debug("user added: {0}".format(gplus_id)) user.last_login_datetime = datetime.datetime.now() user.save() # fetch visible connections, store new connections to the db # NOTE: we do not purge connections that are no longer valid...yet google_request = SERVICE.people().list(userId='me', collection='visible') for profile in google_request.execute(http=http).get('items'): connection = user.update_connection(profile) #app.logger.debug("Created connection: {0}".format(connection.to_json())) except FlowExchangeError: app.logger.warn('connect - FlowExchangeError') session.pop('credentials', None) response = make_response(json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response response = make_response(json.dumps('Successfully connected user.'), 200) response.headers['Content-Type'] = 'application/json' return response