from flask import Flask, request, session, redirect, jsonify from twitter_api_v2 import TwitterApi import os import requests app = Flask(__name__) app.secret_key = os.urandom(24) client_id = os.environ["CLIENT_ID"] client_secret = os.environ["CLIENT_SECRET"] callback_url = os.environ["CALLBACK_URL"] callback_route = "/oauth/callback/twitter" connect_twitter = os.environ["CONNECT_TWITTER"] bearer_token = None @app.route("/bookmarks", methods=["GET"]) def get_bookmarks(): access_token = request.args.get("accessToken") try: client = TwitterApi(access_token) bookmarks = client.v2.bookmarks(expansions=["referenced_tweets.id"]) response = [bookmark for bookmark in bookmarks] return jsonify(response) except Exception as e: return handle_error(e) @app.route("/login/success", methods=["GET"]) def login_success(): return jsonify(session.get("connected")) @app.route("/login/", methods=["GET"]) def login(id): global bearer_token bearer_token = id client = TwitterApi(client_id=client_id, client_secret=client_secret) try: auth_link = client.generate_oauth2_auth_link( callback_url + callback_route, scope=[ "tweet.read", "tweet.write", "users.read", "follows.read", "like.read", "like.write", "bookmark.read", "offline.access", ], ) session["code_verifier"] = auth_link["code_verifier"] session["state"] = auth_link["state"] return redirect(auth_link["url"]) except Exception as e: print(e) return "Error occurred during login." def handle_error(error): if hasattr(error, "response"): data = error.response.json() status = data.get("status") detail = data.get("detail") if status and detail: return detail, status return "Something went wrong", 500 if __name__ == "__main__": app.run()