Hello everyone! I wrote an app which is a chatbot to respond user queries based on files on Google Drive. For the authentication, I use a singleton to store and compare the token to defend against CSRF. everything works locally but in the deployed window to let a user click allow is disappears immediately or stuck.
from flask import Blueprint, request, jsonify
from google_auth_oauthlib.flow import Flow
from utils.secret_manager import access_secret_version
from utils.token_storage import token_storage
from utils.Singleton import Singleton
import json
import os
from config import google_drive_scopes, google_drive_redirect_uri
bp = Blueprint('google_drive', __name__)
# Access client secrets from secret manager
cred_json = access_secret_version("tr-multimodel-ro", "drive_auth")
cred_info = json.loads(cred_json)
@BP.route('/api/google_drive/drive_validate', methods=['GET']) def drive_validate():
flow = Flow.from_client_config(
cred_info,
scopes=google_drive_scopes,
redirect_uri=google_drive_redirect_uri
)
state = os.urandom(16).hex()
authorization_url, _ = flow.authorization_url(
access_type='offline',
include_granted_scopes='true',
state=state
)
singleton = Singleton()
singleton.set_property('state', state)
return jsonify({"status": "redirect", "url": authorization_url}), 200
@BP.route('/api/google_drive/oauth2callback') def oauth2callback():
singleton = Singleton()
state_singleton = singleton.get_property('state')
state = request.args.get('state')
print('state:', state)
print('state_singleton:', state_singleton)
if state == state_singleton:
flow = Flow.from_client_config(
cred_info,
scopes=google_drive_scopes,
redirect_uri=google_drive_redirect_uri,
state=state_singleton
)
try:
flow.fetch_token(authorization_response=request.url)
credentials = flow.credentials
singleton.delete_property('state')
singleton.delete_instance()
# Store the credentials using TokenStorage
user_id = "example_user_id"
token_storage.store_token(user_id, credentials)
# Retrieve the credentials from TokenStorage to verify
credentials = token_storage.get_token(user_id)
else:
return jsonify({"error": "Invalid state parameter"}), 400