Esempio n. 1
0
def do_resend_user_invite_email(prereg_user: PreregistrationUser) -> int:
    # These are two structurally for the caller's code path.
    assert prereg_user.referred_by is not None
    assert prereg_user.realm is not None

    check_invite_limit(prereg_user.referred_by.realm, 1)

    prereg_user.invited_at = timezone_now()
    prereg_user.save()

    expiry_date = prereg_user.confirmation.get().expiry_date
    if expiry_date is None:
        invite_expires_in_minutes = None
    else:
        # The resent invitation is reset to expire as long after the
        # reminder is sent as it lasted originally.
        invite_expires_in_minutes = (
            expiry_date - prereg_user.invited_at).total_seconds() / 60
    prereg_user.confirmation.clear()

    do_increment_logging_stat(prereg_user.realm,
                              COUNT_STATS["invites_sent::day"], None,
                              prereg_user.invited_at)

    clear_scheduled_invitation_emails(prereg_user.email)
    # We don't store the custom email body, so just set it to None
    event = {
        "prereg_id": prereg_user.id,
        "referrer_id": prereg_user.referred_by.id,
        "email_language": prereg_user.referred_by.realm.default_language,
        "invite_expires_in_minutes": invite_expires_in_minutes,
    }
    queue_json_publish("invites", event)

    return datetime_to_timestamp(prereg_user.invited_at)
    def handle(self, *args: Any, **options: Any) -> None:
        duplicates = False
        realm = self.get_realm(options)
        assert realm is not None  # Should be ensured by parser

        if not options['emails']:
            self.print_help("./manage.py", "generate_invite_links")
            exit(1)

        for email in options['emails']:
            try:
                self.get_user(email, realm)
                print(email + ": There is already a user registered with that address.")
                duplicates = True
                continue
            except CommandError:
                pass

        if duplicates:
            return

        for email in options['emails']:
            try:
                email_allowed_for_realm(email, realm)
            except DomainNotAllowedForRealmError:
                if not options["force"]:
                    print("You've asked to add an external user '%s' to a closed realm '%s'." % (
                        email, realm.string_id))
                    print("Are you sure? To do this, pass --force.")
                    exit(1)

            prereg_user = PreregistrationUser(email=email, realm=realm)
            prereg_user.save()
            print(email + ": " + create_confirmation_link(prereg_user, realm.host,
                                                          Confirmation.INVITATION))
Esempio n. 3
0
    def handle(self, *args, **options):
        # type: (*Any, **Any) -> None
        duplicates = False
        for email in options['emails']:
            try:
                get_user_profile_by_email(email)
                print(
                    email +
                    ": There is already a user registered with that address.")
                duplicates = True
                continue
            except UserProfile.DoesNotExist:
                pass

        if duplicates:
            return

        realm = None
        string_id = options["string_id"]
        if string_id:
            realm = get_realm_by_string_id(string_id)
        if not realm:
            print("The realm %s doesn't exist yet, please create it first." %
                  (string_id, ))
            print("Don't forget default streams!")
            exit(1)

        for email in options['emails']:
            if realm:
                if not email_allowed_for_realm(email,
                                               realm) and not options["force"]:
                    print(
                        "You've asked to add an external user (%s) to a closed realm (%s)."
                        % (email, string_id))
                    print("Are you sure? To do this, pass --force.")
                    exit(1)
                else:
                    prereg_user = PreregistrationUser(email=email, realm=realm)
            else:
                prereg_user = PreregistrationUser(email=email)
            prereg_user.save()
            print(email + ": " + Confirmation.objects.get_link_for_object(
                prereg_user, host=realm.host))
Esempio n. 4
0
    def handle(self, *args, **options):
        duplicates = False
        for email in options['emails']:
            try:
                get_user_profile_by_email(email)
                print(
                    email +
                    ": There is already a user registered with that address.")
                duplicates = True
                continue
            except UserProfile.DoesNotExist:
                pass

        if duplicates:
            return

        realm = None
        domain = options["domain"]
        if domain:
            realm = get_realm(domain)
        if not realm:
            print("The realm %s doesn't exist yet, please create it first." %
                  (domain, ))
            print("Don't forget default streams!")
            exit(1)

        for email in options['emails']:
            if realm:
                if realm.restricted_to_domain and \
                        domain.lower() != email.split("@", 1)[-1].lower() and \
                        not options["force"]:
                    print(
                        "You've asked to add an external user (%s) to a closed realm (%s)."
                        % (email, domain))
                    print("Are you sure? To do this, pass --force.")
                    exit(1)
                else:
                    prereg_user = PreregistrationUser(email=email, realm=realm)
            else:
                prereg_user = PreregistrationUser(email=email)
            prereg_user.save()
            print(email + ": " +
                  Confirmation.objects.get_link_for_object(prereg_user))
Esempio n. 5
0
    def handle(self, *args, **options):
        duplicates = False
        for email in options['emails']:
            try:
                get_user_profile_by_email(email)
                print email + ": There is already a user registered with that address."
                duplicates = True
                continue
            except UserProfile.DoesNotExist:
                pass

        if duplicates:
            return

        realm = None
        domain = options["domain"]
        if domain:
            realm = get_realm(domain)
        if not realm:
            print "The realm %s doesn't exist yet, please create it first." % (domain,)
            print "Don't forget default streams!"
            exit(1)

        for email in options['emails']:
            if realm:
                if realm.restricted_to_domain and \
                        domain.lower() != email.split("@", 1)[-1].lower() and \
                        not options["force"]:
                    print "You've asked to add an external user (%s) to a closed realm (%s)." % (
                        email, domain)
                    print "Are you sure? To do this, pass --force."
                    exit(1)
                else:
                    prereg_user = PreregistrationUser(email=email, realm=realm)
            else:
                prereg_user = PreregistrationUser(email=email)
            prereg_user.save()
            print email + ": " + Confirmation.objects.get_link_for_object(prereg_user)
Esempio n. 6
0
    def handle(self, *args, **options):
        # type: (*Any, **Any) -> None
        duplicates = False
        for email in options['emails']:
            try:
                get_user_profile_by_email(email)
                print(email + ": There is already a user registered with that address.")
                duplicates = True
                continue
            except UserProfile.DoesNotExist:
                pass

        if duplicates:
            return

        realm = None
        string_id = options["string_id"]
        if string_id:
            realm = get_realm(string_id)
        if not realm:
            print("The realm %s doesn't exist yet, please create it first." % (string_id,))
            print("Don't forget default streams!")
            exit(1)

        for email in options['emails']:
            if realm:
                if not email_allowed_for_realm(email, realm) and not options["force"]:
                    print("You've asked to add an external user (%s) to a closed realm (%s)." % (
                        email, string_id))
                    print("Are you sure? To do this, pass --force.")
                    exit(1)
                else:
                    prereg_user = PreregistrationUser(email=email, realm=realm)
            else:
                prereg_user = PreregistrationUser(email=email)
            prereg_user.save()
            print(email + ": " + Confirmation.objects.get_link_for_object(prereg_user, host=realm.host))
Esempio n. 7
0
    def handle(self, *args, **options):
        # type: (*Any, **Any) -> None
        duplicates = False
        realm = self.get_realm(options)

        if not options['emails']:
            self.print_help("./manage.py", "generate_invite_links")
            exit(1)

        for email in options['emails']:
            try:
                self.get_user(email, realm)
                print(
                    email +
                    ": There is already a user registered with that address.")
                duplicates = True
                continue
            except CommandError:
                pass

        if duplicates:
            return

        for email in options['emails']:
            if not email_allowed_for_realm(email,
                                           realm) and not options["force"]:
                print(
                    "You've asked to add an external user '%s' to a closed realm '%s'."
                    % (email, realm.string_id))
                print("Are you sure? To do this, pass --force.")
                exit(1)

            prereg_user = PreregistrationUser(email=email, realm=realm)
            prereg_user.save()
            print(email + ": " + Confirmation.objects.get_link_for_object(
                prereg_user, realm.host))
Esempio n. 8
0
def do_invite_users(
    user_profile: UserProfile,
    invitee_emails: Collection[str],
    streams: Collection[Stream],
    *,
    invite_expires_in_minutes: Optional[int],
    invite_as: int = PreregistrationUser.INVITE_AS["MEMBER"],
) -> None:
    num_invites = len(invitee_emails)

    check_invite_limit(user_profile.realm, num_invites)
    if settings.BILLING_ENABLED:
        from corporate.lib.registration import check_spare_licenses_available_for_inviting_new_users

        check_spare_licenses_available_for_inviting_new_users(
            user_profile.realm, num_invites)

    realm = user_profile.realm
    if not realm.invite_required:
        # Inhibit joining an open realm to send spam invitations.
        min_age = datetime.timedelta(days=settings.INVITES_MIN_USER_AGE_DAYS)
        if user_profile.date_joined > timezone_now(
        ) - min_age and not user_profile.is_realm_admin:
            raise InvitationError(
                _("Your account is too new to send invites for this organization. "
                  "Ask an organization admin, or a more experienced user."),
                [],
                sent_invitations=False,
            )

    good_emails: Set[str] = set()
    errors: List[Tuple[str, str, bool]] = []
    validate_email_allowed_in_realm = get_realm_email_validator(
        user_profile.realm)
    for email in invitee_emails:
        if email == "":
            continue
        email_error = validate_email_is_valid(
            email,
            validate_email_allowed_in_realm,
        )

        if email_error:
            errors.append((email, email_error, False))
        else:
            good_emails.add(email)
    """
    good_emails are emails that look ok so far,
    but we still need to make sure they're not
    gonna conflict with existing users
    """
    error_dict = get_existing_user_errors(user_profile.realm, good_emails)

    skipped: List[Tuple[str, str, bool]] = []
    for email in error_dict:
        msg, deactivated = error_dict[email]
        skipped.append((email, msg, deactivated))
        good_emails.remove(email)

    validated_emails = list(good_emails)

    if errors:
        raise InvitationError(
            _("Some emails did not validate, so we didn't send any invitations."
              ),
            errors + skipped,
            sent_invitations=False,
        )

    if skipped and len(skipped) == len(invitee_emails):
        # All e-mails were skipped, so we didn't actually invite anyone.
        raise InvitationError(_("We weren't able to invite anyone."),
                              skipped,
                              sent_invitations=False)

    # We do this here rather than in the invite queue processor since this
    # is used for rate limiting invitations, rather than keeping track of
    # when exactly invitations were sent
    do_increment_logging_stat(
        user_profile.realm,
        COUNT_STATS["invites_sent::day"],
        None,
        timezone_now(),
        increment=len(validated_emails),
    )

    # Now that we are past all the possible errors, we actually create
    # the PreregistrationUser objects and trigger the email invitations.
    for email in validated_emails:
        # The logged in user is the referrer.
        prereg_user = PreregistrationUser(email=email,
                                          referred_by=user_profile,
                                          invited_as=invite_as,
                                          realm=user_profile.realm)
        prereg_user.save()
        stream_ids = [stream.id for stream in streams]
        prereg_user.streams.set(stream_ids)

        event = {
            "prereg_id": prereg_user.id,
            "referrer_id": user_profile.id,
            "email_language": user_profile.realm.default_language,
            "invite_expires_in_minutes": invite_expires_in_minutes,
        }
        queue_json_publish("invites", event)

    if skipped:
        raise InvitationError(
            _("Some of those addresses are already using Zulip, "
              "so we didn't send them an invitation. We did send "
              "invitations to everyone else!"),
            skipped,
            sent_invitations=True,
        )
    notify_invites_changed(user_profile.realm)