Identity - Django View that accepts both Auth and Non-Auth users
I have integrated Azure AD with Django using identity[django] package (docs).
It provides a @login_required
decorator that is used to restrict a view only for AD authenticated users. The view function decorated should accept an additional parameter context
which contains the AD info.
I have written a custom decorator that creates a Django User object using the AD info provided by identity context.
def custom_login_required(f):
@wraps(f)
@settings.AUTH.login_required
def wrapped(request, context=None, *args, **kwargs):
if context:
request.user = get_ad_synced_user(context)
return f(request, context=context, *args, **kwargs)
return wrapped
@custom_login_required
def home(request, *, context):
return render(request, 'home.html')
<html>
<body>
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% endif %}
</body>
</html>
However, I want to create a view that accepts both authenticated and non-authenticated users. If the user is not authenticated, it should display a link to login page, and if the user is authenticated, then it should display private links.
Using the Django User object, I can have access to request.user.is_authenticated
, but since identity creates a separate object context
(which gets AD info only when decorated with @login_required
), I'm not sure how I can set request.user
for the current request from the previous request.