Coverage for documents/management/commands/manage_superuser.py: 75%

26 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 09:07 +0000

1import logging 

2import os 

3from argparse import RawTextHelpFormatter 

4 

5from django.contrib.auth.models import User 

6from django.core.management.base import BaseCommand 

7 

8logger = logging.getLogger("paperless.management.superuser") 

9 

10 

11class Command(BaseCommand): 

12 help = ( 

13 "Creates a Django superuser:\n" 

14 " User named: admin\n" 

15 " Email: root@localhost\n" 

16 " Password: based on env variable PAPERLESS_ADMIN_PASSWORD\n" 

17 "No superuser will be created, when:\n" 

18 " - The username is taken already exists\n" 

19 " - A superuser already exists\n" 

20 " - PAPERLESS_ADMIN_PASSWORD is not set" 

21 ) 

22 

23 def create_parser(self, *args, **kwargs): 

24 parser = super().create_parser(*args, **kwargs) 

25 parser.formatter_class = RawTextHelpFormatter 

26 return parser 

27 

28 def handle(self, *args, **options) -> None: 

29 username = os.getenv("PAPERLESS_ADMIN_USER", "admin") 

30 mail = os.getenv("PAPERLESS_ADMIN_MAIL", "root@localhost") 

31 password = os.getenv("PAPERLESS_ADMIN_PASSWORD") 

32 

33 # Check if there's already a user called admin 

34 if User.objects.filter(username=username).exists(): 34 ↛ 35line 34 didn't jump to line 35 because the condition on line 34 was never true

35 self.stdout.write( 

36 self.style.NOTICE( 

37 f"Did not create superuser, a user {username} already exists", 

38 ), 

39 ) 

40 return 

41 

42 # Check if any superuseruser 

43 # exists already, leave as is if it does 

44 if User.objects.filter(is_superuser=True).count() > 0: 44 ↛ 45line 44 didn't jump to line 45 because the condition on line 44 was never true

45 self.stdout.write( 

46 self.style.NOTICE( 

47 "Did not create superuser, the DB already contains superusers", 

48 ), 

49 ) 

50 return 

51 

52 if password is None: 52 ↛ 53line 52 didn't jump to line 53 because the condition on line 52 was never true

53 self.stdout.write( 

54 self.style.ERROR( 

55 "Please check if PAPERLESS_ADMIN_PASSWORD has been" 

56 " set in the environment", 

57 ), 

58 ) 

59 else: 

60 # Create superuser with password based on env variable 

61 User.objects.create_superuser(username, mail, password) 

62 self.stdout.write( 

63 self.style.SUCCESS( 

64 f'Created superuser "{username}" with provided password.', 

65 ), 

66 )