Package: django-magic-link
Django Magic LinkOpinionated Django app for managing "magic link" logins.WARNINGIf you send a login link to the wrong person, they will gain full access
to the user's account. Use with extreme caution, and do not use this
package without reading the source code and ensuring that you are
comfortable with it. If you have an internal security team, ask them to
look at it before using it. If your clients have security sign-off on
your application, ask them to look at it before using it./WARNINGThis app is not intended for general purpose URL tokenisation; it is
designed to support a single use case - so-called "magic link" logins.There are lots of alternative apps that can support this use case,
including the project from which this has been extracted -django-request-token.
The reason for yet another one is to handle the real-world challenge of
URL caching / pre-fetch, where intermediaries use URLs with unintended
consequences.This packages supports a very specific model:User is sent a link to log them in automatically.User clicks on the link, and which does a GET request to the URL.User is presented with a confirmation page, but isnotlogged in.User clicks on a button and performs a POST to the same page.The POST request authenticates the user, and deactivates the token.The advantage of this is the email clients do not support POST links,
and any prefetch that attempts a POST will fail the CSRF checks.The purpose is to ensure that someone actively, purposefully, clicked on
a link to authenticate themselves. This enables instant deactivation of
the token, so that it can no longer be used.In practice, without this check, valid magic links may be requested a
number of times via GET request before the intended recipient even sees
the link. If you use a "max uses" restriction to lock down the link you
may find this limit is hit, and the end user then finds that the link is
inactive. The alternative to this is to remove the use limit and rely
instead on an expiry window. This risks leaving the token active even
after the user has logged in. This package is targeted at this
situation.UsePrerequisite: Update settings.py and urls.pyAddmagic_linkto INSTALLED_APPS in settings.py:INSTALLED_APPS=[...'magic_link',]Add themagic_linkurls to urls.py:frommagic_linkimporturlsasmagic_link_urlsurlpatterns=[...url(r'^magic_link/',include(magic_link_urls)),]Prerequisite: Override the default templates.This package has two HTML templates that must be overridden in your
local application.templates/magic_link/logmein.htmlThis is the landing page that a user sees when they click on the magic
link. You can add any content you like to this page - the only
requirement is that must contains a simple form with a csrf token and a
submit button. This form must POST back to the link URL. The template
render context includes thelinkwhich has aget_absolute_urlmethod
to simplify this:<formmethod="POST"action="{{ link.get_absolute_url }}">{% csrf_token %}<buttontype="submit">Log me in</button></form>templates/magic_link/error.htmlIf the link has expired, been used, or is being accessed by someone who
is already logged in, then theerror.htmltemplate will be rendered.
The template context includeslinkanderror.<p>Error handling magic link {{ link }}: {{ error }}.</p>1. Create a new login linkThe first step in managing magic links is to create one. Links are bound
to a user, and can have a custom post-login redirect URL.# create a link with the default expiry and redirectlink=MagicLink.objects.create(user=user)# create a link with a specific redirectlink=MagicLink.objects.create(user=user,redirect_to="/foo")# construct a full URL from a MagicLink object and a Django HttpResponseurl=request.build_absolute_uri(link.get_absolute_url())2. Send the link to the userThis package does not handle the sending on your behalf - it is your
responsibility to ensure that you send the link to the correct user. If
you send the link to the wrong user, they will have full access to the
link user's account.YOU HAVE BEEN WARNED.AuditingA core requirement of this package is to be able to audit the use of
links - for monitoring and analysis. To enable this we have a second
model,MagicLinkUse, and we create a new object for every request to a
link URL,regardless of outcome. Questions that we want to have
answers for include:How long does it take for users to click on a link?How many times is a link used before the POST login?How often is a link usedaftera successful login?How often does a link expire before a successful login?Can we identify common non-user client requests (email caches, bots, etc)?Should we disable links after X non-POST requests?In order to facilitate this analysis we denormalise a number of
timestamps from theMagicLinkUseobject back onto theMagicLinkitself:created_at- when the record was created in the databaseaccessed_at- the first GET request to the link URLlogged_in_at- the successful POSTexpires_at- the link expiry, set when the link is created.Note that the expiry timestamp isnotupdated when the link is used.
This is by design, to retain the original expiry timestamp.Link validationIn addition to the timestamp fields, there is a separate boolean flag,is_active. This acts as a "kill switch" that overrides any other
attribute, and it allows a link to be disabled without having to edit
(or destroy) existing timestamp values. You can deactivate all links in
one hit by callingMagicLink.objects.deactivate().A link'sis_validproperty combines bothis_activeand timestamp
data to return a bool value that defines whether a link can used, based
on the following criteria:The link is active (is_active)The link has not expired (expires_at)The link has not already been used (logged_in_at)In addition to checking the propertyis_valid, thevalidate()method
will raise an exception based on the specific condition that failed.
This is used by the link view to give feedback to the user on the nature
of the failure.Request authorizationIf the link'sis_validproperty returnsTrue, then the linkcanbe
used. However, this does not mean that the link can be used by anyone.
We do not allow authenticated users to login using someone else's magic
link. Theauthorize()method takes aUserargument and determines
whether they are authorized to use the link. If the user is
authenticated, and does not match thelink.user, then aPermissionDeniedexception is raised.Putting it togetherCombining the validation, authorization and auditing, we get a
simplified flow that looks something like this:defget(request,token):"""Render login page."""link=get_object_or_404(MagicLink,token=token)link.validate()link.authorize(request.user)link.audit()returnrender("logmein.html")defpost(request,token):"""Handle the login POST."""link=get_object_or_404(MagicLink,token=token)link.validate()link.authorize(request.user)link.login(request)link.disable()returnredirect(link.redirect_to)SettingsSettings are read from adjango.conf.settingssettings dictionary calledMAGIC_LINK.Default settings show below:# settings.pyMAGIC_LINK={# link expiry, in seconds"DEFAULT_EXPIRY":300,# default link redirect"DEFAULT_REDIRECT":"/",# the preferred authorization backend to use, in the case where you have more# than one specified in the `settings.AUTHORIZATION_BACKENDS` setting."AUTHENTICATION_BACKEND":"django.contrib.auth.backends.ModelBackend",# SESSION_COOKIE_AGE override for magic-link logins - in seconds (default is 1 week)"SESSION_EXPIRY":7*24*60*60}ScreenshotsDefault landing page (logmein.html)Default error page (error.html)Admin view of magic link uses