2017-07-07 20:35:31 +02:00
|
|
|
# Library code for use in management commands
|
2022-03-21 05:32:38 +01:00
|
|
|
import logging
|
2022-03-21 05:58:28 +01:00
|
|
|
from argparse import ArgumentParser, RawTextHelpFormatter
|
2022-03-21 05:32:38 +01:00
|
|
|
from dataclasses import dataclass
|
2022-06-23 20:07:19 +02:00
|
|
|
from typing import Any, Collection, Dict, Optional
|
2019-01-09 19:39:29 +01:00
|
|
|
|
2018-05-04 01:04:12 +02:00
|
|
|
from django.conf import settings
|
2022-03-21 05:32:38 +01:00
|
|
|
from django.core import validators
|
|
|
|
from django.core.exceptions import MultipleObjectsReturned, ValidationError
|
2021-08-14 16:51:57 +02:00
|
|
|
from django.core.management.base import BaseCommand, CommandError, CommandParser
|
2017-07-07 20:35:31 +02:00
|
|
|
|
2022-03-21 05:32:38 +01:00
|
|
|
from zerver.lib.initial_password import initial_password
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.models import Client, Realm, UserProfile, get_client
|
|
|
|
|
2017-07-07 20:35:31 +02:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def is_integer_string(val: str) -> bool:
|
2017-07-07 20:35:31 +02:00
|
|
|
try:
|
|
|
|
int(val)
|
|
|
|
return True
|
|
|
|
except ValueError:
|
|
|
|
return False
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2018-05-04 01:04:12 +02:00
|
|
|
def check_config() -> None:
|
|
|
|
for (setting_name, default) in settings.REQUIRED_SETTINGS:
|
2018-05-14 17:45:32 +02:00
|
|
|
# if required setting is the same as default OR is not found in settings,
|
|
|
|
# throw error to add/set that setting in config
|
2018-05-04 01:04:12 +02:00
|
|
|
try:
|
2022-10-08 07:35:48 +02:00
|
|
|
if getattr(settings, setting_name) != default:
|
2018-05-04 01:04:12 +02:00
|
|
|
continue
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
2020-06-10 06:41:04 +02:00
|
|
|
raise CommandError(f"Error: You must set {setting_name} in /etc/zulip/settings.py.")
|
2018-05-04 01:04:12 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2022-03-21 05:32:38 +01:00
|
|
|
@dataclass
|
|
|
|
class CreateUserParameters:
|
|
|
|
email: str
|
|
|
|
full_name: str
|
|
|
|
password: Optional[str]
|
|
|
|
|
|
|
|
|
2017-07-07 20:35:31 +02:00
|
|
|
class ZulipBaseCommand(BaseCommand):
|
2019-01-09 19:39:29 +01:00
|
|
|
|
|
|
|
# Fix support for multi-line usage
|
2021-08-14 16:51:57 +02:00
|
|
|
def create_parser(self, prog_name: str, subcommand: str, **kwargs: Any) -> CommandParser:
|
|
|
|
parser = super().create_parser(prog_name, subcommand, **kwargs)
|
2019-01-09 19:39:29 +01:00
|
|
|
parser.formatter_class = RawTextHelpFormatter
|
|
|
|
return parser
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def add_realm_args(
|
2021-05-10 21:29:25 +02:00
|
|
|
self, parser: ArgumentParser, *, required: bool = False, help: Optional[str] = None
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> None:
|
2017-08-07 17:03:33 +02:00
|
|
|
if help is None:
|
|
|
|
help = """The numeric or string ID (subdomain) of the Zulip organization to modify.
|
|
|
|
You can use the command list_realms to find ID of the realms in this server."""
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
parser.add_argument("-r", "--realm", dest="realm_id", required=required, help=help)
|
2017-07-07 20:35:31 +02:00
|
|
|
|
2022-03-21 04:32:20 +01:00
|
|
|
def add_create_user_args(self, parser: ArgumentParser) -> None:
|
|
|
|
parser.add_argument(
|
|
|
|
"email",
|
|
|
|
metavar="<email>",
|
|
|
|
nargs="?",
|
2022-03-21 04:36:29 +01:00
|
|
|
help="Email address for the new user",
|
2022-03-21 04:32:20 +01:00
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"full_name",
|
|
|
|
metavar="<full name>",
|
|
|
|
nargs="?",
|
2022-03-21 04:36:29 +01:00
|
|
|
help="Full name for the new user",
|
2022-03-21 04:32:20 +01:00
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--password",
|
2022-03-21 04:36:29 +01:00
|
|
|
help="""\
|
|
|
|
Password for the new user. Recommended only in a development environment.
|
|
|
|
|
|
|
|
Sending passwords via command-line arguments is insecure,
|
|
|
|
since it can be snooped by any process running on the
|
|
|
|
server via `ps -ef` or reading bash history. Prefer
|
|
|
|
--password-file.""",
|
2022-03-21 04:32:20 +01:00
|
|
|
)
|
2022-03-21 04:36:29 +01:00
|
|
|
parser.add_argument("--password-file", help="File containing a password for the new user.")
|
2022-03-21 04:32:20 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def add_user_list_args(
|
|
|
|
self,
|
|
|
|
parser: ArgumentParser,
|
2021-02-12 08:20:45 +01:00
|
|
|
help: str = "A comma-separated list of email addresses.",
|
2021-02-12 08:19:30 +01:00
|
|
|
all_users_help: str = "All users in realm.",
|
|
|
|
) -> None:
|
2021-02-12 08:20:45 +01:00
|
|
|
parser.add_argument("-u", "--users", help=help)
|
2017-08-19 21:00:19 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
parser.add_argument("-a", "--all-users", action="store_true", help=all_users_help)
|
2017-08-24 21:46:13 +02:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def get_realm(self, options: Dict[str, Any]) -> Optional[Realm]:
|
2017-07-07 20:35:31 +02:00
|
|
|
val = options["realm_id"]
|
|
|
|
if val is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
# If they specified a realm argument, we need to ensure the
|
|
|
|
# realm exists. We allow two formats: the numeric ID for the
|
|
|
|
# realm and the string ID of the realm.
|
|
|
|
try:
|
|
|
|
if is_integer_string(val):
|
|
|
|
return Realm.objects.get(id=val)
|
2017-07-07 23:39:55 +02:00
|
|
|
return Realm.objects.get(string_id=val)
|
2017-07-07 20:35:31 +02:00
|
|
|
except Realm.DoesNotExist:
|
2021-02-12 08:19:30 +01:00
|
|
|
raise CommandError(
|
|
|
|
"There is no realm with id '{}'. Aborting.".format(options["realm_id"])
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_users(
|
|
|
|
self,
|
|
|
|
options: Dict[str, Any],
|
|
|
|
realm: Optional[Realm],
|
|
|
|
is_bot: Optional[bool] = None,
|
|
|
|
include_deactivated: bool = False,
|
2022-06-23 20:07:19 +02:00
|
|
|
) -> Collection[UserProfile]:
|
2017-08-24 21:46:13 +02:00
|
|
|
if "all_users" in options:
|
|
|
|
all_users = options["all_users"]
|
|
|
|
|
2017-08-25 00:10:47 +02:00
|
|
|
if not options["users"] and not all_users:
|
|
|
|
raise CommandError("You have to pass either -u/--users or -a/--all-users.")
|
|
|
|
|
|
|
|
if options["users"] and all_users:
|
2017-08-24 21:46:13 +02:00
|
|
|
raise CommandError("You can't use both -u/--users and -a/--all-users.")
|
|
|
|
|
|
|
|
if all_users and realm is None:
|
|
|
|
raise CommandError("The --all-users option requires a realm; please pass --realm.")
|
|
|
|
|
|
|
|
if all_users:
|
2019-01-11 11:25:36 +01:00
|
|
|
user_profiles = UserProfile.objects.filter(realm=realm)
|
2019-08-14 19:48:54 +02:00
|
|
|
if not include_deactivated:
|
|
|
|
user_profiles = user_profiles.filter(is_active=True)
|
2019-01-11 11:25:36 +01:00
|
|
|
if is_bot is not None:
|
|
|
|
return user_profiles.filter(is_bot=is_bot)
|
|
|
|
return user_profiles
|
2017-08-24 21:46:13 +02:00
|
|
|
|
2017-08-19 21:00:19 +02:00
|
|
|
if options["users"] is None:
|
|
|
|
return []
|
2020-04-09 21:51:58 +02:00
|
|
|
emails = {email.strip() for email in options["users"].split(",")}
|
2022-06-23 20:21:54 +02:00
|
|
|
return [self.get_user(email, realm) for email in emails]
|
2017-08-19 21:00:19 +02:00
|
|
|
|
2018-05-11 01:40:23 +02:00
|
|
|
def get_user(self, email: str, realm: Optional[Realm]) -> UserProfile:
|
2017-07-07 20:35:31 +02:00
|
|
|
|
|
|
|
# If a realm is specified, try to find the user there, and
|
|
|
|
# throw an error if they don't exist.
|
|
|
|
if realm is not None:
|
|
|
|
try:
|
2018-12-07 00:05:57 +01:00
|
|
|
return UserProfile.objects.select_related().get(
|
2021-02-12 08:19:30 +01:00
|
|
|
delivery_email__iexact=email.strip(), realm=realm
|
|
|
|
)
|
2017-07-07 20:35:31 +02:00
|
|
|
except UserProfile.DoesNotExist:
|
2021-02-12 08:19:30 +01:00
|
|
|
raise CommandError(
|
|
|
|
f"The realm '{realm}' does not contain a user with email '{email}'"
|
|
|
|
)
|
2017-07-07 20:35:31 +02:00
|
|
|
|
|
|
|
# Realm is None in the remaining code path. Here, we
|
|
|
|
# optimistically try to see if there is exactly one user with
|
|
|
|
# that email; if so, we'll return it.
|
|
|
|
try:
|
2018-12-07 00:05:57 +01:00
|
|
|
return UserProfile.objects.select_related().get(delivery_email__iexact=email.strip())
|
2017-07-07 20:35:31 +02:00
|
|
|
except MultipleObjectsReturned:
|
2021-02-12 08:19:30 +01:00
|
|
|
raise CommandError(
|
|
|
|
"This Zulip server contains multiple users with that email "
|
|
|
|
+ "(in different realms); please pass `--realm` "
|
|
|
|
"to specify which one to modify."
|
|
|
|
)
|
2017-07-07 20:35:31 +02:00
|
|
|
except UserProfile.DoesNotExist:
|
2020-06-10 06:41:04 +02:00
|
|
|
raise CommandError(f"This Zulip server does not contain a user with email '{email}'")
|
2018-03-14 00:25:31 +01:00
|
|
|
|
|
|
|
def get_client(self) -> Client:
|
|
|
|
"""Returns a Zulip Client object to be used for things done in management commands"""
|
|
|
|
return get_client("ZulipServer")
|
2022-03-21 05:32:38 +01:00
|
|
|
|
|
|
|
def get_create_user_params(self, options: Dict[str, Any]) -> CreateUserParameters: # nocoverage
|
|
|
|
"""
|
|
|
|
Parses parameters for user creation defined in add_create_user_args.
|
|
|
|
"""
|
2022-03-21 05:58:28 +01:00
|
|
|
if options["email"] is None:
|
2022-03-21 05:32:38 +01:00
|
|
|
email = input("Email: ")
|
|
|
|
else:
|
|
|
|
email = options["email"]
|
|
|
|
|
|
|
|
try:
|
|
|
|
validators.validate_email(email)
|
|
|
|
except ValidationError:
|
|
|
|
raise CommandError("Invalid email address.")
|
|
|
|
|
2022-03-21 05:58:28 +01:00
|
|
|
if options["full_name"] is None:
|
2022-03-21 05:32:38 +01:00
|
|
|
full_name = input("Full name: ")
|
|
|
|
else:
|
|
|
|
full_name = options["full_name"]
|
|
|
|
|
|
|
|
if options["password_file"] is not None:
|
|
|
|
with open(options["password_file"]) as f:
|
|
|
|
password: Optional[str] = f.read().strip()
|
|
|
|
elif options["password"] is not None:
|
|
|
|
logging.warning(
|
|
|
|
"Passing password on the command line is insecure; prefer --password-file."
|
|
|
|
)
|
|
|
|
password = options["password"]
|
|
|
|
else:
|
|
|
|
# initial_password will return a random password that
|
|
|
|
# is a salted hash of the email address in a
|
|
|
|
# development environment, and None in a production
|
|
|
|
# environment.
|
|
|
|
user_initial_password = initial_password(email)
|
|
|
|
if user_initial_password is None:
|
|
|
|
logging.info("User will be created with a disabled password.")
|
|
|
|
else:
|
|
|
|
assert settings.DEVELOPMENT
|
|
|
|
logging.info("Password will be available via `./manage.py print_initial_password`.")
|
|
|
|
password = user_initial_password
|
|
|
|
|
|
|
|
return CreateUserParameters(
|
|
|
|
email=email,
|
|
|
|
full_name=full_name,
|
|
|
|
password=password,
|
|
|
|
)
|