Protect Your Views
Learn how the auth decorator can be used to protect authenticated views.
Previously, during the Wristband SDK setup, we created an auth decorator named require_session. This section explains how to use it to ensure that protected views are accessible only to authenticated users.
Redirect Behavior for Template ViewsSince this guide uses server-side templates, the decorator is configured with
UnauthenticatedBehavior.REDIRECT, which redirects unauthenticated users to your Login Endpoint. For API views that return JSON, you would create an additional decorator that usesUnauthenticatedBehavior.JSONinstead to return a 401 Unauthorized response.
Using the Auth Decorator to Protect Views
Apply the require_session decorator to any view that requires authentication:
# your_app/protected_views.py
from django.shortcuts import render
from .wristband import require_session
@require_session
def dashboard(request):
"""Protected view - only accessible to authenticated users"""
return render(request, 'dashboard.html')When an unauthenticated user attempts to access a protected view, they'll be automatically redirected to your Login Endpoint.
Add Auth-Aware Rendering to Templates
For pages that allow unauthenticated access, you can display different content depending on the user's authentication status. To do so, create a view and retrieve the is_authenticated value from the session:
# your_app/views.py
def home(request):
"""Public home page with conditional UI"""
return render(request, 'home.html', {
'is_authenticated': request.session.get('is_authenticated', False),
'email': request.session.get('email'),
})Then use the is_authenticated variable in your template to render different content for authenticated and unauthenticated users. For example, you could show login links for unauthenticated users and logout links for authenticated users:
<!-- Example: your_app/templates/base.html -->
{% if is_authenticated %}
<p>Welcome, {{ email }}!</p>
<a href="{% url 'your_app:logout' %}">Logout</a>
{% else %}
<a href="{% url 'your_app:login' %}">Login</a>
{% endif %}Updated about 3 hours ago
Now that you've finished protecting your views, let's run some final tests to ensure everything is working.