Token based authentication

This commit is contained in:
Shivering Ocelot committed 2025-05-28 01:15:46 -05:00
1 parent 9a8e68f021
commit 5bbdfe8747
7 files changed
+121 -77

No files matched your search

+45 -8
View File
@@ -1,10 +1,23 @@
from quart import Quart, Response, request, send_from_directory, websocket
from quart_auth import (
QuartAuth, current_user,
AuthUser, login_user, logout_user
)
import json
import asyncio
import nest_asyncio
def start_server(app):
server = Quart(__name__, static_folder='../frontend/build/web')
server.secret_key = 'horde-secret'
auth_manager = QuartAuth(server, mode="brearer")
@server.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
@server.route('/')
async def index():
@@ -14,6 +27,21 @@ def start_server(app):
async def serve_static(path):
return await send_from_directory(server.static_folder, path)
@server.route('/user/login', methods=['POST'])
async def login():
data = await request.get_json()
if "username" not in data or "password" not in data:
await websocket.send(json.dumps({'error': 'invalid arguments'}))
return
user_id = app.verify_user_credentials(data['username'], data['password'])
if user_id == None:
return jsonify({'error': "bad credentials"}), 401
token = auth_manager.dump_token(user_id)
return {"token": token}
@server.route('/user/signup', methods=['POST'])
async def signup():
data = await request.get_json()
@@ -39,15 +67,24 @@ def start_server(app):
# Authenticate before dedicating any resources
auth_req = json.loads(await websocket.receive())
if "username" not in auth_req or "password" not in auth_req:
print("Invalid auth request:", auth_req)
await websocket.send(json.dumps({'error': 'invalid auth'}))
return
user_id = app.verify_user_credentials(auth_req['username'], auth_req['password'])
if user_id is None:
await websocket.send(json.dumps({'error': 'invalid credentials'}))
return
if 'token' in auth_req:
try:
user_id = auth_manager.load_token(auth_req['token'])
except Exception as err:
print("Token authentication failed: ", err)
await websocket.send(json.dumps({'error': 'token authentication failed'}))
return
else:
if "username" not in auth_req or "password" not in auth_req:
print("Invalid auth request:", auth_req)
await websocket.send(json.dumps({'error': 'invalid auth'}))
return
user_id = app.verify_user_credentials(auth_req['username'], auth_req['password'])
if user_id is None:
await websocket.send(json.dumps({'error': 'invalid credentials'}))
return
send_queue = asyncio.Queue()
async def sender_task():