From 6c3609f590c92c56986bedc7b11c7620acdbf275 Mon Sep 17 00:00:00 2001 From: Inex Code Date: Tue, 16 Nov 2021 12:32:10 +0200 Subject: [PATCH] Add basic API auth --- selfprivacy_api/app.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/selfprivacy_api/app.py b/selfprivacy_api/app.py index 2c7dcbb..28959f1 100644 --- a/selfprivacy_api/app.py +++ b/selfprivacy_api/app.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 -from flask import Flask +from flask import Flask, request, jsonify from flask_restful import Api +import os from selfprivacy_api.resources.users import Users from selfprivacy_api.resources.common import DecryptDisk @@ -10,6 +11,19 @@ def create_app(): app = Flask(__name__) api = Api(app) + app.config['AUTH_TOKEN'] = os.environ.get('AUTH_TOKEN') + + # Check bearer token + @app.before_request + def check_auth(): + auth = request.headers.get("Authorization") + if auth is None: + return jsonify({"error": "Missing Authorization header"}), 401 + + # Check if token is valid + if auth != "Bearer " + app.config['AUTH_TOKEN']: + return jsonify({"error": "Invalid token"}), 401 + api.add_resource(Users, "/users") api.add_resource(DecryptDisk, "/decryptDisk") from selfprivacy_api.resources.system import api_system