Spaces:
Sleeping
Sleeping
File size: 5,302 Bytes
988a5e2 a0c1752 add4925 e93886b b85a736 988a5e2 f00bc4e 2b51d02 5ab6141 3133bf3 ed51e71 bc52bd6 5e6964f 938a1cb 9d07d46 d3ebf3e 1b7ac06 988a5e2 338a575 ed51e71 bc52bd6 965d8b2 43da317 8faf469 43da317 dc3dd03 1b65c90 dc3dd03 54f8daf 3289880 43da317 bc52bd6 5ab6141 e93886b dc3dd03 5ab6141 d6f36b6 8faf469 a2f88b1 2c883ba 5ab6141 c41c101 dc3dd03 e5155a3 c41c101 6715fb1 26a2bd4 279ab20 26a2bd4 e5155a3 c6e081e c41c101 e64321a dc3dd03 c41c101 5abe8ef c41c101 3ce2724 c41c101 8faf469 a2f88b1 c41c101 d3ebf3e c41c101 e93886b 47afa07 e93886b 6459dee e93886b 7f95107 add4925 e93886b 52243f0 e93886b 52243f0 61f285f 52243f0 9aad134 acd4b4a add4925 dc3dd03 d6f36b6 9a82649 e93886b 338a575 e93886b 5f31536 e93886b 5f31536 e93886b 5f31536 e93886b 338a575 c66d6cd 338a575 5f31536 | 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | 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)
@app.route("/")
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
@app.route("/signup")
def signup():
# if not allow_signups:
#abort(404)
return render_template("signup.html")
@app.route("/login", methods=['GET', 'POST'])
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)
@app.route("/logout")
def logout():
wipeSession()
return redirect(url_for("login"))
@app.post("/api/signup")
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
@app.post("/api/messages")
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
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
@app.route("/app")
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) |