From 0891d14934f9ebd47958cd196b45cb7b5dd5f1ef Mon Sep 17 00:00:00 2001 From: Carson Gee Date: Sun, 28 Jun 2015 17:02:31 -0400 Subject: [PATCH] Added user to flask.g Closes #9 --- README.rst | 3 ++- flask_htpasswd.py | 5 +++-- tests/test_htpasswd.py | 6 ++++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 47383d3..dc04e3a 100644 --- a/README.rst +++ b/README.rst @@ -63,7 +63,8 @@ accept tokens). If you would like to protect all of your views, that is easy too, just add a little config. By setting ``app.config['FLASK_AUTH_ALL']=True`` before initializing the extension, an ``@app.before_request`` is added -that will require auth for all pages. +that will require auth for all pages, and it will add the user as +``flask.g.user``. One last small feature, is that you can also set the authentication realm. The default is 'Login Required', but it can be set with diff --git a/flask_htpasswd.py b/flask_htpasswd.py index 992b6bf..1aceb6d 100644 --- a/flask_htpasswd.py +++ b/flask_htpasswd.py @@ -8,7 +8,7 @@ import hashlib import logging -from flask import request, Response, current_app +from flask import request, Response, current_app, g from itsdangerous import JSONWebSignatureSerializer as Serializer from itsdangerous import BadSignature from passlib.apache import HtpasswdFile @@ -54,9 +54,10 @@ def require_auth(): # pylint: disable=unused-variable """Pre request processing for enabling full app authentication.""" if not current_app.config['FLASK_AUTH_ALL']: return - is_valid, _ = self.authenticate() + is_valid, user = self.authenticate() if not is_valid: return self.auth_failed() + g.user = user def check_basic_auth(self, username, password): """ diff --git a/tests/test_htpasswd.py b/tests/test_htpasswd.py index fcddd18..aebec86 100644 --- a/tests/test_htpasswd.py +++ b/tests/test_htpasswd.py @@ -6,7 +6,7 @@ import os import unittest -from flask import request, Flask +from flask import request, Flask, g # pylint: disable=no-name-in-module,import-error from flask.ext.htpasswd import HtPasswdAuth from itsdangerous import JSONWebSignatureSerializer as Serializer @@ -234,7 +234,7 @@ def test_requires_auth(self): self.assertEqual(401, response.status_code) def test_auth_all_views_disabled(self): - """Verify that with ``FLASK_AUTH_ALL`` turned on, views are normal""" + """Verify that with ``FLASK_AUTH_ALL`` turned off, views are normal""" self._setup_normal_extension() @self.app.route('/') @@ -253,6 +253,8 @@ def test_auth_all_views_enabled(self): @self.app.route('/') def _(): """Simple view to verify we are protected.""" + # Validate we have the user available in g + self.assertEqual(g.user, self.TEST_USER) return 'Hi' response = self.app.test_client().get('/')