Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented redirect_unauthenticated_users on LoginRequiredMixin #131

Merged
merged 1 commit into from Mar 24, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion braces/views/_access.py
Expand Up @@ -51,9 +51,11 @@ class LoginRequiredMixin(AccessMixin):
combined with CsrfExemptMixin - which in that case should
be the left-most mixin.
"""
redirect_unauthenticated_users = False

def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated():
if self.raise_exception:
if self.raise_exception and not self.redirect_unauthenticated_users:
raise PermissionDenied # return a forbidden response
else:
return redirect_to_login(request.get_full_path(),
Expand Down
2 changes: 2 additions & 0 deletions docs/access.rst
Expand Up @@ -46,6 +46,8 @@ This mixin is rather simple and is generally the first inherited class in any vi
def get(self, request):
return self.render_to_response({})

An optional class attribute of ``redirect_unauthenticated_users`` can be set to ``True`` if you are using another ``access`` mixin with ``raise_exception`` set to ``True``. This will redirect to the login page if the user is not authenticated, but raises an exception if they are but do not have the required access defined by the other mixins. This defaults to ``False``.

.. _PermissionRequiredMixin:

PermissionRequiredMixin
Expand Down
8 changes: 8 additions & 0 deletions tests/test_access_mixins.py
Expand Up @@ -147,6 +147,14 @@ def test_authenticated(self):
assert resp.status_code == 200
assert force_text(resp.content) == 'OK'

def test_anonymous_redirects(self):
resp = self.dispatch_view(
self.build_request(path=self.view_url),
raise_exception=True,
redirect_unauthenticated_users=True)
assert resp.status_code == 302
assert resp['Location'] == '/accounts/login/?next=/login_required/'


class TestAnonymousRequiredMixin(TestViewHelper, test.TestCase):
"""
Expand Down