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
|
2024-04-23 20:58:26 +02:00
|
|
|
import os
|
|
|
|
import sys
|
2024-05-24 15:55:37 +02:00
|
|
|
from argparse import ArgumentParser, BooleanOptionalAction, RawTextHelpFormatter, _ActionsContainer
|
2022-03-21 05:32:38 +01:00
|
|
|
from dataclasses import dataclass
|
2024-04-23 20:58:26 +02:00
|
|
|
from functools import reduce, wraps
|
|
|
|
from typing import Any, Dict, Optional, Protocol
|
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
|
2023-08-03 22:20:37 +02:00
|
|
|
from django.db.models import Q, QuerySet
|
2023-10-12 19:43:45 +02:00
|
|
|
from typing_extensions import override
|
2017-07-07 20:35:31 +02:00
|
|
|
|
2024-04-23 20:58:26 +02:00
|
|
|
from zerver.lib.context_managers import lockfile_nonblocking
|
2022-03-21 05:32:38 +01:00
|
|
|
from zerver.lib.initial_password import initial_password
|
2023-12-15 04:33:19 +01:00
|
|
|
from zerver.models import Client, Realm, UserProfile
|
|
|
|
from zerver.models.clients import get_client
|
2020-06-11 00:54:34 +02:00
|
|
|
|
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:
|
2023-02-02 04:35:24 +01:00
|
|
|
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
|
|
|
|
2024-04-23 20:58:26 +02:00
|
|
|
class HandleMethod(Protocol):
|
|
|
|
def __call__(self, *args: Any, **kwargs: Any) -> None: ...
|
|
|
|
|
|
|
|
|
|
|
|
def abort_unless_locked(handle_func: HandleMethod) -> HandleMethod:
|
|
|
|
@wraps(handle_func)
|
|
|
|
def our_handle(self: BaseCommand, *args: Any, **kwargs: Any) -> None:
|
|
|
|
os.makedirs(settings.LOCKFILE_DIRECTORY, exist_ok=True)
|
|
|
|
# Trim out just the last part of the module name, which is the
|
|
|
|
# command name, to use as the lockfile name;
|
|
|
|
# `zerver.management.commands.send_zulip_update_announcements`
|
|
|
|
# becomes `/srv/zulip-locks/send_zulip_update_announcements.lock`
|
|
|
|
lockfile_name = handle_func.__module__.split(".")[-1]
|
|
|
|
lockfile_path = settings.LOCKFILE_DIRECTORY + "/" + lockfile_name + ".lock"
|
|
|
|
with lockfile_nonblocking(lockfile_path) as lock_acquired:
|
|
|
|
if not lock_acquired: # nocoverage
|
|
|
|
self.stdout.write(
|
|
|
|
self.style.ERROR(f"Lock {lockfile_path} is unavailable; exiting.")
|
|
|
|
)
|
|
|
|
sys.exit(1)
|
|
|
|
handle_func(self, *args, **kwargs)
|
|
|
|
|
|
|
|
return our_handle
|
|
|
|
|
|
|
|
|
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
|
2023-10-12 19:43:45 +02:00
|
|
|
@override
|
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)
|
2024-05-24 15:55:37 +02:00
|
|
|
parser.add_argument(
|
|
|
|
"--automated",
|
|
|
|
help="This command is run non-interactively (enables Sentry, etc)",
|
|
|
|
action=BooleanOptionalAction,
|
|
|
|
default=not sys.stdin.isatty(),
|
|
|
|
)
|
2019-01-09 19:39:29 +01:00
|
|
|
parser.formatter_class = RawTextHelpFormatter
|
|
|
|
return parser
|
|
|
|
|
2024-05-24 15:55:37 +02:00
|
|
|
@override
|
|
|
|
def execute(self, *args: Any, **options: Any) -> None:
|
|
|
|
if settings.SENTRY_DSN and not options["automated"]: # nocoverage
|
|
|
|
import sentry_sdk
|
|
|
|
|
|
|
|
# This deactivates Sentry
|
|
|
|
sentry_sdk.init()
|
|
|
|
super().execute(*args, **options)
|
|
|
|
|
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,
|
2023-08-03 21:57:13 +02:00
|
|
|
parser: _ActionsContainer,
|
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,
|
2023-08-03 22:20:37 +02:00
|
|
|
) -> QuerySet[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:
|
2023-08-03 22:20:37 +02:00
|
|
|
return UserProfile.objects.none()
|
2020-04-09 21:51:58 +02:00
|
|
|
emails = {email.strip() for email in options["users"].split(",")}
|
2023-08-03 22:20:37 +02:00
|
|
|
# This is inefficient, but we fetch (and throw away) the
|
|
|
|
# get_user of each email, so that we verify that the email
|
|
|
|
# address/realm returned only one result; it may return more
|
|
|
|
# if realm is not specified but email address was.
|
|
|
|
for email in emails:
|
|
|
|
self.get_user(email, realm)
|
|
|
|
|
|
|
|
user_profiles = UserProfile.objects.all().select_related("realm")
|
|
|
|
if realm is not None:
|
|
|
|
user_profiles = user_profiles.filter(realm=realm)
|
|
|
|
email_matches = [Q(delivery_email__iexact=e) for e in emails]
|
2023-08-21 20:19:35 +02:00
|
|
|
user_profiles = user_profiles.filter(reduce(lambda a, b: a | b, email_matches)).order_by(
|
|
|
|
"id"
|
|
|
|
)
|
2023-08-03 22:20:37 +02:00
|
|
|
|
|
|
|
# Return the single query, for ease of composing.
|
|
|
|
return user_profiles
|
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:
|
2023-07-13 16:59:30 +02:00
|
|
|
return UserProfile.objects.select_related("realm").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:
|
2023-07-13 16:59:30 +02:00
|
|
|
return UserProfile.objects.select_related("realm").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(
|
2023-01-03 02:16:53 +01:00
|
|
|
"This Zulip server contains multiple users with that email (in different realms);"
|
|
|
|
" please pass `--realm` to specify which one to modify."
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
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,
|
|
|
|
)
|