diff options
| author | Morgana <Morgana@icolotl.com> | 2026-10-03 10:25:51 -0500 |
|---|---|---|
| committer | Morgana <Morgana@icolotl.com> | 2026-10-03 10:25:51 -0500 |
| commit | dfe2069c1dd4eb14d44a57d35d76afdc47d1598e (patch) | |
| tree | 88d2a4688bbc536af1d90ce12118cbf028f9f60b /app.py | |
| parent | e96fdc880d45ab22eea5eb1210fe767ce7fcd34e (diff) | |
Initial captcha code
Diffstat (limited to 'app.py')
| -rw-r--r-- | app.py | 45 |
1 files changed, 45 insertions, 0 deletions
@@ -16,9 +16,15 @@ from flask import ( ) from werkzeug.exceptions import HTTPException +from captcha import Captcha + SCRYPT_PARAMS = {"n": 16384, "r": 8, "p": 1} HEX_CHARS = set("0123456789ABCDEF") +GUEST_CAPTCHA = Captcha.from_string( + 5, "m...cena....m...ebneb.clm", ".........................", True +) + def get_db(): if "db" not in g: @@ -32,6 +38,16 @@ def teardown(e=None): db.close() +def has_captcha(captcha_id): + return captcha_id in session.get("captcha", []) + + +def add_captcha(captcha_id): + if "captcha" not in session: + session["captcha"] = [] + session["captcha"].append(captcha_id) + + app = Flask(__name__) with open("./config.json", "r", encoding="utf-8") as file: config = json.load(file) @@ -41,6 +57,11 @@ with open("./config.json", "r", encoding="utf-8") as file: app.teardown_appcontext(teardown) +@app.context_processor +def context_processor(): + return dict(has_captcha=has_captcha) + + @app.errorhandler(HTTPException) def handle_bad_request(e): if request.endpoint != "static": @@ -104,10 +125,21 @@ def login(): return render_template("login.html") +@app.route("/guest") +def guest_login(): + if has_captcha(GUEST_CAPTCHA.id) and "username" not in session: + session["username"] = "guest" + flash(f"Success: Logged in as guest.") + return redirect(url_for("index")) + return render_template("guest.html", captcha=GUEST_CAPTCHA) + + @app.route("/logout") def logout(): if "username" in session: del session["username"] + if "captcha" in session: + del session["captcha"] flash("Success: You have been logged out.") return redirect(url_for("index")) @@ -133,3 +165,16 @@ def news(): cur.execute("SELECT * FROM news ORDER BY id DESC") results = cur.fetchall() return render_template("news.html", news=results) + + +@app.route("/captcha") +def captcha(): + size = request.args.get("size", "") + label = request.args.get("label", "") + lock = request.args.get("lock", "") + answer = request.args.get("answer", "") + captcha = Captcha.safe_validate(size, label, lock, answer) + if captcha: + add_captcha(captcha.id) + return {"valid": True}, 200 + return {"valid": False}, 400 |