示例#1
0
 def subscribe_to_stream(self, email, stream_name, realm=None):
     realm = get_realm(resolve_email_to_domain(email))
     stream = get_stream(stream_name, realm)
     if stream is None:
         stream, _ = create_stream_if_needed(realm, stream_name)
     user_profile = get_user_profile_by_email(email)
     do_add_subscription(user_profile, stream, no_log=True)
示例#2
0
 def subscribe_to_stream(self, email, stream_name, realm=None):
     realm = get_realm(resolve_email_to_domain(email))
     stream = get_stream(stream_name, realm)
     if stream is None:
         stream, _ = create_stream_if_needed(realm, stream_name)
     user_profile = get_user_profile_by_email(email)
     do_add_subscription(user_profile, stream, no_log=True)
示例#3
0
文件: forms.py 项目: wdaher/zulip
def has_valid_realm(value):
    # Checks if there is a realm without invite_required
    # matching the domain of the input e-mail.
    try:
        realm = Realm.objects.get(domain=resolve_email_to_domain(value))
    except Realm.DoesNotExist:
        return False
    return not realm.invite_required
示例#4
0
def has_valid_realm(value):
    # Checks if there is a realm without invite_required
    # matching the domain of the input e-mail.
    try:
        realm = Realm.objects.get(domain=resolve_email_to_domain(value))
    except Realm.DoesNotExist:
        return False
    return not realm.invite_required
def realm_for_email(email):
    try:
        user = get_user_profile_by_email(email)
        return user.realm
    except UserProfile.DoesNotExist:
        pass

    return get_realm(resolve_email_to_domain(email))
示例#6
0
文件: forms.py 项目: galexrt/zulip
def get_valid_realm(value):
    # type: (str) -> Optional[Realm]
    """Checks if there is a realm without invite_required
    matching the domain of the input e-mail."""
    realm = get_realm(resolve_email_to_domain(value))
    if realm is None or realm.invite_required:
        return None
    return realm
示例#7
0
文件: forms.py 项目: zeenfaizpy/zulip
def get_valid_realm(value):
    # type: (str) -> Optional[Realm]
    """Checks if there is a realm without invite_required
    matching the domain of the input e-mail."""
    realm = get_realm(resolve_email_to_domain(value))
    if realm is None or realm.invite_required:
        return None
    return realm
示例#8
0
 def subscribe_to_stream(self, email, stream_name, realm=None):
     # type: (text_type, text_type, Optional[Realm]) -> None
     if realm is None:
         realm = get_realm(resolve_email_to_domain(email))
     stream = get_stream(stream_name, realm)
     if stream is None:
         stream, _ = create_stream_if_needed(realm, stream_name)
     user_profile = get_user_profile_by_email(email)
     bulk_add_subscriptions([stream], [user_profile])
示例#9
0
 def subscribe_to_stream(self, email, stream_name, realm=None):
     # type: (text_type, text_type, Optional[Realm]) -> None
     if realm is None:
         realm = get_realm(resolve_email_to_domain(email))
     stream = get_stream(stream_name, realm)
     if stream is None:
         stream, _ = create_stream_if_needed(realm, stream_name)
     user_profile = get_user_profile_by_email(email)
     bulk_add_subscriptions([stream], [user_profile])
示例#10
0
def realm_for_email(email):
    # type: (str) -> Optional[Realm]
    try:
        user = get_user_profile_by_email(email)
        return user.realm
    except UserProfile.DoesNotExist:
        pass

    return get_realm(resolve_email_to_domain(email))
示例#11
0
def same_realm_irc_user(user_profile, email):
    # Check whether the target email address is an IRC user in the
    # same realm as user_profile, i.e. if the domain were example.com,
    # the IRC user would need to be [email protected]
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)

    return user_profile.realm.domain == domain.replace("irc.", "")
示例#12
0
文件: messages.py 项目: danshev/zulip
def same_realm_irc_user(user_profile, email):
    # Check whether the target email address is an IRC user in the
    # same realm as user_profile, i.e. if the domain were example.com,
    # the IRC user would need to be [email protected]
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)

    return user_profile.realm.domain == domain.replace("irc.", "")
示例#13
0
def same_realm_jabber_user(user_profile, email):
    # type: (UserProfile, text_type) -> bool
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)

    # If your Jabber users have a different email domain than the
    # Zulip users, this is where you would do any translation.
    return user_profile.realm.domain == domain
示例#14
0
def same_realm_jabber_user(user_profile, email):
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)
    # The ist.mit.edu realm uses mit.edu email addresses so that their accounts
    # can receive mail.
    if user_profile.realm.domain == 'ist.mit.edu' and domain == 'mit.edu':
        return True

    return user_profile.realm.domain == domain
示例#15
0
def same_realm_zephyr_user(user_profile, email):
    # Are the sender and recipient both @mit.edu addresses?
    # We have to handle this specially, inferring the domain from the
    # e-mail address, because the recipient may not existing in Zulip
    # and we may need to make a stub MIT user on the fly.
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)

    return user_profile.realm.domain == "mit.edu" and domain == "mit.edu"
示例#16
0
文件: messages.py 项目: danshev/zulip
def same_realm_jabber_user(user_profile, email):
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)
    # The ist.mit.edu realm uses mit.edu email addresses so that their accounts
    # can receive mail.
    if user_profile.realm.domain == 'ist.mit.edu' and domain == 'mit.edu':
        return True

    return user_profile.realm.domain == domain
示例#17
0
文件: messages.py 项目: danshev/zulip
def same_realm_zephyr_user(user_profile, email):
    # Are the sender and recipient both @mit.edu addresses?
    # We have to handle this specially, inferring the domain from the
    # e-mail address, because the recipient may not existing in Zulip
    # and we may need to make a stub MIT user on the fly.
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)

    return user_profile.realm.domain == "mit.edu" and domain == "mit.edu"
示例#18
0
文件: messages.py 项目: galexrt/zulip
def same_realm_jabber_user(user_profile, email):
    # type: (UserProfile, text_type) -> bool
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)
    # The ist.mit.edu realm uses mit.edu email addresses so that their accounts
    # can receive mail.
    if user_profile.realm.domain == "ist.mit.edu" and domain == "mit.edu":
        return True

    return user_profile.realm.domain == domain
示例#19
0
def bulk_create_users(realms, users_raw, bot_type=None):
    # type: (Mapping[str, Realm], Set[Tuple[str, text_type, text_type, bool]], Optional[int]) -> None
    """
    Creates and saves a UserProfile with the given email.
    Has some code based off of UserManage.create_user, but doesn't .save()
    """
    users = []
    existing_users = set(u.email for u in UserProfile.objects.all())
    for (email, full_name, short_name, active) in users_raw:
        if email in existing_users:
            continue
        users.append((email, full_name, short_name, active))
        existing_users.add(email)
    users = sorted(users)

    # Now create user_profiles
    profiles_to_create = []
    for (email, full_name, short_name, active) in users:
        domain = str(resolve_email_to_domain(email))
        profile = create_user_profile(realms[domain], email,
                                      initial_password(email), active,
                                      bot_type, full_name, short_name, None,
                                      False)
        profiles_to_create.append(profile)
    UserProfile.objects.bulk_create(profiles_to_create)

    profiles_by_email = {}
    profiles_by_id = {}
    for profile in UserProfile.objects.select_related().all():
        profiles_by_email[profile.email] = profile
        profiles_by_id[profile.id] = profile

    recipients_to_create = []
    for (email, full_name, short_name, active) in users:
        recipients_to_create.append(
            Recipient(type_id=profiles_by_email[email].id,
                      type=Recipient.PERSONAL))
    Recipient.objects.bulk_create(recipients_to_create)

    recipients_by_email = {}
    for recipient in Recipient.objects.filter(type=Recipient.PERSONAL):
        recipients_by_email[profiles_by_id[
            recipient.type_id].email] = recipient

    subscriptions_to_create = []
    for (email, full_name, short_name, active) in users:
        subscriptions_to_create.append(
            Subscription(user_profile_id=profiles_by_email[email].id,
                         recipient=recipients_by_email[email]))
    Subscription.objects.bulk_create(subscriptions_to_create)
示例#20
0
    def get_or_create_user(self, username, ldap_user):
        try:
            return get_user_profile_by_email(username), False
        except UserProfile.DoesNotExist:
            domain = resolve_email_to_domain(username)
            realm = get_realm(domain)

            full_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP["full_name"]
            short_name = full_name = ldap_user.attrs[full_name_attr]
            if "short_name" in settings.AUTH_LDAP_USER_ATTR_MAP:
                short_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP["short_name"]
                short_name = ldap_user.attrs[short_name_attr]

            user_profile = do_create_user(username, None, realm, full_name, short_name)
            return user_profile, False
示例#21
0
文件: messages.py 项目: galexrt/zulip
def same_realm_zephyr_user(user_profile, email):
    # type: (UserProfile, text_type) -> bool
    #
    # Are the sender and recipient both addresses in the same Zephyr
    # mirroring realm?  We have to handle this specially, inferring
    # the domain from the e-mail address, because the recipient may
    # not existing in Zulip and we may need to make a stub Zephyr
    # mirroring user on the fly.
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)

    return user_profile.realm.domain == domain and user_profile.realm.is_zephyr_mirror_realm
示例#22
0
def same_realm_zephyr_user(user_profile, email):
    # type: (UserProfile, text_type) -> bool
    #
    # Are the sender and recipient both addresses in the same Zephyr
    # mirroring realm?  We have to handle this specially, inferring
    # the domain from the e-mail address, because the recipient may
    # not existing in Zulip and we may need to make a stub Zephyr
    # mirroring user on the fly.
    try:
        validators.validate_email(email)
    except ValidationError:
        return False

    domain = resolve_email_to_domain(email)

    return user_profile.realm.domain == domain and user_profile.realm.is_zephyr_mirror_realm
示例#23
0
def bulk_create_users(realms, users_raw, bot_type=None):
    # type: (Mapping[text_type, Realm], Set[Tuple[text_type, text_type, text_type, bool]], Optional[int]) -> None
    """
    Creates and saves a UserProfile with the given email.
    Has some code based off of UserManage.create_user, but doesn't .save()
    """
    users = [] # type: List[Tuple[text_type, text_type, text_type, bool]]
    existing_users = set(u.email for u in UserProfile.objects.all()) # type: Set[text_type]
    for (email, full_name, short_name, active) in users_raw:
        if email in existing_users:
            continue
        users.append((email, full_name, short_name, active))
        existing_users.add(email)
    users = sorted(users)

    # Now create user_profiles
    profiles_to_create = [] # type: List[UserProfile]
    for (email, full_name, short_name, active) in users:
        domain = resolve_email_to_domain(email)
        profile = create_user_profile(realms[domain], email,
                                      initial_password(email), active, bot_type,
                                      full_name, short_name, None, False)
        profiles_to_create.append(profile)
    UserProfile.objects.bulk_create(profiles_to_create)

    profiles_by_email = {} # type: Dict[text_type, UserProfile]
    profiles_by_id = {} # type: Dict[int, UserProfile]
    for profile in UserProfile.objects.select_related().all():
        profiles_by_email[profile.email] = profile
        profiles_by_id[profile.id] = profile

    recipients_to_create = [] # type: List[Recipient]
    for (email, full_name, short_name, active) in users:
        recipients_to_create.append(Recipient(type_id=profiles_by_email[email].id,
                                              type=Recipient.PERSONAL))
    Recipient.objects.bulk_create(recipients_to_create)

    recipients_by_email = {} # type: Dict[text_type, Recipient]
    for recipient in Recipient.objects.filter(type=Recipient.PERSONAL):
        recipients_by_email[profiles_by_id[recipient.type_id].email] = recipient

    subscriptions_to_create = [] # type: List[Subscription]
    for (email, full_name, short_name, active) in users:
        subscriptions_to_create.append(
            Subscription(user_profile_id=profiles_by_email[email].id,
                         recipient=recipients_by_email[email]))
    Subscription.objects.bulk_create(subscriptions_to_create)
示例#24
0
文件: backends.py 项目: zag/zulip
    def get_or_create_user(self, username, ldap_user):
        try:
            return get_user_profile_by_email(username), False
        except UserProfile.DoesNotExist:
            domain = resolve_email_to_domain(username)
            realm = get_realm(domain)

            full_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP["full_name"]
            short_name = full_name = ldap_user.attrs[full_name_attr][0]
            if "short_name" in settings.AUTH_LDAP_USER_ATTR_MAP:
                short_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP[
                    "short_name"]
                short_name = ldap_user.attrs[short_name_attr][0]

            user_profile = do_create_user(username, None, realm, full_name,
                                          short_name)
            return user_profile, False
示例#25
0
def bulk_create_users(realms, users_raw, bot=False):
    """
    Creates and saves a UserProfile with the given email.
    Has some code based off of UserManage.create_user, but doesn't .save()
    """
    users = []
    existing_users = set(u.email for u in UserProfile.objects.all())
    for (email, full_name, short_name, active) in users_raw:
        if email in existing_users:
            continue
        users.append((email, full_name, short_name, active))
        existing_users.add(email)

    # Now create user_profiles
    profiles_to_create = []
    for (email, full_name, short_name, active) in users:
        domain = resolve_email_to_domain(email)
        profile = create_user_profile(realms[domain], email,
                                      initial_password(email), active, bot,
                                      full_name, short_name, None, False)
        profiles_to_create.append(profile)
    UserProfile.objects.bulk_create(profiles_to_create)

    profiles_by_email = {}
    profiles_by_id = {}
    for profile in UserProfile.objects.select_related().all():
        profiles_by_email[profile.email] = profile
        profiles_by_id[profile.id] = profile

    recipients_to_create = []
    for (email, _, _, _) in users:
        recipients_to_create.append(Recipient(type_id=profiles_by_email[email].id,
                                              type=Recipient.PERSONAL))
    Recipient.objects.bulk_create(recipients_to_create)

    recipients_by_email = {}
    for recipient in Recipient.objects.filter(type=Recipient.PERSONAL):
        recipients_by_email[profiles_by_id[recipient.type_id].email] = recipient

    subscriptions_to_create = []
    for (email, _, _, _) in users:
        subscriptions_to_create.append(
            Subscription(user_profile_id=profiles_by_email[email].id,
                         recipient=recipients_by_email[email]))
    Subscription.objects.bulk_create(subscriptions_to_create)
示例#26
0
文件: __init__.py 项目: sd2017/zulip
def accounts_accept_terms(request):
    # type: (HttpRequest) -> HttpResponse
    if request.method == "POST":
        form = ToSForm(request.POST)
        if form.is_valid():
            do_change_tos_version(request.user, settings.TOS_VERSION)
            return redirect(home)
    else:
        form = ToSForm()

    email = request.user.email
    domain = resolve_email_to_domain(email)
    special_message_template = None
    if request.user.tos_version is None and settings.FIRST_TIME_TOS_TEMPLATE is not None:
        special_message_template = 'zerver/' + settings.FIRST_TIME_TOS_TEMPLATE
    return render_to_response('zerver/accounts_accept_terms.html',
        { 'form': form, 'company_name': domain, 'email': email, \
          'special_message_template' : special_message_template },
        request=request)
示例#27
0
def accounts_accept_terms(request):
    # type: (HttpRequest) -> HttpResponse
    if request.method == "POST":
        form = ToSForm(request.POST)
        if form.is_valid():
            do_change_tos_version(request.user, settings.TOS_VERSION)
            return redirect(home)
    else:
        form = ToSForm()

    email = request.user.email
    domain = resolve_email_to_domain(email)
    special_message_template = None
    if request.user.tos_version is None and settings.FIRST_TIME_TOS_TEMPLATE is not None:
        special_message_template = 'zerver/' + settings.FIRST_TIME_TOS_TEMPLATE
    return render_to_response('zerver/accounts_accept_terms.html',
        { 'form': form, 'company_name': domain, 'email': email, \
          'special_message_template' : special_message_template },
        request=request)
示例#28
0
    def clean_email(self):
        # type: () -> str
        """Returns the email if and only if the user's email address is
        allowed to join the realm they are trying to join."""
        email = self.cleaned_data['email']

        if get_unique_open_realm():
            return email

        # Otherwise, the user is trying to join a specific realm.
        realm = None
        if self.string_id:
            realm = get_realm_by_string_id(self.string_id)
        elif not settings.REALMS_HAVE_SUBDOMAINS:
            realm = get_realm(resolve_email_to_domain(email))

        if realm is None:
            if settings.REALMS_HAVE_SUBDOMAINS:
                raise ValidationError(
                    _("The organization you are trying to join does not exist."
                      ))
            else:
                raise ValidationError(
                    _("Your email address does not correspond to any existing organization."
                      ))

        if realm.invite_required:
            raise ValidationError(
                _("Please request an invite from the organization administrator."
                  ))

        if not email_allowed_for_realm(email, realm):
            raise ValidationError(
                _("The organization you are trying to join, %(string_id)s, only allows users with e-mail "
                  "addresses within the organization. Please try a different e-mail address."
                  % {'string_id': realm.string_id}))

        if realm.is_zephyr_mirror_realm:
            email_is_not_mit_mailing_list(email)

        return email
示例#29
0
文件: backends.py 项目: pxhanus/zulip
    def get_or_create_user(self, username, ldap_user):
        try:
            user_profile = get_user_profile_by_email(username)
            if not user_profile.is_active or user_profile.realm.deactivated:
                raise ZulipLDAPException("Realm has been deactivated")
            return user_profile, False
        except UserProfile.DoesNotExist:
            domain = resolve_email_to_domain(username)
            realm = get_realm(domain)
            # No need to check for an inactive user since they don't exist yet
            if realm.deactivated:
                raise ZulipLDAPException("Realm has been deactivated")

            full_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP["full_name"]
            short_name = full_name = ldap_user.attrs[full_name_attr][0]
            if "short_name" in settings.AUTH_LDAP_USER_ATTR_MAP:
                short_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP["short_name"]
                short_name = ldap_user.attrs[short_name_attr][0]

            user_profile = do_create_user(username, None, realm, full_name, short_name)
            return user_profile, False
示例#30
0
 def subscribe_to_stream(self, email, stream_name, realm=None):
     realm = Realm.objects.get(domain=resolve_email_to_domain(email))
     stream, _ = create_stream_if_needed(realm, stream_name)
     user_profile = get_user_profile_by_email(email)
     do_add_subscription(user_profile, stream, no_log=True)
示例#31
0
 def subscribe_to_stream(self, email, stream_name, realm=None):
     realm = Realm.objects.get(domain=resolve_email_to_domain(email))
     stream, _ = create_stream_if_needed(realm, stream_name)
     user_profile = get_user_profile_by_email(email)
     do_add_subscription(user_profile, stream, no_log=True)
示例#32
0
文件: forms.py 项目: Croolis/zulip
def has_valid_realm(value):
    # Checks if there is a realm without invite_required
    # matching the domain of the input e-mail.
    realm = get_realm(resolve_email_to_domain(value))
    return realm is not None and not realm.invite_required
示例#33
0
文件: __init__.py 项目: sd2017/zulip
def accounts_register(request):
    # type: (HttpRequest) -> HttpResponse
    key = request.POST['key']
    confirmation = Confirmation.objects.get(confirmation_key=key)
    prereg_user = confirmation.content_object
    email = prereg_user.email
    realm_creation = prereg_user.realm_creation
    try:
        existing_user_profile = get_user_profile_by_email(email)
    except UserProfile.DoesNotExist:
        existing_user_profile = None

    validators.validate_email(email)
    # If OPEN_REALM_CREATION is enabled all user sign ups should go through the
    # special URL with domain name so that REALM can be identified if multiple realms exist
    unique_open_realm = get_unique_open_realm()
    if unique_open_realm is not None:
        realm = unique_open_realm
        domain = realm.domain
    elif prereg_user.referred_by:
        # If someone invited you, you are joining their realm regardless
        # of your e-mail address.
        realm = prereg_user.referred_by.realm
        domain = realm.domain
        if not email_allowed_for_realm(email, realm):
            return render_to_response("zerver/closed_realm.html",
                                      {"closed_domain_name": realm.name})
    elif prereg_user.realm:
        # You have a realm set, even though nobody referred you. This
        # happens if you sign up through a special URL for an open
        # realm.
        domain = prereg_user.realm.domain
        realm = get_realm(domain)
    else:
        domain = resolve_email_to_domain(email)
        realm = get_realm(domain)

    if realm and realm.deactivated:
        # The user is trying to register for a deactivated realm. Advise them to
        # contact support.
        return render_to_response(
            "zerver/deactivated.html", {
                "deactivated_domain_name": realm.name,
                "zulip_administrator": settings.ZULIP_ADMINISTRATOR
            })

    try:
        if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            # Mirror dummy users to be activated must be inactive
            is_inactive(email)
        else:
            # Other users should not already exist at all.
            user_email_is_unique(email)
    except ValidationError:
        return HttpResponseRedirect(
            reverse('django.contrib.auth.views.login') + '?email=' +
            urllib.parse.quote_plus(email))

    name_validated = False
    full_name = None

    if request.POST.get('from_confirmation'):
        try:
            del request.session['authenticated_full_name']
        except KeyError:
            pass
        if realm is not None and realm.is_zephyr_mirror_realm and domain == "mit.edu":
            # for MIT users, we can get an authoritative name from Hesiod
            hesiod_name = compute_mit_user_fullname(email)
            form = RegistrationForm(
                initial={
                    'full_name': hesiod_name if "@" not in hesiod_name else ""
                })
            name_validated = True
        elif settings.POPULATE_PROFILE_VIA_LDAP:
            for backend in get_backends():
                if isinstance(backend, LDAPBackend):
                    ldap_attrs = _LDAPUser(
                        backend, backend.django_to_ldap_username(email)).attrs
                    try:
                        ldap_full_name = ldap_attrs[
                            settings.AUTH_LDAP_USER_ATTR_MAP['full_name']][0]
                        request.session[
                            'authenticated_full_name'] = ldap_full_name
                        name_validated = True
                        # We don't use initial= here, because if the form is
                        # complete (that is, no additional fields need to be
                        # filled out by the user) we want the form to validate,
                        # so they can be directly registered without having to
                        # go through this interstitial.
                        form = RegistrationForm({'full_name': ldap_full_name})
                        # FIXME: This will result in the user getting
                        # validation errors if they have to enter a password.
                        # Not relevant for ONLY_SSO, though.
                        break
                    except TypeError:
                        # Let the user fill out a name and/or try another backend
                        form = RegistrationForm()
        elif 'full_name' in request.POST:
            form = RegistrationForm(
                initial={'full_name': request.POST.get('full_name')})
        else:
            form = RegistrationForm()
    else:
        postdata = request.POST.copy()
        if name_changes_disabled(realm):
            # If we populate profile information via LDAP and we have a
            # verified name from you on file, use that. Otherwise, fall
            # back to the full name in the request.
            try:
                postdata.update(
                    {'full_name': request.session['authenticated_full_name']})
                name_validated = True
            except KeyError:
                pass
        form = RegistrationForm(postdata)
        if not password_auth_enabled(realm):
            form['password'].field.required = False

    if form.is_valid():
        if password_auth_enabled(realm):
            password = form.cleaned_data['password']
        else:
            # SSO users don't need no passwords
            password = None

        if realm_creation:
            domain = split_email_to_domain(email)
            realm_name = form.cleaned_data['realm_name']
            org_type = int(form.cleaned_data['realm_org_type'])
            if settings.REALMS_HAVE_SUBDOMAINS:
                realm = do_create_realm(
                    domain,
                    realm_name,
                    org_type=org_type,
                    subdomain=form.cleaned_data['realm_subdomain'])[0]
            else:
                realm = do_create_realm(domain, realm_name,
                                        org_type=org_type)[0]

            set_default_streams(realm, settings.DEFAULT_NEW_REALM_STREAMS)

        full_name = form.cleaned_data['full_name']
        short_name = email_to_username(email)
        first_in_realm = len(
            UserProfile.objects.filter(realm=realm, is_bot=False)) == 0

        # FIXME: sanitize email addresses and fullname
        if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            try:
                user_profile = existing_user_profile
                do_activate_user(user_profile)
                do_change_password(user_profile, password)
                do_change_full_name(user_profile, full_name)
            except UserProfile.DoesNotExist:
                user_profile = do_create_user(
                    email,
                    password,
                    realm,
                    full_name,
                    short_name,
                    prereg_user=prereg_user,
                    tos_version=settings.TOS_VERSION,
                    newsletter_data={"IP": request.META['REMOTE_ADDR']})
        else:
            user_profile = do_create_user(
                email,
                password,
                realm,
                full_name,
                short_name,
                prereg_user=prereg_user,
                tos_version=settings.TOS_VERSION,
                newsletter_data={"IP": request.META['REMOTE_ADDR']})

        # This logs you in using the ZulipDummyBackend, since honestly nothing
        # more fancy than this is required.
        return_data = {}  # type: Dict[str, bool]
        auth_result = authenticate(username=user_profile.email,
                                   realm_subdomain=realm.subdomain,
                                   return_data=return_data,
                                   use_dummy_backend=True)
        if return_data.get('invalid_subdomain'):
            # By construction, this should never happen.
            logging.error("Subdomain mismatch in registration %s: %s" % (
                realm.subdomain,
                user_profile.email,
            ))
            return redirect('/')
        login(request, auth_result)

        if first_in_realm:
            do_change_is_admin(user_profile, True)
        return HttpResponseRedirect(realm.uri + reverse('zerver.views.home'))

    return render_to_response(
        'zerver/register.html',
        {
            'form': form,
            'company_name': domain,
            'email': email,
            'key': key,
            'full_name': request.session.get('authenticated_full_name', None),
            'lock_name': name_validated and name_changes_disabled(realm),
            # password_auth_enabled is normally set via our context processor,
            # but for the registration form, there is no logged in user yet, so
            # we have to set it here.
            'creating_new_team': realm_creation,
            'realms_have_subdomains': settings.REALMS_HAVE_SUBDOMAINS,
            'password_auth_enabled': password_auth_enabled(realm),
        },
        request=request)
示例#34
0
def accounts_register(request):
    # type: (HttpRequest) -> HttpResponse
    key = request.POST['key']
    confirmation = Confirmation.objects.get(confirmation_key=key)
    prereg_user = confirmation.content_object
    email = prereg_user.email
    realm_creation = prereg_user.realm_creation
    try:
        existing_user_profile = get_user_profile_by_email(email)
    except UserProfile.DoesNotExist:
        existing_user_profile = None

    validators.validate_email(email)
    # If OPEN_REALM_CREATION is enabled all user sign ups should go through the
    # special URL with domain name so that REALM can be identified if multiple realms exist
    unique_open_realm = get_unique_open_realm()
    if unique_open_realm is not None:
        realm = unique_open_realm
        domain = realm.domain
    elif prereg_user.referred_by:
        # If someone invited you, you are joining their realm regardless
        # of your e-mail address.
        realm = prereg_user.referred_by.realm
        domain = realm.domain
        if not email_allowed_for_realm(email, realm):
            return render_to_response("zerver/closed_realm.html", {"closed_domain_name": realm.name})
    elif prereg_user.realm:
        # You have a realm set, even though nobody referred you. This
        # happens if you sign up through a special URL for an open
        # realm.
        domain = prereg_user.realm.domain
        realm = get_realm(domain)
    else:
        domain = resolve_email_to_domain(email)
        realm = get_realm(domain)

    if realm and realm.deactivated:
        # The user is trying to register for a deactivated realm. Advise them to
        # contact support.
        return render_to_response("zerver/deactivated.html",
                                  {"deactivated_domain_name": realm.name,
                                   "zulip_administrator": settings.ZULIP_ADMINISTRATOR})

    try:
        if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            # Mirror dummy users to be activated must be inactive
            is_inactive(email)
        else:
            # Other users should not already exist at all.
            user_email_is_unique(email)
    except ValidationError:
        return HttpResponseRedirect(reverse('django.contrib.auth.views.login') + '?email=' +
                                    urllib.parse.quote_plus(email))

    name_validated = False
    full_name = None

    if request.POST.get('from_confirmation'):
        try:
            del request.session['authenticated_full_name']
        except KeyError:
            pass
        if realm is not None and realm.is_zephyr_mirror_realm and domain == "mit.edu":
            # for MIT users, we can get an authoritative name from Hesiod
            hesiod_name = compute_mit_user_fullname(email)
            form = RegistrationForm(
                    initial={'full_name': hesiod_name if "@" not in hesiod_name else ""})
            name_validated = True
        elif settings.POPULATE_PROFILE_VIA_LDAP:
            for backend in get_backends():
                if isinstance(backend, LDAPBackend):
                    ldap_attrs = _LDAPUser(backend, backend.django_to_ldap_username(email)).attrs
                    try:
                        ldap_full_name = ldap_attrs[settings.AUTH_LDAP_USER_ATTR_MAP['full_name']][0]
                        request.session['authenticated_full_name'] = ldap_full_name
                        name_validated = True
                        # We don't use initial= here, because if the form is
                        # complete (that is, no additional fields need to be
                        # filled out by the user) we want the form to validate,
                        # so they can be directly registered without having to
                        # go through this interstitial.
                        form = RegistrationForm({'full_name': ldap_full_name})
                        # FIXME: This will result in the user getting
                        # validation errors if they have to enter a password.
                        # Not relevant for ONLY_SSO, though.
                        break
                    except TypeError:
                        # Let the user fill out a name and/or try another backend
                        form = RegistrationForm()
        elif 'full_name' in request.POST:
            form = RegistrationForm(
                initial={'full_name': request.POST.get('full_name')}
            )
        else:
            form = RegistrationForm()
    else:
        postdata = request.POST.copy()
        if name_changes_disabled(realm):
            # If we populate profile information via LDAP and we have a
            # verified name from you on file, use that. Otherwise, fall
            # back to the full name in the request.
            try:
                postdata.update({'full_name': request.session['authenticated_full_name']})
                name_validated = True
            except KeyError:
                pass
        form = RegistrationForm(postdata)
        if not password_auth_enabled(realm):
            form['password'].field.required = False

    if form.is_valid():
        if password_auth_enabled(realm):
            password = form.cleaned_data['password']
        else:
            # SSO users don't need no passwords
            password = None

        if realm_creation:
            string_id = form.cleaned_data['realm_subdomain']
            realm_name = form.cleaned_data['realm_name']
            org_type = int(form.cleaned_data['realm_org_type'])
            domain = split_email_to_domain(email)
            realm = do_create_realm(string_id, realm_name, org_type=org_type,
                                    domain=domain)[0]

            set_default_streams(realm, settings.DEFAULT_NEW_REALM_STREAMS)

        full_name = form.cleaned_data['full_name']
        short_name = email_to_username(email)
        first_in_realm = len(UserProfile.objects.filter(realm=realm, is_bot=False)) == 0

        # FIXME: sanitize email addresses and fullname
        if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
            try:
                user_profile = existing_user_profile
                do_activate_user(user_profile)
                do_change_password(user_profile, password)
                do_change_full_name(user_profile, full_name)
            except UserProfile.DoesNotExist:
                user_profile = do_create_user(email, password, realm, full_name, short_name,
                                              prereg_user=prereg_user,
                                              tos_version=settings.TOS_VERSION,
                                              newsletter_data={"IP": request.META['REMOTE_ADDR']})
        else:
            user_profile = do_create_user(email, password, realm, full_name, short_name,
                                          prereg_user=prereg_user,
                                          tos_version=settings.TOS_VERSION,
                                          newsletter_data={"IP": request.META['REMOTE_ADDR']})

        if first_in_realm:
            do_change_is_admin(user_profile, True)

        if realm_creation and settings.REALMS_HAVE_SUBDOMAINS:
            # Because for realm creation, registration happens on the
            # root domain, we need to log them into the subdomain for
            # their new realm.
            return redirect_and_log_into_subdomain(realm, full_name, email)

        # This dummy_backend check below confirms the user is
        # authenticating to the correct subdomain.
        return_data = {} # type: Dict[str, bool]
        auth_result = authenticate(username=user_profile.email,
                                   realm_subdomain=realm.subdomain,
                                   return_data=return_data,
                                   use_dummy_backend=True)
        if return_data.get('invalid_subdomain'):
            # By construction, this should never happen.
            logging.error("Subdomain mismatch in registration %s: %s" % (
                realm.subdomain, user_profile.email,))
            return redirect('/')
        login(request, auth_result)
        return HttpResponseRedirect(realm.uri + reverse('zerver.views.home'))

    return render_to_response('zerver/register.html',
            {'form': form,
             'company_name': domain,
             'email': email,
             'key': key,
             'full_name': request.session.get('authenticated_full_name', None),
             'lock_name': name_validated and name_changes_disabled(realm),
             # password_auth_enabled is normally set via our context processor,
             # but for the registration form, there is no logged in user yet, so
             # we have to set it here.
             'creating_new_team': realm_creation,
             'realms_have_subdomains': settings.REALMS_HAVE_SUBDOMAINS,
             'password_auth_enabled': password_auth_enabled(realm),
            },
        request=request)
示例#35
0
def has_valid_realm(value):
    # type: (str) -> bool
    # Checks if there is a realm without invite_required
    # matching the domain of the input e-mail.
    realm = get_realm(resolve_email_to_domain(value))
    return realm is not None and not realm.invite_required