From 695c4d7b84bc26a0423e533f51c334463b17f4f7 Mon Sep 17 00:00:00 2001 From: "Muhamad H. Asadi" Date: Thu, 21 Sep 2023 11:17:17 +0330 Subject: [PATCH] Fixed authentication issues added env vars instead of importing python modules for configuration Changes to be committed: modified: server/server_api.py --- server/server_api.py | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/server/server_api.py b/server/server_api.py index 72df5bf..277a77f 100644 --- a/server/server_api.py +++ b/server/server_api.py @@ -1,17 +1,23 @@ from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy -from api_keys import api_keys -import config import datetime +import os +import json +# Flask app instance app = Flask(__name__) # Configuration for SQLAlchemy -app.config.from_object(config.Config) +app.config[ + 'SQLALCHEMY_DATABASE_URI' +] = os.environ.get( + "SQLALCHEMY_DATABASE_URI" +) db = SQLAlchemy(app) # Database Model for Records class Record(db.Model): + __tablename__ = 'records' id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.String(255), nullable=False) description = db.Column(db.String(255), nullable=False) @@ -23,15 +29,35 @@ def parse_timestamp(timestamp_str): except ValueError: return None +# Function to validate API keys based on their values and access level +def validate_api_key(api_key, required_access_level): + api_keys_json = os.environ.get('API_KEYS_JSON', '{}') + api_keys_dict = json.loads(api_keys_json) + + if api_key in api_keys_dict: + access_level = api_keys_dict[api_key].get("access_level") + return access_level == required_access_level + + return False + # API key authentication @app.before_request def authenticate(): # Check if the API key provided in the request headers is valid api_key = request.headers.get("Authorization") + + # Allow all requests with RW keys + if validate_api_key(api_key, "RW"): + return None # Allow the request to proceed + + # Allow GET requests with RO keys + if request.method == "GET" and validate_api_key(api_key, "RO"): + return None # Allow the request to proceed + + # Return a 401 Unauthorized response for invalid API keys or access levels + return jsonify({'error': 'Invalid API key or access level'}), 401 + - if api_key not in api_keys: - # Return a 401 Unauthorized response for invalid API keys - return jsonify({'error': 'Invalid API key'}), 401 # Route to add a new record @app.route(