Last active
April 5, 2021 09:29
-
-
Save jefftriplett/e87b36d750f94e48080a2be46e71dbe1 to your computer and use it in GitHub Desktop.
Django Management Command to print a "Magic Link" for one-click log-in. This is nice for people who project switch or don't want to remember passwords.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Django Management Command to print a "Magic Link" for one-click login | |
by Jeff Triplett <jefftriplett> / https://twitter.com/webology | |
https://gist.github.com/jefftriplett/e87b36d750f94e48080a2be46e71dbe1 | |
Relies on: https://github.com/aaugustin/django-sesame | |
$ pip install django-click | |
$ pip install django-sesame[ua] | |
This should live in one of your app that is installed in your `settings.INSTALLED_APPS` | |
/management/commands/magic-link.py | |
Example: | |
$ python manage.py magic-link | |
http://localhost:8000/?sesame=AAAAAZXgFCVouyZCceM | |
""" | |
import djclick as click | |
from django.contrib.auth import get_user_model | |
from django.contrib.sites.models import Site | |
from sesame.utils import get_query_string | |
@click.command() | |
@click.option("username", "--user", default=None) | |
def command(username): | |
User = get_user_model() | |
if username: | |
try: | |
user = User.objects.get(username=username) | |
except User.DoesNotExist: | |
user = None | |
else: | |
user = User.objects.first() | |
domain_name = Site.objects.get_current() | |
if user: | |
click.echo(f"http://{domain_name}/{get_query_string(user)}") | |
else: | |
click.secho(f"No user or username was found", fg="red") |
I don't, but I probably will going forward. It's optional so it's going to fetch the first user or which every you pass in with. python manage.py magic-link --user=admin
This is mostly for convenience.
Added to Django Snippets too: https://djangosnippets.org/snippets/10855/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So do you run this command with arguments for the username of the user?