Spaces:
Configuration error
Configuration error
Create server.py
Browse files
server.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, redirect, request, session, jsonify, send_from_directory
|
| 2 |
+
import requests
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
app = Flask(__name__)
|
| 6 |
+
app.secret_key = os.getenv("SECRET_KEY", "supersecret") # for sessions
|
| 7 |
+
|
| 8 |
+
# Google OAuth config
|
| 9 |
+
GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
|
| 10 |
+
GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
|
| 11 |
+
REDIRECT_URI = f"https://{os.getenv('SPACE_ID')}.hf.space/google/auth/callback"
|
| 12 |
+
|
| 13 |
+
@app.route("/")
|
| 14 |
+
def index():
|
| 15 |
+
return send_from_directory(".", "frontend.html")
|
| 16 |
+
|
| 17 |
+
@app.route("/google/login")
|
| 18 |
+
def google_login():
|
| 19 |
+
google_auth_url = (
|
| 20 |
+
"https://accounts.google.com/o/oauth2/v2/auth"
|
| 21 |
+
"?response_type=code"
|
| 22 |
+
f"&client_id={GOOGLE_CLIENT_ID}"
|
| 23 |
+
f"&redirect_uri={REDIRECT_URI}"
|
| 24 |
+
"&scope=openid%20email%20profile"
|
| 25 |
+
)
|
| 26 |
+
return redirect(google_auth_url)
|
| 27 |
+
|
| 28 |
+
@app.route("/google/auth/callback")
|
| 29 |
+
def google_callback():
|
| 30 |
+
code = request.args.get("code")
|
| 31 |
+
if not code:
|
| 32 |
+
return "Error: No code provided", 400
|
| 33 |
+
|
| 34 |
+
# Exchange code for tokens
|
| 35 |
+
token_url = "https://oauth2.googleapis.com/token"
|
| 36 |
+
data = {
|
| 37 |
+
"code": code,
|
| 38 |
+
"client_id": GOOGLE_CLIENT_ID,
|
| 39 |
+
"client_secret": GOOGLE_CLIENT_SECRET,
|
| 40 |
+
"redirect_uri": REDIRECT_URI,
|
| 41 |
+
"grant_type": "authorization_code",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
r = requests.post(token_url, data=data)
|
| 45 |
+
tokens = r.json()
|
| 46 |
+
|
| 47 |
+
# Get user info
|
| 48 |
+
user_info = requests.get(
|
| 49 |
+
"https://www.googleapis.com/oauth2/v2/userinfo",
|
| 50 |
+
headers={"Authorization": f"Bearer {tokens['access_token']}"}
|
| 51 |
+
).json()
|
| 52 |
+
|
| 53 |
+
session["user"] = user_info
|
| 54 |
+
return redirect("/")
|
| 55 |
+
|
| 56 |
+
@app.route("/api/user")
|
| 57 |
+
def get_user():
|
| 58 |
+
user = session.get("user")
|
| 59 |
+
if user:
|
| 60 |
+
return jsonify(user)
|
| 61 |
+
return jsonify({"error": "Not logged in"}), 401
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
app.run(host="0.0.0.0", port=7860)
|