Changeset - dd87009b518b
[Not reviewed]
default
0 5 0
Mads Kiilerich - 10 years ago 2015-07-31 15:44:07
madski@unity3d.com
auth: various minor cleanup of general auth functionality
5 files changed with 23 insertions and 21 deletions:
0 comments (0 inline, 0 general)
kallithea/lib/auth_modules/__init__.py
Show inline comments
 
@@ -52,16 +52,16 @@ class KallitheaAuthPluginBase(object):
 
        "firstname": "first name",
 
        "lastname": "last name",
 
        "email": "email address",
 
        "groups": '["list", "of", "groups"]',
 
        "extern_name": "name in external source of record",
 
        "extern_type": "type of external source of record",
 
        "admin": 'True|False defines if user should be Kallithea super admin',
 
        "active": 'True|False defines active state of user internally for Kallithea',
 
        "active_from_extern": "True|False\None, active state from the external auth, "
 
                              "None means use definition from Kallithea extern_type active value"
 
        "admin": 'True|False defines if user should be Kallithea admin',
 
        "active": 'True|False defines active state of user in Kallithea',
 
        "active_from_extern": "True|False|None, active state from the external auth, "
 
                              "None means use value from the auth plugin"
 
    }
 

	
 
    @property
 
    def validators(self):
 
        """
 
        Exposes Kallithea validators modules
 
@@ -181,13 +181,13 @@ class KallitheaAuthPluginBase(object):
 
        """
 
        raise NotImplementedError("Not implemented in base class")
 

	
 
    def plugin_settings(self):
 
        """
 
        This method is called by the authentication framework, not the .settings()
 
        method. This method adds a few default settings (e.g., "active"), so that
 
        method. This method adds a few default settings (e.g., "enabled"), so that
 
        plugin authors don't have to maintain a bunch of boilerplate.
 

	
 
        OVERRIDING THIS METHOD WILL CAUSE YOUR PLUGIN TO FAIL.
 
        """
 

	
 
        rcsettings = self.settings()
 
@@ -208,20 +208,20 @@ class KallitheaAuthPluginBase(object):
 
        :returns: boolean
 
        """
 
        raise NotImplementedError("Not implemented in base class")
 

	
 
    def auth(self, userobj, username, passwd, settings, **kwargs):
 
        """
 
        Given a user object (which may be null), username, a plaintext password,
 
        Given a user object (which may be None), username, a plaintext password,
 
        and a settings object (containing all the keys needed as listed in settings()),
 
        authenticate this user's login attempt.
 

	
 
        Return None on failure. On success, return a dictionary of the form:
 
        Return None on failure. On success, return a dictionary with keys from
 
        KallitheaAuthPluginBase.auth_func_attrs.
 

	
 
            see: KallitheaAuthPluginBase.auth_func_attrs
 
        This is later validated for correctness
 
        This is later validated for correctness.
 
        """
 
        raise NotImplementedError("not implemented in base class")
 

	
 
    def _authenticate(self, userobj, username, passwd, settings, **kwargs):
 
        """
 
        Wrapper to call self.auth() that validates call on it
 
@@ -229,15 +229,15 @@ class KallitheaAuthPluginBase(object):
 
        :param userobj: userobj
 
        :param username: username
 
        :param passwd: plaintext password
 
        :param settings: plugin settings
 
        """
 
        auth = self.auth(userobj, username, passwd, settings, **kwargs)
 
        if auth:
 
        if auth is not None:
 
            return self._validate_auth_return(auth)
 
        return auth
 
        return None
 

	
 
    def _validate_auth_return(self, ret):
 
        if not isinstance(ret, dict):
 
            raise Exception('returned value from auth must be a dict')
 
        for k in self.auth_func_attrs:
 
            if k not in ret:
 
@@ -256,13 +256,13 @@ class KallitheaExternalAuthPlugin(Kallit
 
        """
 
        raise NotImplementedError("Not implemented in base class")
 

	
 
    def _authenticate(self, userobj, username, passwd, settings, **kwargs):
 
        auth = super(KallitheaExternalAuthPlugin, self)._authenticate(
 
            userobj, username, passwd, settings, **kwargs)
 
        if auth:
 
        if auth is not None:
 
            # maybe plugin will clean the username ?
 
            # we should use the return value
 
            username = auth['username']
 
            # if user is not active from our extern type we should fail to auth
 
            # this can prevent from creating users in Kallithea when using
 
            # external authentication, but if it's inactive user we shouldn't
 
@@ -405,15 +405,15 @@ def authenticate(username, password, env
 
        # then auth is correct.
 
        plugin_user = plugin._authenticate(user, username, password,
 
                                           plugin_settings,
 
                                           environ=environ or {})
 
        log.debug('PLUGIN USER DATA: %s' % plugin_user)
 

	
 
        if plugin_user:
 
        if plugin_user is not None:
 
            log.debug('Plugin returned proper authentication data')
 
            return plugin_user
 

	
 
        # we failed to Auth because .auth() method didn't return proper the user
 
        # we failed to Auth because .auth() method didn't return the user
 
        if username:
 
            log.warning("User `%s` failed to authenticate against %s"
 
                        % (username, plugin.__module__))
 
    return None
kallithea/lib/base.py
Show inline comments
 
@@ -162,13 +162,13 @@ class BasicAuth(paste.auth.basic.AuthBas
 
        if 'basic' != authmeth.lower():
 
            return self.build_authentication()
 
        auth = auth.strip().decode('base64')
 
        _parts = auth.split(':', 1)
 
        if len(_parts) == 2:
 
            username, password = _parts
 
            if self.authfunc(username, password, environ):
 
            if self.authfunc(username, password, environ) is not None:
 
                return username
 
        return self.build_authentication()
 

	
 
    __call__ = authenticate
 

	
 

	
 
@@ -176,13 +176,13 @@ class BaseVCSController(object):
 

	
 
    def __init__(self, application, config):
 
        self.application = application
 
        self.config = config
 
        # base path of repo locations
 
        self.basepath = self.config['base_path']
 
        #authenticate this VCS request using authfunc
 
        # authenticate this VCS request using the authentication modules
 
        self.authenticate = BasicAuth('', auth_modules.authenticate,
 
                                      config.get('auth_ret_code'))
 
        self.ip_addr = '0.0.0.0'
 

	
 
    def _handle_request(self, environ, start_response):
 
        raise NotImplementedError()
 
@@ -410,13 +410,13 @@ class BaseController(WSGIController):
 
            try:
 
                auth_info = auth_modules.authenticate('', '', request.environ)
 
            except UserCreationError as e:
 
                from kallithea.lib import helpers as h
 
                h.flash(e, 'error', logf=log.error)
 
            else:
 
                if auth_info:
 
                if auth_info is not None:
 
                    username = auth_info['username']
 
                    user = User.get_by_username(username, case_insensitive=True)
 
                    return log_in_user(user, remember=False,
 
                                       is_external_auth=True)
 

	
 
        # User is anonymous
kallithea/lib/middleware/simplegit.py
Show inline comments
 
@@ -121,13 +121,13 @@ class SimpleGit(BaseVCSController):
 
                # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
 
                #==============================================================
 

	
 
                # try to auth based on environ, container auth methods
 
                log.debug('Running PRE-AUTH for container based authentication')
 
                pre_auth = auth_modules.authenticate('', '', environ)
 
                if pre_auth and pre_auth.get('username'):
 
                if pre_auth is not None and pre_auth.get('username'):
 
                    username = pre_auth['username']
 
                log.debug('PRE-AUTH got %s as username' % username)
 

	
 
                # If not authenticated by the container, running basic auth
 
                if not username:
 
                    self.authenticate.realm = \
kallithea/lib/middleware/simplehg.py
Show inline comments
 
@@ -125,13 +125,13 @@ class SimpleHg(BaseVCSController):
 
                # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
 
                #==============================================================
 

	
 
                # try to auth based on environ, container auth methods
 
                log.debug('Running PRE-AUTH for container based authentication')
 
                pre_auth = auth_modules.authenticate('', '', environ)
 
                if pre_auth and pre_auth.get('username'):
 
                if pre_auth is not None and pre_auth.get('username'):
 
                    username = pre_auth['username']
 
                log.debug('PRE-AUTH got %s as username' % username)
 

	
 
                # If not authenticated by the container, running basic auth
 
                if not username:
 
                    self.authenticate.realm = \
kallithea/model/validators.py
Show inline comments
 
@@ -269,13 +269,13 @@ def ValidOldPassword(username):
 
        messages = {
 
            'invalid_password': _('Invalid old password')
 
        }
 

	
 
        def validate_python(self, value, state):
 
            from kallithea.lib import auth_modules
 
            if not auth_modules.authenticate(username, value, ''):
 
            if auth_modules.authenticate(username, value, '') is None:
 
                msg = M(self, 'invalid_password', state)
 
                raise formencode.Invalid(msg, value, state,
 
                    error_dict=dict(current_password=msg)
 
                )
 
    return _validator
 

	
 
@@ -306,13 +306,15 @@ def ValidAuth():
 
        def validate_python(self, value, state):
 
            from kallithea.lib import auth_modules
 

	
 
            password = value['password']
 
            username = value['username']
 

	
 
            if not auth_modules.authenticate(username, password):
 
            # authenticate returns unused dict but has called
 
            # plugin._authenticate which has create_or_update'ed the username user in db
 
            if auth_modules.authenticate(username, password) is None:
 
                user = User.get_by_username(username)
 
                if user and not user.active:
 
                    log.warning('user %s is disabled' % username)
 
                    msg = M(self, 'disabled_account', state)
 
                    raise formencode.Invalid(msg, value, state,
 
                        error_dict=dict(username=msg)
0 comments (0 inline, 0 general)