devicehub-django/user/management/commands/add_user.py

46 lines
1.6 KiB
Python
Raw Permalink Normal View History

2024-09-27 12:23:25 +00:00
from uuid import uuid4
2024-07-01 10:19:02 +00:00
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
2024-09-17 15:28:14 +00:00
from user.models import Institution
2024-09-27 12:23:25 +00:00
from api.models import Token
2024-07-01 10:19:02 +00:00
User = get_user_model()
class Command(BaseCommand):
help = "Create a new user"
def add_arguments(self, parser):
2024-09-17 15:28:14 +00:00
parser.add_argument('institution', type=str, help='institution')
2024-07-01 10:19:02 +00:00
parser.add_argument('email', type=str, help='email')
parser.add_argument('password', type=str, help='password')
2024-10-07 14:57:26 +00:00
parser.add_argument('is_admin', nargs='?', default=False, type=str, help='is admin')
parser.add_argument('predefined_token', nargs='?', default='', type=str, help='predefined token')
2024-07-01 10:19:02 +00:00
def handle(self, *args, **kwargs):
email = kwargs['email']
password = kwargs['password']
2024-10-07 14:57:26 +00:00
is_admin = kwargs['is_admin']
predefined_token = kwargs['predefined_token']
2024-09-17 15:28:14 +00:00
institution = Institution.objects.get(name=kwargs['institution'])
self.create_user(institution, email, password, is_admin, predefined_token)
2024-07-01 10:19:02 +00:00
def create_user(self, institution, email, password, is_admin, predefined_token):
2024-09-17 15:28:14 +00:00
self.u = User.objects.create(
institution=institution,
email=email,
2024-10-07 14:57:26 +00:00
password=password,
is_admin=is_admin,
2024-09-17 15:28:14 +00:00
)
2024-10-10 10:28:03 +00:00
self.u.set_password(password)
2024-07-18 15:21:22 +00:00
self.u.save()
if predefined_token:
token = predefined_token
else:
token = uuid4()
2024-09-27 12:23:25 +00:00
Token.objects.create(token=token, owner=self.u)
print(f"TOKEN: {token}")