4. Limiting access to logged-in users¶
4.1. The raw way¶
The simple, raw way to limit access to pages is to check
request.user.is_authenticated()
and either redirect to a login page or display an error message. This is largely
based off of django’s User.is_authenticated() method.
from django.http import HttpResponseRedirect
def my_view(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/?next=%s' % request.path)
# ...
4.2. The login_required decorator¶
You can limit access to logged-in users using the
login_required()
decorator. The login_required decorator can be used in the same way that
the Django login_required decorator can be used but with some notable differences.
login_required()
can take no arguments in the same way that the
login_required() decorator for django auth does.
from newauth.decorators import login_required
@login_required
def my_view(request):
...
It also takes the same keyword arguments.
from newauth.decorators import login_required
@login_required(login_url="/mylogin", redirect_field_name="next_url")
def my_view(request):
...
However it also can take a list of backend names so that you can specify the specific backends that are required to execute that view.
from newauth.decorators import login_required
@login_required(["default", "backend2"])
def my_view(request):
...
We’ll tie everything we have set up so far in the next section by adding the settings to make a working example.