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

Add next query param with original request URL in requires decorator #920

Merged
merged 2 commits into from
Feb 16, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,29 @@ async def dashboard(request):
...
```

When redirecting users, the page you redirect them to will include URL they originally requested at the `next` query param:

```python
from starlette.authentication import requires
from starlette.responses import RedirectResponse


@requires('authenticated', redirect='login')
async def admin(request):
...


async def login(request):
if request.method == "POST":
# Now that the user is authenticated,
# we can send them to their original request destination
if request.user.is_authenticated:
next_url = request.query_params.get("next")
if next_url:
return RedirectResponse(next_url)
return RedirectResponse("/")
```

For class-based endpoints, you should wrap the decorator
around a method on the class.

Expand Down
15 changes: 11 additions & 4 deletions starlette/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import functools
import inspect
import typing
from urllib.parse import urlencode

from starlette.exceptions import HTTPException
from starlette.requests import HTTPConnection, Request
Expand Down Expand Up @@ -63,9 +64,12 @@ async def async_wrapper(

if not has_required_scope(request, scopes_list):
if redirect is not None:
return RedirectResponse(
url=request.url_for(redirect), status_code=303
orig_request_qparam = urlencode({"next": str(request.url)})
next_url = "{redirect_path}?{orig_request}".format(
redirect_path=request.url_for(redirect),
orig_request=orig_request_qparam,
)
return RedirectResponse(url=next_url, status_code=303)
raise HTTPException(status_code=status_code)
return await func(*args, **kwargs)

Expand All @@ -80,9 +84,12 @@ def sync_wrapper(*args: typing.Any, **kwargs: typing.Any) -> Response:

if not has_required_scope(request, scopes_list):
if redirect is not None:
return RedirectResponse(
url=request.url_for(redirect), status_code=303
orig_request_qparam = urlencode({"next": str(request.url)})
next_url = "{redirect_path}?{orig_request}".format(
redirect_path=request.url_for(redirect),
orig_request=orig_request_qparam,
)
return RedirectResponse(url=next_url, status_code=303)
raise HTTPException(status_code=status_code)
return func(*args, **kwargs)

Expand Down
11 changes: 9 additions & 2 deletions tests/test_authentication.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import base64
import binascii
from urllib.parse import urlencode

import pytest

Expand Down Expand Up @@ -305,15 +306,21 @@ def test_authentication_redirect(test_client_factory):
with test_client_factory(app) as client:
response = client.get("/admin")
assert response.status_code == 200
assert response.url == "http://testserver/"
url = "{}?{}".format(
"http://testserver/", urlencode({"next": "http://testserver/admin"})
)
assert response.url == url

response = client.get("/admin", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}

response = client.get("/admin/sync")
assert response.status_code == 200
assert response.url == "http://testserver/"
url = "{}?{}".format(
"http://testserver/", urlencode({"next": "http://testserver/admin/sync"})
)
assert response.url == url

response = client.get("/admin/sync", auth=("tomchristie", "example"))
assert response.status_code == 200
Expand Down