diff --git a/ash.py b/ash.py index 968b36a..769358e 100644 --- a/ash.py +++ b/ash.py @@ -17,6 +17,7 @@ import flask import requests +from flask_httpauth import HTTPBasicAuth from elasticsearch import Elasticsearch @@ -52,6 +53,20 @@ class DefaultConfig: app.config['T_TWITTER_TOKEN'] = bearer_token +# Setup basic auth +auth = HTTPBasicAuth() + + +@auth.verify_password +def verify_password(username, password): + if db := app.config.get('T_SEARCH_BASIC_AUTH', {}): + if username == db.get('username') and password == db.get('password'): + return True + else: + return True + return False + + def toot_to_tweet(status: dict) -> dict: '''Transform toot to be compatible with tweet-interface''' # Status is a tweet @@ -463,17 +478,11 @@ def get_media_from_filesystem(fs_path: str): @app.route('/tweet/search.') +@auth.login_required def search_tweet(ext: str): if ext not in ('html', 'txt', 'json'): flask.abort(404) - basic_auth = app.config.get('T_SEARCH_BASIC_AUTH') - if basic_auth and (basic_auth != flask.request.authorization): - resp = flask.Response( - status=401, headers={'WWW-Authenticate': 'Basic realm="Auth Required"'} - ) - return resp - tdb = get_tdb() users = tdb.get_users() indexes = tdb.get_indexes() diff --git a/requirements.txt b/requirements.txt index b7e4f37..b0c4a2a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,15 @@ -Flask==2.3.2 +blinker==1.6.2 +certifi==2023.5.7 +charset-normalizer==3.2.0 +click==8.1.4 +elastic-transport==8.4.0 elasticsearch==8.8.0 +Flask==2.3.2 +Flask-HTTPAuth==4.8.0 +idna==3.4 +itsdangerous==2.1.2 +Jinja2==3.1.2 +MarkupSafe==2.1.3 requests==2.31.0 +urllib3==1.26.16 +Werkzeug==2.3.6 diff --git a/tests/test_views.py b/tests/test_views.py index 4a5ebbe..b320f6a 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -23,6 +23,17 @@ def test_search(self, client): for kw in self.keywords: assert kw in resp.text + def test_search_with_basic_auth(self, client): + db = { + 'username': 'foo', + 'password': 'bar' + } + client.application.config['T_SEARCH_BASIC_AUTH'] = db + resp = client.get('/tweet/search.html') + assert resp.status_code == 401 + resp = client.get('/tweet/search.html', auth=(db['username'], db['password'])) + assert '