From d42b798b262031dd4d97e80a0b28b1dac0b137f3 Mon Sep 17 00:00:00 2001 From: Zbigniew Siciarz Date: Mon, 13 Jun 2011 15:33:39 +0200 Subject: [PATCH 1/2] First try at Basic Auth. --- httpbin/core.py | 11 ++++++++++- httpbin/helpers.py | 9 ++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/httpbin/core.py b/httpbin/core.py index 6c1634d..d57756e 100644 --- a/httpbin/core.py +++ b/httpbin/core.py @@ -18,7 +18,7 @@ from time import time as now from decorator import decorator from flask import Flask, Response, request, render_template, redirect, g -from .helpers import get_files, get_headers, status_code, get_dict +from .helpers import get_files, get_headers, status_code, get_dict, check_basic_authorization app = Flask(__name__) @@ -196,5 +196,14 @@ def set_cookie(name, value): return response +@app.route('/basic-auth') +def basic_auth(): + """Prompts the user for authentication using HTTP Basic Auth.""" + + if not check_basic_authorization(): + return status_code(401) + return app.make_response('auth ok') + + if __name__ == '__main__': app.run() diff --git a/httpbin/helpers.py b/httpbin/helpers.py index 32ca9e7..bba8f93 100644 --- a/httpbin/helpers.py +++ b/httpbin/helpers.py @@ -108,4 +108,11 @@ def status_code(code): if 'headers' in m: r.headers = m['headers'] - return r \ No newline at end of file + return r + + +def check_basic_authorization(): + """Checks user authentication using HTTP Basic Auth.""" + + auth = request.authorization + return auth and auth.username == "httpbin" and auth.password == "secret" From f5ca0deb9009e3dd3bef7fa3d89367c1757c1ab8 Mon Sep 17 00:00:00 2001 From: Zbigniew Siciarz Date: Mon, 13 Jun 2011 15:50:40 +0200 Subject: [PATCH 2/2] Tweaking Basic Auth support. --- httpbin/core.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/httpbin/core.py b/httpbin/core.py index bcbd71a..042acf5 100644 --- a/httpbin/core.py +++ b/httpbin/core.py @@ -36,6 +36,10 @@ def json_resource(f, runtime=True, *args, **kwargs): data = f(*args, **kwargs) _t1 = now() + # we already have a formatted response, move along + if isinstance(data, Response): + return data + dump = json.dumps(data, sort_keys=True, indent=3) r = app.make_response(dump) @@ -197,12 +201,13 @@ def set_cookie(name, value): @app.route('/basic-auth') +@json_resource def basic_auth(): - """Prompts the user for authentication using HTTP Basic Auth.""" + """Prompts the user for authorization using HTTP Basic Auth.""" if not check_basic_authorization(): return status_code(401) - return app.make_response('auth ok') + return dict(authenticated=True) if __name__ == '__main__':