Last active
August 28, 2024 03:05
-
-
Save mwollenweber/334f60eeead496468d7de3c0bd1a02c9 to your computer and use it in GitHub Desktop.
nonce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, jsonify | |
from uuid import uuid4 | |
app = Flask(__name__) | |
app.secret_key = 'password42' # For session management | |
# requests come with these parameters from the frontend in `metadata`: | |
# 1. `user_agent`: the user agent of the client | |
# 2. `user_id`: a unique ID assigned to each user | |
# 3. `user_ip`: the user's ip address | |
DB_NONCE_SOURCES = { | |
#'42': ('alpha', None, "127.0.0.1") | |
} | |
def check_nonce(nonce): | |
return nonce in DB_NONCE_SOURCES | |
def add_nonce(nonce, metadata): | |
DB_NONCE_SOURCES[nonce] = metadata | |
def get_nonce(nonce): | |
return DB_NONCE_SOURCES[nonce] | |
def create_nonce(request): | |
user_agent = request.headers.get('User-Agent') | |
user_id = request.headers.get('user_id') | |
user_ip = request.remote_addr | |
metadata = (user_agent, user_id, user_ip) | |
nonce = f"{uuid4()}" | |
add_nonce(nonce, metadata) | |
return (nonce, metadata) | |
def validate_nonce(nonce, *args): | |
if check_nonce(nonce): | |
metadata = DB_NONCE_SOURCES[nonce] | |
#nonce's are one use. Delete | |
del DB_NONCE_SOURCES[nonce] | |
return metadata | |
return None | |
@app.route('/create', methods=['GET']) | |
def create(): | |
nonce, metadata = create_nonce(request) | |
result = {"nonce": nonce, "metadata": metadata} | |
return jsonify(result) | |
@app.route('/validate', methods=['POST']) | |
def validate(): | |
nonce = request.args.get("nonce") | |
user_agent = request.headers.get('User-Agent') | |
user_id = request.headers.get('user_id') | |
user_ip = request.remote_addr | |
metadata = (user_agent, user_id, user_ip) | |
if validate_nonce(nonce) == metadata: | |
return jsonify({"status": "good"}) | |
return jsonify({ | |
"status": "error", | |
"metadata": metadata, | |
"error": "invalid nonce", | |
}) | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0', port=5001, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment