Skip to content

Commit

Permalink
Added user to flask.g with FLASK_AUTH_ALL=True
Browse files Browse the repository at this point in the history
Closes #9
  • Loading branch information
carsongee committed Jun 28, 2015
1 parent a41cad3 commit 1976803
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 5 deletions.
3 changes: 2 additions & 1 deletion README.rst
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions flask_htpasswd.py
Expand Up @@ -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
Expand Down Expand Up @@ -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):
"""
Expand Down
6 changes: 4 additions & 2 deletions tests/test_htpasswd.py
Expand Up @@ -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
Expand Down Expand Up @@ -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('/')
Expand All @@ -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('/')
Expand Down

0 comments on commit 1976803

Please sign in to comment.