2828from django .core .management .base import BaseCommand
2929from django .core .management .base import CommandError
3030
31- from rest_framework . authtoken . models import Token
31+ from scanpipe . models import APIToken
3232
3333
3434class Command (BaseCommand ):
@@ -43,13 +43,21 @@ def __init__(self, *args, **kwargs):
4343 )
4444
4545 def add_arguments (self , parser ):
46- parser .add_argument ("username" , help = "Specifies the username for the user." )
46+ parser .add_argument (
47+ "username" ,
48+ help = f"Specifies the { self .UserModel .USERNAME_FIELD } for the user." ,
49+ )
4750 parser .add_argument (
4851 "--no-input" ,
4952 action = "store_false" ,
5053 dest = "interactive" ,
5154 help = "Do not prompt the user for input of any kind." ,
5255 )
56+ parser .add_argument (
57+ "--generate-api-key" ,
58+ action = "store_true" ,
59+ help = "Generate an API key for this user and print it to the console." ,
60+ )
5361 parser .add_argument (
5462 "--admin" ,
5563 action = "store_true" ,
@@ -63,9 +71,16 @@ def add_arguments(self, parser):
6371
6472 def handle (self , * args , ** options ):
6573 username = options ["username" ]
74+ generate_api_key = options ["generate_api_key" ]
6675 is_admin = options ["admin" ]
6776 is_superuser = options ["super" ]
6877
78+ if options ["verbosity" ] <= 0 and generate_api_key :
79+ raise CommandError (
80+ "Cannot display the API key with verbosity disabled. "
81+ "The key is only shown once at generation time."
82+ )
83+
6984 error_msg = self ._validate_username (username )
7085 if error_msg :
7186 raise CommandError (error_msg )
@@ -75,19 +90,27 @@ def handle(self, *args, **options):
7590 password = self .get_password_from_stdin (username )
7691
7792 user_kwargs = {
78- "username" : username ,
93+ self . UserModel . USERNAME_FIELD : username ,
7994 "password" : password ,
8095 "is_staff" : is_admin or is_superuser ,
8196 "is_superuser" : is_superuser ,
8297 }
83-
8498 user = self .UserModel ._default_manager .create_user (** user_kwargs )
85- token , _ = Token ._default_manager .get_or_create (user = user )
8699
87100 if options ["verbosity" ] > 0 :
88- msg = f"User { username } created with API key: { token . key } "
101+ msg = f"User { username } created. "
89102 self .stdout .write (msg , self .style .SUCCESS )
90103
104+ if generate_api_key :
105+ plain_api_key = APIToken .create_token (user = user )
106+ self .stdout .write (f"API key: { plain_api_key } " , self .style .SUCCESS )
107+ warning_msg = (
108+ "Treat your API key like a password and keep it secure. "
109+ "For security reasons, the key is only shown once at generation time. "
110+ "If you lose it, you will need to regenerate a new one."
111+ )
112+ self .stdout .write (warning_msg , self .style .WARNING )
113+
91114 def get_password_from_stdin (self , username ):
92115 # Validators, such as UserAttributeSimilarityValidator, depends on other user's
93116 # fields data for password validation.
0 commit comments