500&404 errors

This commit is contained in:
2025-06-20 09:48:20 +01:00
parent 30884ecaa4
commit f2cffc4400
25 changed files with 353 additions and 193 deletions
+60 -30
View File
@@ -1,8 +1,12 @@
from flask import Flask, request, render_template
from flask import Flask, request, render_template, send_from_directory
from flask_session import Session
from dotenv import load_dotenv
from os import getenv as env
import logging, database, requests
import logging, requests
try:
import src.database as database
except ImportError:
import database
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
@@ -11,8 +15,9 @@ load_dotenv()
app = Flask(
__name__,
template_folder=env('TEMPLATE_FOLDER', default='templates'),
static_folder=env('STATIC_FOLDER', default='static'),
template_folder=env('TEMPLATE_FOLDER', default='../templates'),
static_folder=env('STATIC_FOLDER', default='../static'),
static_url_path=env('STATIC_URL_PATH', default='/static')
)
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
@@ -28,48 +33,73 @@ def index():
return render_template('index.html')
@app.route('/snake/submit', methods=['POST'])
@app.route('/robots.txt')
@app.route('/sitemap.xml')
@app.route('/favicon.ico')
def web_stuffs():
return send_from_directory(
app.static_folder,
request.path[1:],
)
@app.route('/404')
@app.errorhandler(404)
def not_found():
unformatted_scores = db.get_snake_scores()
scores = [{'position': i + 1, 'name': score[1], 'score': score[2]} for i, score in enumerate(unformatted_scores)]
return render_template('404.html', scores=scores)
@app.route('/404/submit', methods=['POST'])
def snake_submit():
data = request.json
if not data or 'name' not in data or 'score' not in data:
logging.error("Invalid data received: %s", data)
return {'error': 'Invalid data'}, 400
unformatted_scores = db.get_snake_scores()
scores = [{'position': i + 1, 'name': score[1], 'score': score[2]} for i, score in enumerate(unformatted_scores)]
data = request.form
username = data.get('username', '').strip()
score = data.get('snake-score', '').strip()
token = data.get('cap-token', '').strip()
if not username or not score or not token:
logging.error("Missing required fields: username=%s, score=%s, token=%s", username, score, token)
return render_template('404.html', scores=scores, error='Missing required fields'), 400
name = data.get('name', '')
cap = data.get('cap', '')
score = data.get('score', -1)
try:
score = int(score)
except ValueError:
logging.error("Invalid score value: %s", score)
return render_template('404.html', scores=scores, error='Invalid score value'), 400
if score <= 0 or score > 10000 or len(username) < 3 or len(username) > 20:
logging.error("Invalid score or username length: score=%s, username=%s", score, username)
return render_template('404.html', scores=scores, error='Invalid score or username length'), 400
cap_response = requests.post(
env('CAP_VERIFY_URL', default='https://<instance_url>/<key_id>/siteverify'),
json={
'secret': env('CAP_SECRET', default=''),
'response': cap,
'response': token,
}
)
if cap_response.status_code != 200 or not cap_response.json().get('success', "false") != "true":
logging.error("Captcha verification failed: %s", cap_response.json())
return {'error': 'Captcha verification failed'}, 400
if not isinstance(name, str) or not isinstance(score, int):
logging.error("Invalid data types: name=%s, score=%s", type(name), type(score))
return {'error': 'Invalid data types'}, 400
return render_template('404.html', scores=scores, error='Captcha verification failed'), 400
if not name or score <= 0 or score > 10000:
logging.error("Invalid name or score: name=%s, score=%s", name, score)
return {'error': 'Invalid name or score'}, 400
db.insert_snake(name, score)
logging.info("Snake submitted: name=%s, score=%d", name, score)
return {'success': True, 'message': 'Snake submitted successfully'}, 200
db.insert_snake(name=username, score=int(score))
logging.info("Snake submitted: name=%s, score=%d", username, score)
@app.errorhandler(404)
def page_not_found(e):
logging.error("Page not found: %s", request.path)
unformatted_scores = db.get_snake_scores()
scores = [{'position': i + 1, 'name': score[1], 'score': score[2]} for i, score in enumerate(unformatted_scores)]
return render_template('404.html', scores=scores), 404
return render_template('404.html', scores=scores, success='Score submitted successfully!')
@app.route('/500')
@app.errorhandler(500)
def internal_error(error="An internal server error occurred."):
logging.error("Internal server error: %s", error)
return render_template('500.html'), 500
if __name__ == '__main__':