Skip to content

Commit

Permalink
allow login require to redirect to a default location
Browse files Browse the repository at this point in the history
  • Loading branch information
Dusty Phillips committed Mar 25, 2012
1 parent f0e89b5 commit a1dad52
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
5 changes: 4 additions & 1 deletion README.md
Expand Up @@ -52,7 +52,10 @@ to access user data. The auth module also contains login, logout, and login_requ
* logout(request)
* login_required(request, "/login/page.html")

The latter will raise an appropriate redirect response if the user is not authenticated.
The latter will raise an appropriate redirect response if the user is not
authenticated. If you do not specify a redirect url, it will redirect to
trembling.auth.LOGIN_URL. This defaults to /account/login.html, or you can set
it to a string of your choice in an aspen startup hook.

For an example of how these modules can be used in practice, see
[Todoy](https://github.com/buchuki/Todoy)
Expand Down
5 changes: 4 additions & 1 deletion trembling/auth.py
Expand Up @@ -11,6 +11,7 @@
SALT_LENGTH = 23
SALT_CHARACTERS = string.ascii_letters + string.digits
AUTH_SESSION_KEY = "auth_user_id"
LOGIN_URL = "/account/login.html"


class User(Document):
Expand Down Expand Up @@ -58,10 +59,12 @@ def logout(request):
request.session = {SESSION_COOKIE_NAME: key}


def login_required(request, login_url):
def login_required(request, login_url=None):
'''if a user is not logged in, redirect to the login url.
Assumes that inbound has already been called on the request.'''
if not request.authenticated:
if login_url is None:
login_url = LOGIN_URL
raise Redirect(login_url)
else:
return True
Expand Down
12 changes: 9 additions & 3 deletions trembling/tests/test_auth.py
Expand Up @@ -67,12 +67,18 @@ def test_logout(mongodb, user, request):
def test_login_required(mongodb, request):
inbound(request)
with raises(Redirect) as exc:
login_required(request, "/accounts/login.html")
assert exc.value.headers.one("Location") == "/accounts/login.html"
login_required(request, "/login.html")
assert exc.value.headers.one("Location") == "/login.html"


def test_authenticated_user_passes(mongodb, user, request):
request.session['auth_user_id'] = "Paul"
inbound(request)
login_required(request, "/accounts/login.html")
login_required(request, "/login.html")
# If we got this far, great!

def test_login_required_no_url(mongodb, request):
inbound(request)
with raises(Redirect) as exc:
login_required(request)
assert exc.value.headers.one("Location") == "/account/login.html"

0 comments on commit a1dad52

Please sign in to comment.