diff --git a/README.md b/README.md index 0ac2dc6..132e101 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,15 @@ List of available configuration options: | Name | Description | | ---- | ----------- | | `SQLALCHEMY_DATABASE_URI` | Database connection string. e.g: `postgresql://user:password@localhost/photowall` | -| `DEBUG` | Enable/disable debug mode +| `DEBUG` | Enable/disable debug mode | +| `API_KEYS` | A list of api keys that are used to authenticate to the API + +## Authentication +Authentication to the API is performed via HTTP Basic Auth. The user should provide her API key as the basic auth username parameter. An example request in cURL looks like this (adding a colon after the username prevents cURL from asking for a password): +``` +$ curl http://localhost:5000/designers/ -u mykey: +``` +API keys should be added to the `API_KEYS` configuration option ## Getting started diff --git a/api/__init__.py b/api/__init__.py index 89948ec..64ba28d 100644 --- a/api/__init__.py +++ b/api/__init__.py @@ -1,4 +1,4 @@ -from flask import Flask, jsonify +from flask import Flask, jsonify, Response, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) @@ -17,6 +17,22 @@ from api.views import designers app.register_blueprint(designers.mod) +def check_authentication(): + auth = request.authorization + if not auth: + return False + return auth.username in app.config.get("API_KEYS") + + +@app.before_request +def authenticate(): + if not check_authentication(): + return Response( + 'No valid API key provided', 401, + {'WWW-Authenticate': 'Basic realm="Login Required"'} + ) + + @app.route("/") def index(): data = { diff --git a/config.sample.py b/config.sample.py index de45af9..b8a1b98 100644 --- a/config.sample.py +++ b/config.sample.py @@ -1,3 +1,4 @@ SQLALCHEMY_DATABASE_URI = 'postgresql://user:password@host/db_name' SQLALCHEMY_TRACK_MODIFICATIONS = True -DEBUG = True \ No newline at end of file +DEBUG = True +API_KEYS = ['secretkey'] \ No newline at end of file