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.""" data = self.cleaned_data['email'] # If the server has a unique open realm, pass if get_unique_open_realm(): return data # If a realm is specified and that realm is open, pass if completely_open(self.domain): return data # If no realm is specified, fail realm = get_valid_realm(data) if realm is None: raise ValidationError(mark_safe(SIGNUP_STRING)) # If it's a clear realm not used for Zephyr mirroring, pass if not realm.is_zephyr_mirror_realm: return data # At this point, the user is trying to join a Zephyr mirroring # realm. We confirm that they are a real account (not a # mailing list), and if so, let them in. if not_mit_mailing_list(data): return data # Otherwise, the user is an MIT mailing list, and we return failure raise ValidationError(mark_safe(SIGNUP_STRING))
def clean_username(self): # type: () -> str email = self.cleaned_data['username'] try: user_profile = get_user_profile_by_email(email) except UserProfile.DoesNotExist: return email if user_profile.realm.deactivated: error_msg = u"""Sorry for the trouble, but %s has been deactivated. Please contact %s to reactivate this group.""" % ( user_profile.realm.name, FromAddress.SUPPORT) raise ValidationError(mark_safe(error_msg)) if not user_profile.is_active and not user_profile.is_mirror_dummy: error_msg = (u"Sorry for the trouble, but your account has been " u"deactivated. Please contact %s to reactivate " u"it.") % (FromAddress.SUPPORT,) raise ValidationError(mark_safe(error_msg)) if not check_subdomain(get_subdomain(self.request), user_profile.realm.subdomain): logging.warning("User %s attempted to password login to wrong subdomain %s" % (user_profile.email, get_subdomain(self.request))) raise ValidationError(mark_safe(WRONG_SUBDOMAIN_ERROR)) return email
def group_buttons(request, url, title, funcs, block_class): url = current_site_url() + url url = url.encode('utf-8') title = title.encode('utf-8') res = mark_safe("<div class=\"%s\">" % block_class) for f in funcs: res += f(request, url, title) res += mark_safe("</div>") return mark_safe(res)
def clean_email(self): # type: () -> text_type data = self.cleaned_data['email'] domain = split_email_to_domain(data) if (get_realm(domain) is not None): raise ValidationError(mark_safe(get_registration_string(domain))) return data
def clean_email(self): data = self.cleaned_data['email'] if (get_unique_open_realm() or completely_open(self.domain) or (has_valid_realm(data) and not_mit_mailing_list(data))): return data raise ValidationError(mark_safe(SIGNUP_STRING))
def tweet_like(request, url, title): return mark_safe(""" <iframe allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" class="twitter-share-button twitter-count-horizontal" src="https://platform.twitter.com/widgets/tweet_button.html?_=1302382076454&count=horizontal&lang=en&via=escalibro&%s" style="width: 110px; height: 20px; " title="Twitter For Websites: Tweet Button"></iframe> <script type="text/javascript" src="https://platform.twitter.com/widgets.js"></script> """ % ('text=' + title + ' %23escalibro&' + urllib.urlencode({'url': url})))
def vk_like(request, url, title): block_id = (hashlib.md5(url + title)).hexdigest() if not hasattr(request, '_vk_js'): request._vk_js = '' request._vk_js += 'VK.Widgets.Like("vk_like_%s", {type: "button", pageUrl: "%s", pageTitle: "%s", height: "28px"});' \ % (block_id, url, settings.SITE_NAME + " - " + title) return mark_safe('<div id="vk_like_%s"></div>' % block_id)
def gplus_js(request): return mark_safe(""" <script type="text/javascript"> window.___gcfg = {lang: 'ru'}; (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script>""")
def multilingual_flatpage(request, url): """ Multilingual flat page view. Models: `multilingual.flatpages.models` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url f = get_object_or_404(MultilingualFlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) # Serve the content in the language defined by the Django translation module # if possible else serve the default language. f._default_language = get_language() if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, MultilingualFlatPage, f.id) return response
def clean_username(self): # type: () -> str email = self.cleaned_data['username'] try: user_profile = get_user_profile_by_email(email) except UserProfile.DoesNotExist: return email if user_profile.realm.deactivated: error_msg = u"""Sorry for the trouble, but %s has been deactivated. Please contact %s to reactivate this group.""" % ( user_profile.realm.name, settings.ZULIP_ADMINISTRATOR) raise ValidationError(mark_safe(error_msg)) if not check_subdomain(get_subdomain(self.request), user_profile.realm.subdomain): logging.warning("User %s attempted to password login to wrong subdomain %s" % (user_profile.email, get_subdomain(self.request))) raise ValidationError(mark_safe(WRONG_SUBDOMAIN_ERROR)) return email
def email_is_not_mit_mailing_list(email: str) -> None: """Prevent MIT mailing lists from signing up for Zulip""" if "@mit.edu" in email: username = email.rsplit("@", 1)[0] # Check whether the user exists and can get mail. try: DNS.dnslookup("%s.pobox.ns.athena.mit.edu" % (username,), DNS.Type.TXT) except DNS.Base.ServerError as e: if e.rcode == DNS.Status.NXDOMAIN: raise ValidationError(mark_safe(MIT_VALIDATION_ERROR)) else: raise AssertionError("Unexpected DNS error")
def email_is_not_mit_mailing_list(email: str) -> None: """Prevent MIT mailing lists from signing up for Zulip""" if "@mit.edu" in email: username = email.rsplit("@", 1)[0] # Check whether the user exists and can get mail. try: DNS.dnslookup("%s.pobox.ns.athena.mit.edu" % username, DNS.Type.TXT) except DNS.Base.ServerError as e: if e.rcode == DNS.Status.NXDOMAIN: raise ValidationError(mark_safe(MIT_VALIDATION_ERROR)) else: raise AssertionError("Unexpected DNS error")
def clean(self) -> Dict[str, Any]: username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: subdomain = get_subdomain(self.request) realm = get_realm(subdomain) return_data: Dict[str, Any] = {} try: self.user_cache = authenticate(request=self.request, username=username, password=password, realm=realm, return_data=return_data) except RateLimited as e: secs_to_freedom = int(float(str(e))) raise ValidationError(AUTHENTICATION_RATE_LIMITED_ERROR % (secs_to_freedom,)) if return_data.get("inactive_realm"): raise AssertionError("Programming error: inactive realm in authentication form") if return_data.get("inactive_user") and not return_data.get("is_mirror_dummy"): # We exclude mirror dummy accounts here. They should be treated as the # user never having had an account, so we let them fall through to the # normal invalid_login case below. raise ValidationError(mark_safe(DEACTIVATED_ACCOUNT_ERROR)) if return_data.get("invalid_subdomain"): logging.warning("User %s attempted password login to wrong subdomain %s", username, subdomain) raise ValidationError(mark_safe(WRONG_SUBDOMAIN_ERROR)) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) self.confirm_login_allowed(self.user_cache) return self.cleaned_data
def clean(self): # type: () -> Dict[str, Any] username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: subdomain = get_subdomain(self.request) realm = get_realm(subdomain) return_data = {} # type: Dict[str, Any] self.user_cache = authenticate(self.request, username=username, password=password, realm=realm, return_data=return_data) if return_data.get("inactive_realm"): raise AssertionError("Programming error: inactive realm in authentication form") if return_data.get("inactive_user") and not return_data.get("is_mirror_dummy"): # We exclude mirror dummy accounts here. They should be treated as the # user never having had an account, so we let them fall through to the # normal invalid_login case below. error_msg = ( u"Your account is no longer active. " u"Please contact your organization administrator to reactivate it.") raise ValidationError(mark_safe(error_msg)) if return_data.get("invalid_subdomain"): logging.warning("User %s attempted to password login to wrong subdomain %s" % (username, subdomain)) raise ValidationError(mark_safe(WRONG_SUBDOMAIN_ERROR)) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) self.confirm_login_allowed(self.user_cache) return self.cleaned_data
def clean(self) -> Dict[str, Any]: username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: subdomain = get_subdomain(self.request) try: realm = get_realm(subdomain) # type: Optional[Realm] except Realm.DoesNotExist: realm = None return_data = {} # type: Dict[str, Any] self.user_cache = authenticate(self.request, username=username, password=password, realm=realm, return_data=return_data) if return_data.get("inactive_realm"): raise AssertionError("Programming error: inactive realm in authentication form") if return_data.get("inactive_user") and not return_data.get("is_mirror_dummy"): # We exclude mirror dummy accounts here. They should be treated as the # user never having had an account, so we let them fall through to the # normal invalid_login case below. raise ValidationError(mark_safe(DEACTIVATED_ACCOUNT_ERROR)) if return_data.get("invalid_subdomain"): logging.warning("User %s attempted to password login to wrong subdomain %s" % (username, subdomain)) raise ValidationError(mark_safe(WRONG_SUBDOMAIN_ERROR)) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) self.confirm_login_allowed(self.user_cache) return self.cleaned_data
def clean(self) -> Dict[str, Any]: username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: subdomain = get_subdomain(self.request) realm = get_realm(subdomain) return_data = {} # type: Dict[str, Any] self.user_cache = authenticate(self.request, username=username, password=password, realm=realm, return_data=return_data) if return_data.get("inactive_realm"): raise AssertionError("Programming error: inactive realm in authentication form") if return_data.get("inactive_user") and not return_data.get("is_mirror_dummy"): # We exclude mirror dummy accounts here. They should be treated as the # user never having had an account, so we let them fall through to the # normal invalid_login case below. error_msg = ( u"Your account is no longer active. " u"Please contact your organization administrator to reactivate it.") raise ValidationError(mark_safe(error_msg)) if return_data.get("invalid_subdomain"): logging.warning("User %s attempted to password login to wrong subdomain %s" % (username, subdomain)) raise ValidationError(mark_safe(WRONG_SUBDOMAIN_ERROR)) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) self.confirm_login_allowed(self.user_cache) return self.cleaned_data
def user_activity_intervals(): # type: () -> Tuple[mark_safe, Dict[str, float]] day_end = timestamp_to_datetime(time.time()) day_start = day_end - timedelta(hours=24) output = "Per-user online duration for the last 24 hours:\n" total_duration = timedelta(0) all_intervals = UserActivityInterval.objects.filter( end__gte=day_start, start__lte=day_end ).select_related( 'user_profile', 'user_profile__realm' ).only( 'start', 'end', 'user_profile__email', 'user_profile__realm__string_id' ).order_by( 'user_profile__realm__string_id', 'user_profile__email' ) by_string_id = lambda row: row.user_profile.realm.string_id by_email = lambda row: row.user_profile.email realm_minutes = {} for string_id, realm_intervals in itertools.groupby(all_intervals, by_string_id): realm_duration = timedelta(0) output += '<hr>%s\n' % (string_id,) for email, intervals in itertools.groupby(realm_intervals, by_email): duration = timedelta(0) for interval in intervals: start = max(day_start, interval.start) end = min(day_end, interval.end) duration += end - start total_duration += duration realm_duration += duration output += " %-*s%s\n" % (37, email, duration) realm_minutes[string_id] = realm_duration.total_seconds() / 60 output += "\nTotal Duration: %s\n" % (total_duration,) output += "\nTotal Duration in minutes: %s\n" % (total_duration.total_seconds() / 60.,) output += "Total Duration amortized to a month: %s" % (total_duration.total_seconds() * 30. / 60.,) content = mark_safe('<pre>' + output + '</pre>') return content, realm_minutes
def sanitize_name(value: str) -> str: """ Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So unicode is allowed, but not special characters other than ".", "-", and "_". This implementation is based on django.utils.text.slugify; it is modified by: * adding '.' and '_' to the list of allowed characters. * preserving the case of the value. """ value = unicodedata.normalize('NFKC', value) value = re.sub(r'[^\w\s._-]', '', value, flags=re.U).strip() return mark_safe(re.sub(r'[-\s]+', '-', value, flags=re.U))
def not_mit_mailing_list(value): # I don't want ec-discuss signed up for Zulip if "@mit.edu" in value: username = value.rsplit("@", 1)[0] # Check whether the user exists and can get mail. try: DNS.dnslookup("%s.pobox.ns.athena.mit.edu" % username, DNS.Type.TXT) return True except DNS.Base.ServerError as e: if e.rcode == DNS.Status.NXDOMAIN: raise ValidationError(mark_safe(u'That user does not exist at MIT or is a <a href="https://ist.mit.edu/email-lists">mailing list</a>. If you want to sign up an alias for Zulip, <a href="mailto:[email protected]">contact us</a>.')) else: raise return True
def not_mit_mailing_list(value): # type: (str) -> bool # I don't want ec-discuss signed up for Zulip if "@mit.edu" in value: username = value.rsplit("@", 1)[0] # Check whether the user exists and can get mail. try: DNS.dnslookup("%s.pobox.ns.athena.mit.edu" % username, DNS.Type.TXT) return True except DNS.Base.ServerError as e: if e.rcode == DNS.Status.NXDOMAIN: raise ValidationError(mark_safe(MIT_VALIDATION_ERROR)) else: raise return True
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.""" data = self.cleaned_data['email'] # If the server has a unique open realm, pass if get_unique_open_realm(): return data # If a realm is specified and that realm is open, pass if completely_open(self.domain): return data # If the subdomain encodes a complete open realm, pass subdomain_realm = resolve_subdomain_to_realm(self.subdomain) if (subdomain_realm is not None and completely_open(subdomain_realm.domain)): return data # If no realm is specified, fail realm = get_valid_realm(data) if realm is None: raise ValidationError(mark_safe(SIGNUP_STRING)) # If it's a clear realm not used for Zephyr mirroring, pass if not realm.is_zephyr_mirror_realm: return data # At this point, the user is trying to join a Zephyr mirroring # realm. We confirm that they are a real account (not a # mailing list), and if so, let them in. if not_mit_mailing_list(data): return data # Otherwise, the user is an MIT mailing list, and we return failure raise ValidationError(mark_safe(SIGNUP_STRING))
def not_mit_mailing_list(value): # type: (str) -> bool """Prevent MIT mailing lists from signing up for Zulip""" if "@mit.edu" in value: username = value.rsplit("@", 1)[0] # Check whether the user exists and can get mail. try: DNS.dnslookup("%s.pobox.ns.athena.mit.edu" % username, DNS.Type.TXT) return True except DNS.Base.ServerError as e: if e.rcode == DNS.Status.NXDOMAIN: raise ValidationError(mark_safe(MIT_VALIDATION_ERROR)) else: raise return True
def clean_username(self): email = self.cleaned_data['username'] try: user_profile = get_user_profile_by_email(email) except UserProfile.DoesNotExist: return email if user_profile.realm.deactivated: error_msg = u"""Sorry for the trouble, but %s has been deactivated. Please contact %s to reactivate this group.""" % (user_profile.realm.name, settings.ZULIP_ADMINISTRATOR) raise ValidationError(mark_safe(error_msg)) return email
def clean_username(self): email = self.cleaned_data['username'] try: user_profile = get_user_profile_by_email(email) except UserProfile.DoesNotExist: return email if user_profile.realm.deactivated: error_msg = u"""Sorry for the trouble, but %s has been deactivated. Please contact %s to reactivate this group.""" % ( user_profile.realm.name, settings.ZULIP_ADMINISTRATOR) raise ValidationError(mark_safe(error_msg)) return email
def sanitize_name(value: str) -> str: """ Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So Unicode is allowed, but not special characters other than ".", "-", and "_". This implementation is based on django.utils.text.slugify; it is modified by: * adding '.' to the list of allowed characters. * preserving the case of the value. * not stripping trailing dashes and underscores. """ value = unicodedata.normalize("NFKC", value) value = re.sub(r"[^\w\s.-]", "", value, flags=re.U).strip() value = re.sub(r"[-\s]+", "-", value, flags=re.U) assert value not in {"", ".", ".."} return mark_safe(value)
def not_mit_mailing_list(value): # I don't want ec-discuss signed up for Zulip if "@mit.edu" in value: username = value.rsplit("@", 1)[0] # Check whether the user exists and can get mail. try: DNS.dnslookup("%s.pobox.ns.athena.mit.edu" % username, DNS.Type.TXT) return True except DNS.Base.ServerError as e: if e.rcode == DNS.Status.NXDOMAIN: raise ValidationError( mark_safe( u'That user does not exist at MIT or is a <a href="https://ist.mit.edu/email-lists">mailing list</a>. If you want to sign up an alias for Zulip, <a href="mailto:[email protected]">contact us</a>.' )) else: raise return True
def bootstrap_form(*args, **kwargs): return mark_safe(render_form(*args, **kwargs))
def tweet_it(request, url, title): return mark_safe(""" <div class="twitter"> <a href="http://twitter.com/home/?%s" title="%s" target="_blank"></a> </div> """ % (urllib.urlencode({'status': title + (u" " + url + u" #escalibro").encode('utf-8')}), ugettext("Tweet it")))
def like_js(request): return mark_safe(' ').join([f(request) for f in like_js_functions])
def remote_installation_stats_link(server_id: int, hostname: str) -> mark_safe: url_name = 'analytics.views.stats_for_remote_installation' url = reverse(url_name, kwargs=dict(remote_server_id=server_id)) stats_link = '<a href="{}"><i class="fa fa-pie-chart"></i>{}</a>'.format( url, hostname) return mark_safe(stats_link)
def gplus_like(request, url, title): return mark_safe(""" <div class="gplus_like"> <g:plusone size="small"></g:plusone> </div>""")
def vk_it(request, url, title): return mark_safe(""" <div class="vk"> <a onclick="window.open(this.href, '%s', 'width=800,height=300'); return false" href="https://vkontakte.ru/share.php?%s" title="%s"></a> </div> """ % (ugettext("Share link on VKontakte"), urllib.urlencode({'url': url, 'title': title}), ugettext("To VKontakte")))
def gplus_it(request, url, title): return mark_safe(""" <div class="gplus"> <g:plusone size="small" annotation="none"></g:plusone> </div>""")
def vk_js(request): return mark_safe(""" <script type="text/javascript"> VK.init({apiId: "%s", onlyWidgets: true}); %s </script>""" % (settings.VKONTAKTE_APPLICATION_ID, request._vk_js if hasattr(request, '_vk_js') else ''))
def _render(self, bundle, **variation): return mark_safe(_render_include_media(bundle, variation))
def realm_stats_link(realm_str: str) -> mark_safe: url_name = 'analytics.views.stats_for_realm' url = reverse(url_name, kwargs=dict(realm_str=realm_str)) stats_link = '<a href="{}"><i class="fa fa-pie-chart"></i></a>'.format(url, realm_str) return mark_safe(stats_link)
def user_activity_link(email: str) -> mark_safe: url_name = 'analytics.views.get_user_activity' url = urlresolvers.reverse(url_name, kwargs=dict(email=email)) email_link = '<a href="%s">%s</a>' % (url, email) return mark_safe(email_link)
def facebook_it(request, url, title): return mark_safe(""" <div class="facebook"> <a onclick="window.open(this.href, '%s', 'width=800,height=300'); return false" href="https://www.facebook.com/sharer.php?%s" title="%s" target="_blank"></a> </div> """ % (ugettext("Share link on FaceBook"), urllib.urlencode({'u': url, 't': title}), ugettext("To FaceBook")))
def facebook_like(request, url, title): return mark_safe(""" <iframe src="https://www.facebook.com/plugins/like.php?href%s&layout=button_count&show_faces=true&width=85&action=like&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:85px; height:21px;" allowtransparency="true"></iframe> """ % (urllib.urlencode({'': url})))
def user_activity_link(email): # type: (str) -> mark_safe url_name = 'analytics.views.get_user_activity' url = urlresolvers.reverse(url_name, kwargs=dict(email=email)) email_link = '<a href="%s">%s</a>' % (url, email) return mark_safe(email_link)
def realm_activity_link(realm_str: str) -> mark_safe: url_name = 'analytics.views.get_realm_activity' url = urlresolvers.reverse(url_name, kwargs=dict(realm_str=realm_str)) realm_link = '<a href="%s">%s</a>' % (url, realm_str) return mark_safe(realm_link)
def realm_activity_link(realm_str): # type: (str) -> mark_safe url_name = 'analytics.views.get_realm_activity' url = urlresolvers.reverse(url_name, kwargs=dict(realm_str=realm_str)) realm_link = '<a href="%s">%s</a>' % (url, realm_str) return mark_safe(realm_link)
def realm_stats_link(realm_str: str) -> mark_safe: url_name = 'analytics.views.stats_for_realm' url = reverse(url_name, kwargs=dict(realm_str=realm_str)) stats_link = '<a href="{}"><i class="fa fa-pie-chart"></i></a>'.format( url, realm_str) return mark_safe(stats_link)