mirror of
				https://github.com/zulip/zulip.git
				synced 2025-11-04 14:03:30 +00:00 
			
		
		
		
	zproject: Use Python 3 syntax for typing.
This commit is contained in:
		@@ -22,8 +22,7 @@ from zerver.lib.users import check_full_name
 | 
				
			|||||||
from zerver.models import UserProfile, Realm, get_user_profile_by_id, \
 | 
					from zerver.models import UserProfile, Realm, get_user_profile_by_id, \
 | 
				
			||||||
    remote_user_to_email, email_to_username, get_realm, get_user
 | 
					    remote_user_to_email, email_to_username, get_realm, get_user
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def pad_method_dict(method_dict):
 | 
					def pad_method_dict(method_dict: Dict[Text, bool]) -> Dict[Text, bool]:
 | 
				
			||||||
    # type: (Dict[Text, bool]) -> Dict[Text, bool]
 | 
					 | 
				
			||||||
    """Pads an authentication methods dict to contain all auth backends
 | 
					    """Pads an authentication methods dict to contain all auth backends
 | 
				
			||||||
    supported by the software, regardless of whether they are
 | 
					    supported by the software, regardless of whether they are
 | 
				
			||||||
    configured on this server"""
 | 
					    configured on this server"""
 | 
				
			||||||
@@ -32,8 +31,7 @@ def pad_method_dict(method_dict):
 | 
				
			|||||||
            method_dict[key] = False
 | 
					            method_dict[key] = False
 | 
				
			||||||
    return method_dict
 | 
					    return method_dict
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def auth_enabled_helper(backends_to_check, realm):
 | 
					def auth_enabled_helper(backends_to_check: List[Text], realm: Optional[Realm]) -> bool:
 | 
				
			||||||
    # type: (List[Text], Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    if realm is not None:
 | 
					    if realm is not None:
 | 
				
			||||||
        enabled_method_dict = realm.authentication_methods_dict()
 | 
					        enabled_method_dict = realm.authentication_methods_dict()
 | 
				
			||||||
        pad_method_dict(enabled_method_dict)
 | 
					        pad_method_dict(enabled_method_dict)
 | 
				
			||||||
@@ -47,38 +45,30 @@ def auth_enabled_helper(backends_to_check, realm):
 | 
				
			|||||||
                return True
 | 
					                return True
 | 
				
			||||||
    return False
 | 
					    return False
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def ldap_auth_enabled(realm=None):
 | 
					def ldap_auth_enabled(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    return auth_enabled_helper(['LDAP'], realm)
 | 
					    return auth_enabled_helper(['LDAP'], realm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def email_auth_enabled(realm=None):
 | 
					def email_auth_enabled(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    return auth_enabled_helper(['Email'], realm)
 | 
					    return auth_enabled_helper(['Email'], realm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def password_auth_enabled(realm=None):
 | 
					def password_auth_enabled(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    return ldap_auth_enabled(realm) or email_auth_enabled(realm)
 | 
					    return ldap_auth_enabled(realm) or email_auth_enabled(realm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def dev_auth_enabled(realm=None):
 | 
					def dev_auth_enabled(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    return auth_enabled_helper(['Dev'], realm)
 | 
					    return auth_enabled_helper(['Dev'], realm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def google_auth_enabled(realm=None):
 | 
					def google_auth_enabled(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    return auth_enabled_helper(['Google'], realm)
 | 
					    return auth_enabled_helper(['Google'], realm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def github_auth_enabled(realm=None):
 | 
					def github_auth_enabled(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    return auth_enabled_helper(['GitHub'], realm)
 | 
					    return auth_enabled_helper(['GitHub'], realm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def any_oauth_backend_enabled(realm=None):
 | 
					def any_oauth_backend_enabled(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    """Used by the login page process to determine whether to show the
 | 
					    """Used by the login page process to determine whether to show the
 | 
				
			||||||
    'OR' for login with Google"""
 | 
					    'OR' for login with Google"""
 | 
				
			||||||
    return auth_enabled_helper(['GitHub', 'Google'], realm)
 | 
					    return auth_enabled_helper(['GitHub', 'Google'], realm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def require_email_format_usernames(realm=None):
 | 
					def require_email_format_usernames(realm: Optional[Realm]=None) -> bool:
 | 
				
			||||||
    # type: (Optional[Realm]) -> bool
 | 
					 | 
				
			||||||
    if ldap_auth_enabled(realm):
 | 
					    if ldap_auth_enabled(realm):
 | 
				
			||||||
        if settings.LDAP_EMAIL_ATTR or settings.LDAP_APPEND_DOMAIN:
 | 
					        if settings.LDAP_EMAIL_ATTR or settings.LDAP_APPEND_DOMAIN:
 | 
				
			||||||
            return False
 | 
					            return False
 | 
				
			||||||
@@ -112,8 +102,7 @@ def common_get_active_user(email: str, realm: Realm,
 | 
				
			|||||||
    return user_profile
 | 
					    return user_profile
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class ZulipAuthMixin:
 | 
					class ZulipAuthMixin:
 | 
				
			||||||
    def get_user(self, user_profile_id):
 | 
					    def get_user(self, user_profile_id: int) -> Optional[UserProfile]:
 | 
				
			||||||
        # type: (int) -> Optional[UserProfile]
 | 
					 | 
				
			||||||
        """ Get a UserProfile object from the user_profile_id. """
 | 
					        """ Get a UserProfile object from the user_profile_id. """
 | 
				
			||||||
        try:
 | 
					        try:
 | 
				
			||||||
            return get_user_profile_by_id(user_profile_id)
 | 
					            return get_user_profile_by_id(user_profile_id)
 | 
				
			||||||
@@ -123,12 +112,10 @@ class ZulipAuthMixin:
 | 
				
			|||||||
class SocialAuthMixin(ZulipAuthMixin):
 | 
					class SocialAuthMixin(ZulipAuthMixin):
 | 
				
			||||||
    auth_backend_name = None  # type: Text
 | 
					    auth_backend_name = None  # type: Text
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_email_address(self, *args, **kwargs):
 | 
					    def get_email_address(self, *args: Any, **kwargs: Any) -> Text:
 | 
				
			||||||
        # type: (*Any, **Any) -> Text
 | 
					 | 
				
			||||||
        raise NotImplementedError
 | 
					        raise NotImplementedError
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_full_name(self, *args, **kwargs):
 | 
					    def get_full_name(self, *args: Any, **kwargs: Any) -> Text:
 | 
				
			||||||
        # type: (*Any, **Any) -> Text
 | 
					 | 
				
			||||||
        raise NotImplementedError
 | 
					        raise NotImplementedError
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_authenticated_user(self, *args: Any, **kwargs: Any) -> Optional[UserProfile]:
 | 
					    def get_authenticated_user(self, *args: Any, **kwargs: Any) -> Optional[UserProfile]:
 | 
				
			||||||
@@ -191,8 +178,7 @@ class SocialAuthMixin(ZulipAuthMixin):
 | 
				
			|||||||
                                         response=response,
 | 
					                                         response=response,
 | 
				
			||||||
                                         backend=backend)
 | 
					                                         backend=backend)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def _common_authenticate(self, *args, **kwargs):
 | 
					    def _common_authenticate(self, *args: Any, **kwargs: Any) -> Optional[UserProfile]:
 | 
				
			||||||
        # type: (*Any, **Any) -> Optional[UserProfile]
 | 
					 | 
				
			||||||
        return_data = kwargs.get('return_data', {})
 | 
					        return_data = kwargs.get('return_data', {})
 | 
				
			||||||
        realm = kwargs.get("realm")
 | 
					        realm = kwargs.get("realm")
 | 
				
			||||||
        if realm is None:
 | 
					        if realm is None:
 | 
				
			||||||
@@ -209,8 +195,8 @@ class SocialAuthMixin(ZulipAuthMixin):
 | 
				
			|||||||
        return_data["valid_attestation"] = True
 | 
					        return_data["valid_attestation"] = True
 | 
				
			||||||
        return common_get_active_user(email_address, realm, return_data)
 | 
					        return common_get_active_user(email_address, realm, return_data)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def process_do_auth(self, user_profile, *args, **kwargs):
 | 
					    def process_do_auth(self, user_profile: UserProfile, *args: Any,
 | 
				
			||||||
        # type: (UserProfile, *Any, **Any) -> Optional[HttpResponse]
 | 
					                        **kwargs: Any) -> Optional[HttpResponse]:
 | 
				
			||||||
        # These functions need to be imported here to avoid cyclic
 | 
					        # These functions need to be imported here to avoid cyclic
 | 
				
			||||||
        # dependency.
 | 
					        # dependency.
 | 
				
			||||||
        from zerver.views.auth import (login_or_register_remote_user,
 | 
					        from zerver.views.auth import (login_or_register_remote_user,
 | 
				
			||||||
@@ -265,8 +251,7 @@ class SocialAuthMixin(ZulipAuthMixin):
 | 
				
			|||||||
        return redirect_and_log_into_subdomain(realm, full_name, email_address,
 | 
					        return redirect_and_log_into_subdomain(realm, full_name, email_address,
 | 
				
			||||||
                                               is_signup=is_signup)
 | 
					                                               is_signup=is_signup)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def auth_complete(self, *args, **kwargs):
 | 
					    def auth_complete(self, *args: Any, **kwargs: Any) -> Optional[HttpResponse]:
 | 
				
			||||||
        # type: (*Any, **Any) -> Optional[HttpResponse]
 | 
					 | 
				
			||||||
        """
 | 
					        """
 | 
				
			||||||
        Returning `None` from this function will redirect the browser
 | 
					        Returning `None` from this function will redirect the browser
 | 
				
			||||||
        to the login page.
 | 
					        to the login page.
 | 
				
			||||||
@@ -390,38 +375,32 @@ class ZulipLDAPConfigurationError(Exception):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):
 | 
					class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):
 | 
				
			||||||
    # Don't use Django LDAP's permissions functions
 | 
					    # Don't use Django LDAP's permissions functions
 | 
				
			||||||
    def has_perm(self, user, perm, obj=None):
 | 
					    def has_perm(self, user: Optional[UserProfile], perm: Any, obj: Any=None) -> bool:
 | 
				
			||||||
        # type: (Optional[UserProfile], Any, Any) -> bool
 | 
					 | 
				
			||||||
        # Using Any type is safe because we are not doing anything with
 | 
					        # Using Any type is safe because we are not doing anything with
 | 
				
			||||||
        # the arguments.
 | 
					        # the arguments.
 | 
				
			||||||
        return False
 | 
					        return False
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def has_module_perms(self, user, app_label):
 | 
					    def has_module_perms(self, user: Optional[UserProfile], app_label: Optional[str]) -> bool:
 | 
				
			||||||
        # type: (Optional[UserProfile], Optional[str]) -> bool
 | 
					 | 
				
			||||||
        return False
 | 
					        return False
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_all_permissions(self, user, obj=None):
 | 
					    def get_all_permissions(self, user: Optional[UserProfile], obj: Any=None) -> Set[Any]:
 | 
				
			||||||
        # type: (Optional[UserProfile], Any) -> Set[Any]
 | 
					 | 
				
			||||||
        # Using Any type is safe because we are not doing anything with
 | 
					        # Using Any type is safe because we are not doing anything with
 | 
				
			||||||
        # the arguments and always return empty set.
 | 
					        # the arguments and always return empty set.
 | 
				
			||||||
        return set()
 | 
					        return set()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_group_permissions(self, user, obj=None):
 | 
					    def get_group_permissions(self, user: Optional[UserProfile], obj: Any=None) -> Set[Any]:
 | 
				
			||||||
        # type: (Optional[UserProfile], Any) -> Set[Any]
 | 
					 | 
				
			||||||
        # Using Any type is safe because we are not doing anything with
 | 
					        # Using Any type is safe because we are not doing anything with
 | 
				
			||||||
        # the arguments and always return empty set.
 | 
					        # the arguments and always return empty set.
 | 
				
			||||||
        return set()
 | 
					        return set()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def django_to_ldap_username(self, username):
 | 
					    def django_to_ldap_username(self, username: Text) -> Text:
 | 
				
			||||||
        # type: (Text) -> Text
 | 
					 | 
				
			||||||
        if settings.LDAP_APPEND_DOMAIN:
 | 
					        if settings.LDAP_APPEND_DOMAIN:
 | 
				
			||||||
            if not username.endswith("@" + settings.LDAP_APPEND_DOMAIN):
 | 
					            if not username.endswith("@" + settings.LDAP_APPEND_DOMAIN):
 | 
				
			||||||
                raise ZulipLDAPException("Username does not match LDAP domain.")
 | 
					                raise ZulipLDAPException("Username does not match LDAP domain.")
 | 
				
			||||||
            return email_to_username(username)
 | 
					            return email_to_username(username)
 | 
				
			||||||
        return username
 | 
					        return username
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def ldap_to_django_username(self, username):
 | 
					    def ldap_to_django_username(self, username: str) -> str:
 | 
				
			||||||
        # type: (str) -> str
 | 
					 | 
				
			||||||
        if settings.LDAP_APPEND_DOMAIN:
 | 
					        if settings.LDAP_APPEND_DOMAIN:
 | 
				
			||||||
            return "@".join((username, settings.LDAP_APPEND_DOMAIN))
 | 
					            return "@".join((username, settings.LDAP_APPEND_DOMAIN))
 | 
				
			||||||
        return username
 | 
					        return username
 | 
				
			||||||
@@ -445,8 +424,7 @@ class ZulipLDAPAuthBackend(ZulipLDAPAuthBackendBase):
 | 
				
			|||||||
        except ZulipLDAPException:
 | 
					        except ZulipLDAPException:
 | 
				
			||||||
            return None  # nocoverage # TODO: this may no longer be possible
 | 
					            return None  # nocoverage # TODO: this may no longer be possible
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_or_create_user(self, username, ldap_user):
 | 
					    def get_or_create_user(self, username: str, ldap_user: _LDAPUser) -> Tuple[UserProfile, bool]:
 | 
				
			||||||
        # type: (str, _LDAPUser) -> Tuple[UserProfile, bool]
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
        if settings.LDAP_EMAIL_ATTR is not None:
 | 
					        if settings.LDAP_EMAIL_ATTR is not None:
 | 
				
			||||||
            # Get email from ldap attributes.
 | 
					            # Get email from ldap attributes.
 | 
				
			||||||
@@ -514,15 +492,13 @@ class DevAuthBackend(ZulipAuthMixin):
 | 
				
			|||||||
class GitHubAuthBackend(SocialAuthMixin, GithubOAuth2):
 | 
					class GitHubAuthBackend(SocialAuthMixin, GithubOAuth2):
 | 
				
			||||||
    auth_backend_name = "GitHub"
 | 
					    auth_backend_name = "GitHub"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_email_address(self, *args, **kwargs):
 | 
					    def get_email_address(self, *args: Any, **kwargs: Any) -> Optional[Text]:
 | 
				
			||||||
        # type: (*Any, **Any) -> Optional[Text]
 | 
					 | 
				
			||||||
        try:
 | 
					        try:
 | 
				
			||||||
            return kwargs['response']['email']
 | 
					            return kwargs['response']['email']
 | 
				
			||||||
        except KeyError:  # nocoverage # TODO: investigate
 | 
					        except KeyError:  # nocoverage # TODO: investigate
 | 
				
			||||||
            return None
 | 
					            return None
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_full_name(self, *args, **kwargs):
 | 
					    def get_full_name(self, *args: Any, **kwargs: Any) -> Text:
 | 
				
			||||||
        # type: (*Any, **Any) -> Text
 | 
					 | 
				
			||||||
        # In case of any error return an empty string. Name is used by
 | 
					        # In case of any error return an empty string. Name is used by
 | 
				
			||||||
        # the registration page to pre-populate the name field. However,
 | 
					        # the registration page to pre-populate the name field. However,
 | 
				
			||||||
        # if it is not supplied, our registration process will make sure
 | 
					        # if it is not supplied, our registration process will make sure
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -12,8 +12,7 @@ from django.core.mail.backends.base import BaseEmailBackend
 | 
				
			|||||||
from django.core.mail import EmailMultiAlternatives
 | 
					from django.core.mail import EmailMultiAlternatives
 | 
				
			||||||
from django.template import loader
 | 
					from django.template import loader
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def get_forward_address():
 | 
					def get_forward_address() -> str:
 | 
				
			||||||
    # type: () -> str
 | 
					 | 
				
			||||||
    config = configparser.ConfigParser()
 | 
					    config = configparser.ConfigParser()
 | 
				
			||||||
    config.read(settings.FORWARD_ADDRESS_CONFIG_FILE)
 | 
					    config.read(settings.FORWARD_ADDRESS_CONFIG_FILE)
 | 
				
			||||||
    try:
 | 
					    try:
 | 
				
			||||||
@@ -21,8 +20,7 @@ def get_forward_address():
 | 
				
			|||||||
    except (configparser.NoSectionError, configparser.NoOptionError) as e:
 | 
					    except (configparser.NoSectionError, configparser.NoOptionError) as e:
 | 
				
			||||||
        return ""
 | 
					        return ""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def set_forward_address(forward_address):
 | 
					def set_forward_address(forward_address: str) -> None:
 | 
				
			||||||
    # type: (str) -> None
 | 
					 | 
				
			||||||
    config = configparser.ConfigParser()
 | 
					    config = configparser.ConfigParser()
 | 
				
			||||||
    config.read(settings.FORWARD_ADDRESS_CONFIG_FILE)
 | 
					    config.read(settings.FORWARD_ADDRESS_CONFIG_FILE)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -34,8 +32,7 @@ def set_forward_address(forward_address):
 | 
				
			|||||||
            config.write(cfgfile)
 | 
					            config.write(cfgfile)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class EmailLogBackEnd(BaseEmailBackend):
 | 
					class EmailLogBackEnd(BaseEmailBackend):
 | 
				
			||||||
    def send_email_smtp(self, email):
 | 
					    def send_email_smtp(self, email: EmailMultiAlternatives) -> None:
 | 
				
			||||||
        # type: (EmailMultiAlternatives) -> None
 | 
					 | 
				
			||||||
        from_email = email.from_email
 | 
					        from_email = email.from_email
 | 
				
			||||||
        to = get_forward_address()
 | 
					        to = get_forward_address()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -115,7 +115,7 @@ if not CASPER_TESTS:
 | 
				
			|||||||
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
 | 
					        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def set_loglevel(logger_name, level):
 | 
					    def set_loglevel(logger_name, level) -> None:
 | 
				
			||||||
        LOGGING['loggers'].setdefault(logger_name, {})['level'] = level
 | 
					        LOGGING['loggers'].setdefault(logger_name, {})['level'] = level
 | 
				
			||||||
        LOGGING['loggers'].setdefault(logger_name, {})['propagate'] = False
 | 
					        LOGGING['loggers'].setdefault(logger_name, {})['propagate'] = False
 | 
				
			||||||
    set_loglevel('zulip.requests', 'CRITICAL')
 | 
					    set_loglevel('zulip.requests', 'CRITICAL')
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user