File size: 2,390 Bytes
40330c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96e30dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import requests
from flask import Flask, request, redirect, url_for, session
from google.oauth2 import id_token
from google.auth.transport import requests as grequests

app = Flask(__name__)
app.secret_key = "your_secret_key"

CLIENT_ID = "your_google_client_id"

# Google API endpoints
DISCOVERY_URL = "https://accounts.google.com/.well-known/openid-configuration"
TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
DOCS_API_ENDPOINT = "https://docs.googleapis.com/v1/documents/{documentId}"

@app.route("/")
def index():
    return "Welcome to the Google Docs Shiny app!"

@app.route("/login")
def login():
    # Generate Google login URL
    authorization_endpoint = requests.get(DISCOVERY_URL).json()["authorization_endpoint"]
    redirect_uri = request.base_url + "/callback"
    login_url = f"{authorization_endpoint}?response_type=code&client_id={CLIENT_ID}&redirect_uri={redirect_uri}&scope=email%20profile%20openid&access_type=offline"
    return redirect(login_url)

@app.route("/login/callback")
def login_callback():
    # Exchange authorization code for access token
    code = request.args.get("code")
    token_request_data = {
        "code": code,
        "client_id": CLIENT_ID,
        "client_secret": "your_client_secret",
        "redirect_uri": request.base_url,
        "grant_type": "authorization_code"
    }
    token_response = requests.post(TOKEN_ENDPOINT, data=token_request_data)
    access_token = token_response.json().get("access_token")
    
    if access_token:
        session["access_token"] = access_token
        return redirect(url_for("fetch_comments"))
    else:
        return "Failed to obtain access token."

@app.route("/fetch_comments")
def fetch_comments():
    if "access_token" in session:
        # Fetch comments from Google Docs API
        document_id = "your_document_id"
        headers = {"Authorization": f"Bearer {session['access_token']}"}
        response = requests.get(DOCS_API_ENDPOINT.format(documentId=document_id), headers=headers)
        
        if response.status_code == 200:
            # Parse comments from response
            comments = response.json().get("comments", [])
            return str(comments)
        else:
            return f"Failed to fetch comments. Status code: {response.status_code}"
    else:
        return "User not authenticated."

if __name__ == "__main__":
    app.run(debug=True)