def oauth2callback(): # Specify the state when creating the flow in the callback so that it can # verified in the authorization server response. state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( configFunctions.CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) # Use the authorization server's response to fetch the OAuth 2.0 tokens. authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) google_session = flow.authorized_session() #print google_session.get('https://www.googleapis.com/userinfo/v2/me').json() flask.session[SESSION_USER_DATA_KEY] = google_session.get( 'https://www.googleapis.com/userinfo/v2/me').json() # Store credentials in the session. # ACTION ITEM: In a production app, you likely want to save these # credentials in a persistent database instead. credentials = flow.credentials flask.session[SESSION_CREDENTIALS_KEY] = credentials_to_dict(credentials) return flask.redirect(flask.url_for('index'))
def oauth2callback(): state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_config( json.loads(os.environ['CLIENT_SECRET']), scopes=oauth_scopes, state=state) flow.redirect_uri = flask.url_for('routes.oauth2callback', _external=True) authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials print(credentials_to_dict(credentials)) flask.session['credentials'] = credentials_to_dict(credentials) if flask.session['credentials']['refresh_token'] == None: print(">>>>") # flow.credentials.token = "1/NWvP0mjD4Vp3xs22FkvdqWHw-_7VUyC2VN7zcsthHcw" flask.session['credentials'][ 'refresh_token'] = "1/NWvP0mjD4Vp3xs22FkvdqWHw-_7VUyC2VN7zcsthHcw" session = flow.authorized_session() user_info = session.get('https://www.googleapis.com/userinfo/v2/me').json() flask.session["user_info"] = user_info return redirect("/")
def oauth2callback(): logging.debug('oauth2callback') # print "OAUTH2CALLBACK::" # Specify the state when creating the flow in the callback so that it can # verify the authorization server response. state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) # Use the authorization server's response to fetch the OAuth 2.0 tokens. authorization_response = flask.request.url try: token = flow.fetch_token(authorization_response=authorization_response) except Exception: logging.exception('Exception occured during fetch_token.') logging.debug('Token was fetched.') # print "OAUTH2CALLBACK::TOKEN: ", token # acquire user info try: user_info = flow.authorized_session().get(USERINFO_URL).json() except Exception: logging.exception('Exception occured during userinfo.') logging.debug('userinfo was fetched.') flask.session['userinfo'] = user_info # print "OAUTH2CALLBACK::USERINFO: ", user_info # store refresh token & token uri models.store_token(user_info['id'], token) return flask.redirect(flask.url_for('start', userid=user_info['id']))
def get_user_from_code(self, url, code): flow = self.get_auth_flow(url) self.google_token = flow.fetch_token(code=code) self.session = flow.authorized_session() self.user = self.session.get( "https://www.googleapis.com/userinfo/v2/me").json() return self.user
def oauth2callback(): state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_config( json.loads(os.environ['CLIENT_SECRET']), scopes=oauth_scopes, state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials flask.session['credentials'] = credentials_to_dict(credentials) if flask.session['credentials']['refresh_token'] == None: print(">>>>") # flow.credentials.token = "1/NWvP0mjD4Vp3xs22FkvdqWHw-_7VUyC2VN7zcsthHcw" flask.session['credentials'][ 'refresh_token'] = "1/NWvP0mjD4Vp3xs22FkvdqWHw-_7VUyC2VN7zcsthHcw" session = flow.authorized_session() user_info = session.get('https://www.googleapis.com/userinfo/v2/me').json() if ("@lawrenceville.org" in user_info["email"]): flask.session["user_info"] = user_info print(">>>> User info has been set") if (is_valid_school(flask.session["user_info"]["email"])): found_user = db.session.query(ReshwapUsers).filter( ReshwapUsers.email == flask.session["user_info"] ["email"]).all() if (not found_user): user_info = flask.session["user_info"] newUser = ReshwapUsers( user_info["name"], user_info["picture"], user_info["email"], datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y"), datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) db.session.add(newUser) db.session.commit() else: found_user[0].last_login = datetime.datetime.now().strftime( "%I:%M%p on %B %d, %Y") db.session.commit() return redirect("/") return redirect("/invalid_account")
def oauth2callback(): state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_config( json.loads(os.environ['CLIENT_SECRET']), scopes=oauth_scopes, state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials print(credentials_to_dict(credentials)) flask.session['credentials'] = credentials_to_dict(credentials) if flask.session['credentials']['refresh_token'] == None: print(">>>>") # flow.credentials.token = "1/NWvP0mjD4Vp3xs22FkvdqWHw-_7VUyC2VN7zcsthHcw" flask.session['credentials'][ 'refresh_token'] = "1/NWvP0mjD4Vp3xs22FkvdqWHw-_7VUyC2VN7zcsthHcw" session = flow.authorized_session() user_info = session.get('https://www.googleapis.com/userinfo/v2/me').json() flask.session["user_info"] = user_info found_user = db.session.query(MomentsUsers).filter( MomentsUsers.email == flask.session["user_info"]["email"]).all() print found_user print "User creation process initializing..." if (not found_user): user_info = flask.session["user_info"] newUser = MomentsUsers(user_info["name"], user_info["picture"], user_info["email"], datetime.datetime.now(), datetime.datetime.now()) db.session.add(newUser) db.session.commit() print "NEW USER CREATED \n\n\n\n" else: print("someone is signing in again...") found_user[0].last_login = datetime.datetime.now() db.session.commit() return redirect("/")
def callback(): # Specify the state when creating the flow in the callback so that it can # verified in the authorization server response. state = session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( app.config['GOOGLE_CLIENT_SECRET'], scopes=app.config['SCOPES'], state=state) flow.redirect_uri = url_for('callback', _external=True) # Use the authorization server's response to fetch the OAuth 2.0 tokens. authorization_response = request.url flow.fetch_token(authorization_response=authorization_response) # Store credentials in the session. # ACTION ITEM: In a production app, you likely want to save these # credentials in a persistent database instead. credentials = flow.credentials google_session = flow.authorized_session() user_data = google_session.get( 'https://www.googleapis.com/userinfo/v2/me').json() unique_id = user_data['id'] existing_user = User.query.get(unique_id) if existing_user is None: user = User(id=unique_id, name=user_data['name'], email=user_data['email'], image=user_data['picture'], authenticated=True, credentials=credentials_to_dict(credentials)) db.session.add(user) login_user(user) else: # Begin user session by logging the user in existing_user.authenticated = True existing_user.credentials = credentials_to_dict(credentials) login_user(existing_user) db.session.commit() return redirect(url_for("home"))
def auth_redirect(request): state = request.GET['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( client_json_path, scopes=['profile'], state=state, ) flow.redirect_uri = 'http://cursdb.com:8000/redirect' authorization_response = request.build_absolute_uri() flow.fetch_token(authorization_response=authorization_response) session = flow.authorized_session() data = session.get('https://www.googleapis.com/userinfo/v2/me').json() with UserDao() as dao: user = User(data['name'], data['email']) dao.create(user) response = redirect('/') response.set_cookie('useremail', user.email) response.set_cookie('username', user.name) response.set_cookie( 'token', hashlib.md5((user.name + user.email).encode()).hexdigest()) return response
def main(): if len(sys.argv) != 2: print( "Please provide playlist ID as the first parameter to the script") exit(1) # Disable OAuthlib's HTTPS verification when running locally. # *DO NOT* leave this option enabled in production. os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name = "youtube" api_version = "v3" client_secrets_filename = "client_secrets.json" session_filename = "session.json" playlist_id = sys.argv[1].rstrip() print( "Get ready to log in with the same Google account that owns this playlist." ) print( "Preparing to add playlist items to https://www.youtube.com/playlist?list=" + playlist_id) print("Does this playlist link look right?") if not confirm(): exit(1) playlist_filename = "playlist.txt" added_playlist_filename = "added.txt" if os.path.isfile(session_filename): print("Loading session") with open(session_filename) as session_file: info = json.load(session_file) credentials = Credentials( token=info['token'], refresh_token=info['refresh_token'], token_uri=info['token_uri'], client_id=info['client_id'], client_secret=info['client_secret'], scopes=info['scopes'], ) credentials.expiry = datetime.datetime.fromisoformat( info['expiry']) if credentials.expired: print("Refreshing credentials") # don't forget to dump one more time after the refresh # also, some file-locking routines wouldn't be needless credentials.refresh(Request()) info = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes, 'expiry': credentials.expiry.isoformat(), } with open(session_filename, 'w') as session_file: json.dump(info, session_file) else: # Get credentials and create an API client flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( client_secrets_filename, scopes) credentials = flow.run_console() session = flow.authorized_session() print(session.get('https://www.googleapis.com/userinfo/v2/me').json()) info = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes, 'expiry': credentials.expiry.isoformat(), } with open(session_filename, 'w') as session_file: json.dump(info, session_file) youtube = googleapiclient.discovery.build(api_service_name, api_version, credentials=credentials) with open(playlist_filename) as f: i = 0 for line in f: video_id = get_yt_video_id(line) with open(added_playlist_filename) as added_playlist_file: found = False for check_if_already_added in added_playlist_file: #print(check_if_already_added) if line.rstrip() in check_if_already_added: print(i, "Already added", video_id) found = True if not found: print(i, video_id) # exit(1) request = youtube.playlistItems().insert( part="snippet", body={ "snippet": { "playlistId": playlist_id, "position": i, "resourceId": { "kind": "youtube#video", "videoId": video_id } } }) try: # print(request.body) response = request.execute() print(i, response) if response and 'error' in response: print("Dam. I failed.") exit(1) else: with open(added_playlist_filename, 'a') as added_playlist_file: added_playlist_file.writelines(line) except HttpError as e: print(os.linesep) print("Dam. I failed.", e) print("Here's the content:", e.content) print("Here's the resp:", e.resp) print(os.linesep) if "quotaExceeded" in str(e.content): print( "You may have reached your quota for the day. Come back tomorrow." ) exit(1) elif "Forbidden" in str(e.content): print( "Assuming the video was deleted because the account was terminated." ) with open(added_playlist_filename, 'a') as added_playlist_file: added_playlist_file.writelines(line.rstrip() + " # 403" + os.linesep) elif e.resp.status != 404: print( "Check and see if https://youtu.be/" + video_id + " is available. If not, you will need to manually add that to added.txt to skip it. Otherwise, some other error I can't figure out. Dunno." ) exit(1) else: print("This video not found anymore?") with open(added_playlist_filename, 'a') as added_playlist_file: added_playlist_file.writelines(line.rstrip() + " # 404" + os.linesep) i = i + 1