Fixed authentication issues

added env vars instead of importing python modules for configuration
 Changes to be committed:
	modified:   server/server_api.py
This commit is contained in:
2023-09-21 11:17:17 +03:30
parent 0263fffb3c
commit 695c4d7b84

View File

@@ -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(