Spaces:
Sleeping
Sleeping
Download app.py from Arcader7171/InterState: direct link, hf CLI and curl.
- Browser
- Download file 5.3 kB
-
https://huggingface.co/spaces/Arcader7171/InterState/resolve/main/app.py
- Command line
-
hf download hf://spaces/Arcader7171/InterState/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Arcader7171/InterState/resolve/main/app.py
5.3 kB
| import os | |
| import json | |
| import base64 | |
| import asyncio | |
| import traceback | |
| from flask import Flask, render_template, url_for, redirect, request, make_response, session, abort | |
| from flask_socketio import SocketIO, join_room, leave_room | |
| import requests | |
| from supabase import create_client, Client, acreate_client, AsyncClient | |
| import jwt | |
| app = Flask(__name__) | |
| app.config['SECRET_KEY'] = os.environ.get("FLASK_KEY") | |
| redis_url = os.environ.get("REDIS_URL"); | |
| io = SocketIO(app, logger=True, engineio_logger=True, cors_allowerd_origins=[ | |
| "https://arcader7171-interstate.hf.space" | |
| ]) | |
| url: str = os.environ.get("SUPABASE_URL") | |
| publicKey: str = os.environ.get("SUPABASE_PUBLIC_KEY") | |
| serviceKey: str = os.environ.get("SUPABASE_SERVICE_KEY") | |
| jwtKey: str = os.environ.get("JWTKey") | |
| onlineUsers = {} | |
| # Function Config | |
| allow_signups: bool = True # Set to true when allowing a new user | |
| def jwtDecode(token): | |
| try: | |
| return "good", jwt.decode(token, jwtKey, algorithms=["HS256"]) | |
| except jwt.exceptions.InvalidTokenError: | |
| return "bad", "Username/Password does not match" | |
| def wipeSession(): | |
| session.pop("username", None) | |
| session.pop("password", None) | |
| def index(): | |
| return render_template("index.html") | |
| # The route for /app used to be here, but has been moved to be the end of the file to minimize scrolling for other routes | |
| def signup(): | |
| # if not allow_signups: | |
| #abort(404) | |
| return render_template("signup.html") | |
| async def login(): | |
| error = None | |
| if request.method == 'POST': | |
| supabase: Client = create_client(url, serviceKey) | |
| inData = request.form # input data, to seperate from the real, valid data | |
| inUser = inData["user"] | |
| inPass = inData["pass"] | |
| response = ( | |
| supabase.table("users") | |
| .select("username, password", count="exact") | |
| .eq("username", inUser) | |
| .single() | |
| .execute() | |
| ) | |
| data = response.data | |
| if data == []: | |
| error = "Username does not exist" | |
| user = data["username"] | |
| jwtPass = jwtDecode(data["password"]) | |
| if jwtPass[0] == "good": | |
| if jwtPass[1]["password"] == inPass: | |
| session["username"] = user | |
| session["password"] = jwtPass[1]["password"] | |
| return redirect(url_for("interApp")) | |
| error = jwtPass[1] | |
| return render_template("login.html", err=error) | |
| return render_template("login.html", err=None) | |
| def logout(): | |
| wipeSession() | |
| return redirect(url_for("login")) | |
| async def signupAPI(): | |
| supabase: Client = create_client(url, serviceKey) | |
| error = None | |
| # if not allow_signups: # Security mainly. Only allow signups when I want to. | |
| #abort(404) | |
| if request.method == 'POST': | |
| data = json.loads(request.data) | |
| sPass = jwt.encode({"password": data["password"]}, jwtKey, algorithm="HS256") | |
| dbData = {"username": data["username"], "password": sPass} | |
| dbResponse = ( | |
| supabase.table("users") | |
| .insert(dbData) | |
| .execute() | |
| ) | |
| response = dbResponse.data[0] | |
| return make_response(response), 200 | |
| async def messageAPI(): | |
| supabase: Client = create_client(url, serviceKey) | |
| if request.method == 'POST': | |
| data = json.loads(request.data) | |
| msg = data["content"] | |
| author = base64.b64decode(request.headers.get("Authorization").split(" ")[1].encode("ascii")).decode('utf-8').split(":")[0] | |
| response = ( | |
| supabase.table("messages") | |
| .insert({"author_name": author, "content": msg}) | |
| .execute() | |
| ) | |
| try: | |
| resp = response.data[0] | |
| except: | |
| return make_response(json.dumps({"message": "something went wrong", "db_response": response})), 401 | |
| io.emit('msg', {"author": resp["author_name"], "content": resp["content"], "local": False, "id": resp["id"]}) | |
| return make_response(json.dumps({"author": resp["author_name"], "content": resp["content"], "local": True, "id": resp["id"]})), 201 | |
| def not_found(e): | |
| return render_template("404.html") | |
| async def interApp(): | |
| if "username" not in session: | |
| wipeSession() | |
| return redirect(url_for("login")) | |
| if "password" not in session: | |
| wipeSession() | |
| return redirect(url_for("login")) | |
| supabase: AsyncClient = await acreate_client(url, serviceKey) | |
| response = ( | |
| await supabase.table("messages") | |
| .select("id, author_name, content") | |
| .execute() | |
| ) | |
| channel = supabase.channel("main/general") | |
| msgHistory = [] | |
| dbHistory = response.data | |
| latestMsgID = 0 | |
| for msg in dbHistory: | |
| latestMsgID = msg["id"] | |
| local = False | |
| if msg["author_name"] == session["username"]: | |
| local = True | |
| msgHistory.append({"user": msg["author_name"], "message": msg["content"], "local": local}) | |
| supa = { | |
| "url": url, | |
| "public_key": publicKey | |
| } | |
| return render_template("app.html", history=msgHistory, supa=supa, latestID=latestMsgID) |