diff --git a/docs/api.yml b/docs/api.yml index 12d8f7616d0b4451c40676a73fed5e89fe2ca1bd..8f8ef4502656a78adc0c2c8c1e04a5b1a8dbca0a 100644 --- a/docs/api.yml +++ b/docs/api.yml @@ -139,6 +139,13 @@ paths: post: summary: Adds a new measurement. Non-existent device or sensor will be created automatically. operationId: addMeasurement + parameters: + - in: header + name: apiKey + description: The api key + required: true + schema: + type: string requestBody: description: Measurement to add required: true diff --git a/settings-example.json b/settings-example.json index 20725d4df86f3413bf8b0c8742e0d91d2a915684..3c724fa69b38c078d270785b50eecd9b115e0f82 100644 --- a/settings-example.json +++ b/settings-example.json @@ -11,6 +11,7 @@ "databasePath": "storageLeaf.db" }, "api": { - "url": "http://localhost:10003" + "url": "http://localhost:10003", + "key": "" } } \ No newline at end of file diff --git a/src/blueprints/Routes.py b/src/blueprints/Routes.py index fe334f882b2f47f2da654d70339671b258d3e27e..524e729527d1f7b15712f883593d1a416dd39ca2 100644 --- a/src/blueprints/Routes.py +++ b/src/blueprints/Routes.py @@ -7,6 +7,7 @@ import yaml from flask import Blueprint, request, jsonify, render_template from logic import Constants +from logic.AuthenticationWrapper import require_api_key from logic.Database import Database from logic.RequestValidator import ValidationError, RequestValidator @@ -96,6 +97,7 @@ def construct_blueprint(settings, version): return jsonify(database.get_all_measurements_for_sensor(sensorID)) @routes.route('/measurements', methods=['POST']) + @require_api_key(password=settings['api']['key']) def addMeasurement(): try: parameters = RequestValidator.validate(request, DeviceParameters.get_values()) diff --git a/src/logic/AuthenticationWrapper.py b/src/logic/AuthenticationWrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a87abde8e8992363757957f4770f17be79769a --- /dev/null +++ b/src/logic/AuthenticationWrapper.py @@ -0,0 +1,22 @@ +from functools import wraps + +from flask import request, jsonify + + +def require_api_key(password): + def wrap_route(func): + @wraps(func) + def check_api_key(*args, **kwargs): + apiKey = request.headers.get('apiKey') + if not apiKey: + return jsonify({'message': 'apiKey missing'}), 401 + + if apiKey == password: + # redirect to requested url + return func(*args, **kwargs) + + return jsonify({'message': 'apiKey invalid'}), 401 + + return check_api_key + + return wrap_route