本文整理汇总了Python中zerver.lib.utils.get_subdomain函数的典型用法代码示例。如果您正苦于以下问题:Python get_subdomain函数的具体用法?Python get_subdomain怎么用?Python get_subdomain使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_subdomain函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: api_fetch_api_key
def api_fetch_api_key(request, username=REQ(), password=REQ()):
# type: (HttpRequest, str, str) -> HttpResponse
return_data = {} # type: Dict[str, bool]
if username == "google-oauth2-token":
user_profile = authenticate(google_oauth2_token=password,
realm_subdomain=get_subdomain(request),
return_data=return_data)
else:
user_profile = authenticate(username=username,
password=password,
realm_subdomain=get_subdomain(request),
return_data=return_data)
if return_data.get("inactive_user") == True:
return json_error(_("Your account has been disabled."),
data={"reason": "user disable"}, status=403)
if return_data.get("inactive_realm") == True:
return json_error(_("Your realm has been deactivated."),
data={"reason": "realm deactivated"}, status=403)
if return_data.get("password_auth_disabled") == True:
return json_error(_("Password auth is disabled in your team."),
data={"reason": "password auth disabled"}, status=403)
if user_profile is None:
if return_data.get("valid_attestation") == True:
# We can leak that the user is unregistered iff they present a valid authentication string for the user.
return json_error(_("This user is not registered; do so from a browser."),
data={"reason": "unregistered"}, status=403)
return json_error(_("Your username or password is incorrect."),
data={"reason": "incorrect_creds"}, status=403)
return json_success({"api_key": user_profile.api_key, "email": user_profile.email})
示例2: clean_username
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
示例3: create_homepage_form
def create_homepage_form(request, user_info=None):
# type: (HttpRequest, Optional[Dict[str, Any]]) -> HomepageForm
if user_info:
return HomepageForm(user_info, domain=request.session.get("domain"),
subdomain=get_subdomain(request))
# An empty fields dict is not treated the same way as not
# providing it.
return HomepageForm(domain=request.session.get("domain"), subdomain=get_subdomain(request))
示例4: _wrapped_func_arguments
def _wrapped_func_arguments(request, api_key=REQ(),
*args, **kwargs):
# type: (HttpRequest, Text, *Any, **Any) -> HttpResponse
try:
user_profile = UserProfile.objects.get(api_key=api_key)
except UserProfile.DoesNotExist:
raise JsonableError(_("Invalid API key"))
if not user_profile.is_active:
raise JsonableError(_("Account not active"))
if user_profile.realm.deactivated:
raise JsonableError(_("Realm for account has been deactivated"))
if not check_subdomain(get_subdomain(request), user_profile.realm.subdomain):
logging.warning("User %s attempted to access webhook API on wrong subdomain %s" % (
user_profile.email, get_subdomain(request)))
raise JsonableError(_("Account is not associated with this subdomain"))
request.user = user_profile
request._email = user_profile.email
webhook_client_name = "Zulip{}Webhook".format(client_name)
process_client(request, user_profile, client_name=webhook_client_name)
if settings.RATE_LIMITING:
rate_limit_user(request, user_profile, domain='all')
try:
return view_func(request, user_profile, *args, **kwargs)
except Exception as err:
if request.content_type == 'application/json':
try:
request_body = ujson.dumps(ujson.loads(request.body), indent=4)
except ValueError:
request_body = str(request.body)
else:
request_body = str(request.body)
message = """
user: {email} ({realm})
client: {client_name}
URL: {path_info}
content_type: {content_type}
body:
{body}
""".format(
email=user_profile.email,
realm=user_profile.realm.string_id,
client_name=webhook_client_name,
body=request_body,
path_info=request.META.get('PATH_INFO', None),
content_type=request.content_type,
)
webhook_logger.exception(message)
raise err
示例5: validate_api_key
def validate_api_key(request, role, api_key, is_webhook=False):
# type: (HttpRequest, Text, Text, bool) -> Union[UserProfile, RemoteZulipServer]
# Remove whitespace to protect users from trivial errors.
role, api_key = role.strip(), api_key.strip()
if not is_remote_server(role):
try:
profile = get_user_profile_by_email(role) # type: Union[UserProfile, RemoteZulipServer]
except UserProfile.DoesNotExist:
raise JsonableError(_("Invalid user: %s") % (role,))
else:
try:
profile = get_remote_server_by_uuid(role)
except RemoteZulipServer.DoesNotExist:
raise JsonableError(_("Invalid Zulip server: %s") % (role,))
if api_key != profile.api_key:
if len(api_key) != 32:
reason = _("Incorrect API key length (keys should be 32 "
"characters long) for role '%s'")
else:
reason = _("Invalid API key for role '%s'")
raise JsonableError(reason % (role,))
# early exit for RemoteZulipServer instances
if settings.ZILENCER_ENABLED and isinstance(profile, RemoteZulipServer):
if not check_subdomain(get_subdomain(request), ""):
raise JsonableError(_("This API key only works on the root subdomain"))
return profile
profile = cast(UserProfile, profile) # is UserProfile
if not profile.is_active:
raise JsonableError(_("Account not active"))
if profile.is_incoming_webhook and not is_webhook:
raise JsonableError(_("Account is not valid to post webhook messages"))
if profile.realm.deactivated:
raise JsonableError(_("Realm for account has been deactivated"))
if (not check_subdomain(get_subdomain(request), profile.realm.subdomain) and
# Allow access to localhost for Tornado
not (settings.RUNNING_INSIDE_TORNADO and
request.META["SERVER_NAME"] == "127.0.0.1" and
request.META["REMOTE_ADDR"] == "127.0.0.1")):
logging.warning("User %s attempted to access API on wrong subdomain %s" % (
profile.email, get_subdomain(request)))
raise JsonableError(_("Account is not associated with this subdomain"))
return profile
示例6: log_into_subdomain
def log_into_subdomain(request):
# type: (HttpRequest) -> HttpResponse
try:
# Discard state if older than 15 seconds
state = request.get_signed_cookie('subdomain.signature',
salt='zerver.views.auth',
max_age=15)
except KeyError:
logging.warning('Missing subdomain signature cookie.')
return HttpResponse(status=400)
except signing.BadSignature:
logging.warning('Subdomain cookie has bad signature.')
return HttpResponse(status=400)
data = ujson.loads(state)
if data['subdomain'] != get_subdomain(request):
logging.warning('Login attemp on invalid subdomain')
return HttpResponse(status=400)
email_address = data['email']
full_name = data['name']
user_profile, return_data = authenticate_remote_user(request, email_address)
invalid_subdomain = bool(return_data.get('invalid_subdomain'))
return login_or_register_remote_user(request, email_address, user_profile,
full_name, invalid_subdomain)
示例7: authenticate_log_and_execute_json
def authenticate_log_and_execute_json(request, view_func, *args, **kwargs):
# type: (HttpRequest, Callable[..., HttpResponse], *Any, **Any) -> HttpResponse
if not request.user.is_authenticated():
return json_error(_("Not logged in"), status=401)
user_profile = request.user
if not user_profile.is_active:
raise JsonableError(_("Account not active"))
if user_profile.realm.deactivated:
raise JsonableError(_("Realm for account has been deactivated"))
if user_profile.is_incoming_webhook:
raise JsonableError(_("Webhook bots can only access webhooks"))
if (
not check_subdomain(get_subdomain(request), user_profile.realm.subdomain)
and
# Exclude the SOCKET requests from this filter; they were
# checked when the original websocket request reached Tornado
not (request.method == "SOCKET" and request.META["SERVER_NAME"] == "127.0.0.1")
):
logging.warning(
"User %s attempted to access JSON API on wrong subdomain %s" % (user_profile.email, get_subdomain(request))
)
raise JsonableError(_("Account is not associated with this subdomain"))
process_client(request, user_profile, True)
request._email = user_profile.email
return view_func(request, user_profile, *args, **kwargs)
示例8: get_auth_backends_data
def get_auth_backends_data(request):
# type: (HttpRequest) -> Dict[str, Any]
"""Returns which authentication methods are enabled on the server"""
if settings.REALMS_HAVE_SUBDOMAINS:
subdomain = get_subdomain(request)
try:
realm = Realm.objects.get(string_id=subdomain)
except Realm.DoesNotExist:
# If not the root subdomain, this is an error
if subdomain != "":
raise JsonableError(_("Invalid subdomain"))
# With the root subdomain, it's an error or not depending
# whether SUBDOMAINS_HOMEPAGE (which indicates whether
# there are some realms without subdomains on this server)
# is set.
if settings.SUBDOMAINS_HOMEPAGE:
raise JsonableError(_("Subdomain required"))
else:
realm = None
else:
# Without subdomains, we just have to report what the server
# supports, since we don't know the realm.
realm = None
return {"password": password_auth_enabled(realm),
"dev": dev_auth_enabled(realm),
"github": github_auth_enabled(realm),
"google": google_auth_enabled(realm)}
示例9: api_dev_fetch_api_key
def api_dev_fetch_api_key(request, username=REQ()):
# type: (HttpRequest, str) -> HttpResponse
"""This function allows logging in without a password on the Zulip
mobile apps when connecting to a Zulip development environment. It
requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
"""
if not dev_auth_enabled() or settings.PRODUCTION:
return json_error(_("Dev environment not enabled."))
# Django invokes authenticate methods by matching arguments, and this
# authentication flow will not invoke LDAP authentication because of
# this condition of Django so no need to check if LDAP backend is
# enabled.
validate_login_email(username)
return_data = {} # type: Dict[str, bool]
user_profile = authenticate(username=username,
realm_subdomain=get_subdomain(request),
return_data=return_data)
if return_data.get("inactive_realm"):
return json_error(_("Your realm has been deactivated."),
data={"reason": "realm deactivated"}, status=403)
if return_data.get("inactive_user"):
return json_error(_("Your account has been disabled."),
data={"reason": "user disable"}, status=403)
if user_profile is None:
return json_error(_("This user is not registered."),
data={"reason": "unregistered"}, status=403)
login(request, user_profile)
return json_success({"api_key": user_profile.api_key, "email": user_profile.email})
示例10: log_into_subdomain
def log_into_subdomain(request):
# type: (HttpRequest) -> HttpResponse
try:
# Discard state if older than 15 seconds
state = request.get_signed_cookie('subdomain.signature',
salt='zerver.views.auth',
max_age=15)
except KeyError:
logging.warning('Missing subdomain signature cookie.')
return HttpResponse(status=400)
except signing.BadSignature:
logging.warning('Subdomain cookie has bad signature.')
return HttpResponse(status=400)
data = ujson.loads(state)
if data['subdomain'] != get_subdomain(request):
logging.warning('Login attemp on invalid subdomain')
return HttpResponse(status=400)
email_address = data['email']
full_name = data['name']
is_signup = data['is_signup']
if is_signup:
# If we are signing up, user_profile should be None. In case
# email_address already exists, user will get an error message.
user_profile = None
return_data = {} # type: Dict[str, Any]
else:
user_profile, return_data = authenticate_remote_user(request, email_address)
invalid_subdomain = bool(return_data.get('invalid_subdomain'))
return login_or_register_remote_user(request, email_address, user_profile,
full_name, invalid_subdomain=invalid_subdomain,
is_signup=is_signup)
示例11: json_fetch_api_key
def json_fetch_api_key(request, user_profile, password=REQ(default='')):
# type: (HttpRequest, UserProfile, str) -> HttpResponse
if password_auth_enabled(user_profile.realm):
if not authenticate(username=user_profile.email, password=password,
realm_subdomain=get_subdomain(request)):
return json_error(_("Your username or password is incorrect."))
return json_success({"api_key": user_profile.api_key})
示例12: send_mail
def send_mail(self, subject_template_name, email_template_name,
context, from_email, to_email, html_email_template_name=None):
# type: (str, str, Dict[str, Any], str, str, str) -> None
"""
Currently we don't support accounts in multiple subdomains using
a single email address. We override this function so that we do
not send a reset link to an email address if the reset attempt is
done on the subdomain which does not match user.realm.subdomain.
Once we start supporting accounts with the same email in
multiple subdomains, we may be able to refactor this function.
A second reason we override this function is so that we can send
the mail through the functions in zerver.lib.send_email, to match
how we send all other mail in the codebase.
"""
user = get_user_profile_by_email(to_email)
attempted_subdomain = get_subdomain(getattr(self, 'request'))
context['attempted_realm'] = False
if not check_subdomain(user.realm.subdomain, attempted_subdomain):
context['attempted_realm'] = get_realm(attempted_subdomain)
send_email('zerver/emails/password_reset', to_user_id=user.id,
from_name="Zulip Account Security",
from_address=FromAddress.NOREPLY, context=context)
示例13: do_auth
def do_auth(self, *args, **kwargs):
# type: (*Any, **Any) -> Optional[HttpResponse]
kwargs["return_data"] = {}
request = self.strategy.request
kwargs["realm_subdomain"] = get_subdomain(request)
user_profile = None
team_id = settings.SOCIAL_AUTH_GITHUB_TEAM_ID
org_name = settings.SOCIAL_AUTH_GITHUB_ORG_NAME
if team_id is None and org_name is None:
user_profile = GithubOAuth2.do_auth(self, *args, **kwargs)
elif team_id:
backend = GithubTeamOAuth2(self.strategy, self.redirect_uri)
try:
user_profile = backend.do_auth(*args, **kwargs)
except AuthFailed:
logging.info("User profile not member of team.")
user_profile = None
elif org_name:
backend = GithubOrganizationOAuth2(self.strategy, self.redirect_uri)
try:
user_profile = backend.do_auth(*args, **kwargs)
except AuthFailed:
logging.info("User profile not member of organisation.")
user_profile = None
return self.process_do_auth(user_profile, *args, **kwargs)
示例14: do_auth
def do_auth(self, *args, **kwargs):
# type: (*Any, **Any) -> Optional[UserProfile]
kwargs['return_data'] = {}
request = self.strategy.request # type: ignore # This comes from Python Social Auth.
kwargs['realm_subdomain'] = get_subdomain(request)
user_profile = None
team_id = settings.SOCIAL_AUTH_GITHUB_TEAM_ID
org_name = settings.SOCIAL_AUTH_GITHUB_ORG_NAME
if (team_id is None and org_name is None):
user_profile = GithubOAuth2.do_auth(self, *args, **kwargs)
elif (team_id):
backend = GithubTeamOAuth2(self.strategy, self.redirect_uri)
try:
user_profile = backend.do_auth(*args, **kwargs)
except AuthFailed:
logging.info("User profile not member of team.")
user_profile = None
elif (org_name):
backend = GithubOrganizationOAuth2(self.strategy, self.redirect_uri)
try:
user_profile = backend.do_auth(*args, **kwargs)
except AuthFailed:
logging.info("User profile not member of organisation.")
user_profile = None
return self.process_do_auth(user_profile, *args, **kwargs)
示例15: send_mail
def send_mail(self, subject_template_name, email_template_name,
context, from_email, to_email, html_email_template_name=None):
# type: (str, str, Dict[str, Any], str, str, str) -> None
"""
Currently we don't support accounts in multiple subdomains using
a single email addresss. We override this function so that we do
not send a reset link to an email address if the reset attempt is
done on the subdomain which does not match user.realm.subdomain.
Once we start supporting accounts with the same email in
multiple subdomains, we may be able to delete or refactor this
function.
"""
user_realm = get_user_profile_by_email(to_email).realm
attempted_subdomain = get_subdomain(getattr(self, 'request'))
context['attempted_realm'] = False
if not check_subdomain(user_realm.subdomain, attempted_subdomain):
context['attempted_realm'] = get_realm(attempted_subdomain)
super(ZulipPasswordResetForm, self).send_mail(
subject_template_name,
email_template_name,
context,
from_email,
to_email,
html_email_template_name=html_email_template_name
)