Changeset - 03afa7766ac7
[Not reviewed]
default
0 7 0
Mads Kiilerich - 10 years ago 2015-07-31 15:44:07
madski@unity3d.com
auth: consistently use the name 'user_data' for the dict with data for the authenticated user
7 files changed with 50 insertions and 50 deletions:
0 comments (0 inline, 0 general)
kallithea/lib/auth_modules/__init__.py
Show inline comments
 
@@ -222,90 +222,90 @@ class KallitheaAuthPluginBase(object):
 
        """
 
        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
 

	
 
        :param userobj: userobj
 
        :param username: username
 
        :param passwd: plaintext password
 
        :param settings: plugin settings
 
        """
 
        auth = self.auth(userobj, username, passwd, settings, **kwargs)
 
        if auth is not None:
 
            return self._validate_auth_return(auth)
 
        user_data = self.auth(userobj, username, passwd, settings, **kwargs)
 
        if user_data is not None:
 
            return self._validate_auth_return(user_data)
 
        return None
 

	
 
    def _validate_auth_return(self, ret):
 
        if not isinstance(ret, dict):
 
    def _validate_auth_return(self, user_data):
 
        if not isinstance(user_data, dict):
 
            raise Exception('returned value from auth must be a dict')
 
        for k in self.auth_func_attrs:
 
            if k not in ret:
 
            if k not in user_data:
 
                raise Exception('Missing %s attribute from returned data' % k)
 
        return ret
 
        return user_data
 

	
 

	
 
class KallitheaExternalAuthPlugin(KallitheaAuthPluginBase):
 
    def use_fake_password(self):
 
        """
 
        Return a boolean that indicates whether or not we should set the user's
 
        password to a random value when it is authenticated by this plugin.
 
        If your plugin provides authentication, then you will generally want this.
 

	
 
        :returns: boolean
 
        """
 
        raise NotImplementedError("Not implemented in base class")
 

	
 
    def _authenticate(self, userobj, username, passwd, settings, **kwargs):
 
        auth = super(KallitheaExternalAuthPlugin, self)._authenticate(
 
        user_data = super(KallitheaExternalAuthPlugin, self)._authenticate(
 
            userobj, username, passwd, settings, **kwargs)
 
        if auth is not None:
 
        if user_data is not None:
 
            # maybe plugin will clean the username ?
 
            # we should use the return value
 
            username = auth['username']
 
            username = user_data['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
 
            # create that user anyway
 
            if auth['active_from_extern'] is False:
 
            if user_data['active_from_extern'] is False:
 
                log.warning("User %s authenticated against %s, but is inactive"
 
                            % (username, self.__module__))
 
                return None
 

	
 
            if self.use_fake_password():
 
                # Randomize the PW because we don't need it, but don't want
 
                # them blank either
 
                passwd = PasswordGenerator().gen_password(length=8)
 

	
 
            log.debug('Updating or creating user info from %s plugin'
 
                      % self.name)
 
            user = UserModel().create_or_update(
 
                username=username,
 
                password=passwd,
 
                email=auth["email"],
 
                firstname=auth["firstname"],
 
                lastname=auth["lastname"],
 
                active=auth["active"],
 
                admin=auth["admin"],
 
                extern_name=auth["extern_name"],
 
                email=user_data["email"],
 
                firstname=user_data["firstname"],
 
                lastname=user_data["lastname"],
 
                active=user_data["active"],
 
                admin=user_data["admin"],
 
                extern_name=user_data["extern_name"],
 
                extern_type=self.name
 
            )
 
            Session().flush()
 
            # enforce user is just in given groups, all of them has to be ones
 
            # created from plugins. We store this info in _group_data JSON field
 
            groups = auth['groups'] or []
 
            groups = user_data['groups'] or []
 
            UserGroupModel().enforce_groups(user, groups, self.name)
 
            Session().commit()
 
        return auth
 
        return user_data
 

	
 

	
 
def importplugin(plugin):
 
    """
 
    Imports and returns the authentication plugin in the module named by plugin
 
    (e.g., plugin='kallithea.lib.auth_modules.auth_internal'). Returns the
 
    KallitheaAuthPluginBase subclass on success, raises exceptions on failure.
 

	
 
    raises:
 
        AttributeError -- no KallitheaAuthPlugin class in the module
 
        TypeError -- if the KallitheaAuthPlugin is not a subclass of ours KallitheaAuthPluginBase
 
        ImportError -- if we couldn't import the plugin at all
 
@@ -350,25 +350,25 @@ def loadplugin(plugin):
 
                        "forbidden." % plugin)
 
    return plugin
 

	
 

	
 
def authenticate(username, password, environ=None):
 
    """
 
    Authentication function used for access control,
 
    It tries to authenticate based on enabled authentication modules.
 

	
 
    :param username: username can be empty for container auth
 
    :param password: password can be empty for container auth
 
    :param environ: environ headers passed for container auth
 
    :returns: None if auth failed, plugin_user dict if auth is correct
 
    :returns: None if auth failed, user_data dict if auth is correct
 
    """
 

	
 
    auth_plugins = Setting.get_auth_plugins()
 
    log.debug('Authentication against %s plugins' % (auth_plugins,))
 
    for module in auth_plugins:
 
        try:
 
            plugin = loadplugin(module)
 
        except (ImportError, AttributeError, TypeError), e:
 
            raise ImportError('Failed to load authentication module %s : %s'
 
                              % (module, str(e)))
 
        log.debug('Trying authentication using ** %s **' % (module,))
 
        # load plugin settings from Kallithea database
 
@@ -394,26 +394,26 @@ def authenticate(username, password, env
 
                      % (module, user))
 
            continue
 
        else:
 
            log.debug('Plugin %s accepted user `%s` for authentication'
 
                      % (module, user))
 

	
 
        log.info('Authenticating user using %s plugin' % plugin.__module__)
 
        # _authenticate is a wrapper for .auth() method of plugin.
 
        # it checks if .auth() sends proper data. For KallitheaExternalAuthPlugin
 
        # it also maps users to Database and maps the attributes returned
 
        # from .auth() to Kallithea database. If this function returns data
 
        # then auth is correct.
 
        plugin_user = plugin._authenticate(user, username, password,
 
        user_data = plugin._authenticate(user, username, password,
 
                                           plugin_settings,
 
                                           environ=environ or {})
 
        log.debug('PLUGIN USER DATA: %s' % plugin_user)
 
        log.debug('PLUGIN USER DATA: %s' % user_data)
 

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

	
 
        # 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/auth_modules/auth_container.py
Show inline comments
 
@@ -168,27 +168,27 @@ class KallitheaAuthPlugin(auth_modules.K
 
        # if cannot fetch username, it's a no-go for this plugin to proceed
 
        if not username:
 
            return None
 

	
 
        # old attrs fetched from Kallithea database
 
        admin = getattr(userobj, 'admin', False)
 
        active = getattr(userobj, 'active', True)
 
        email = getattr(userobj, 'email', '')
 
        firstname = getattr(userobj, 'firstname', '')
 
        lastname = getattr(userobj, 'lastname', '')
 
        extern_type = getattr(userobj, 'extern_type', '')
 

	
 
        user_attrs = {
 
        user_data = {
 
            'username': username,
 
            'firstname': safe_unicode(firstname or username),
 
            'lastname': safe_unicode(lastname or ''),
 
            'groups': [],
 
            'email': email or '',
 
            'admin': admin or False,
 
            'active': active,
 
            'active_from_extern': True,
 
            'extern_name': username,
 
            'extern_type': extern_type,
 
        }
 

	
 
        log.info('user `%s` authenticated correctly' % user_attrs['username'])
 
        return user_attrs
 
        log.info('user `%s` authenticated correctly' % user_data['username'])
 
        return user_data
kallithea/lib/auth_modules/auth_crowd.py
Show inline comments
 
@@ -213,32 +213,32 @@ class KallitheaAuthPlugin(auth_modules.K
 
        res = server.user_groups(crowd_user["name"])
 
        log.debug("Crowd groups: \n%s" % (formatted_json(res)))
 
        crowd_user["groups"] = [x["name"] for x in res["groups"]]
 

	
 
        # old attrs fetched from Kallithea database
 
        admin = getattr(userobj, 'admin', False)
 
        active = getattr(userobj, 'active', True)
 
        email = getattr(userobj, 'email', '')
 
        firstname = getattr(userobj, 'firstname', '')
 
        lastname = getattr(userobj, 'lastname', '')
 
        extern_type = getattr(userobj, 'extern_type', '')
 

	
 
        user_attrs = {
 
        user_data = {
 
            'username': username,
 
            'firstname': crowd_user["first-name"] or firstname,
 
            'lastname': crowd_user["last-name"] or lastname,
 
            'groups': crowd_user["groups"],
 
            'email': crowd_user["email"] or email,
 
            'admin': admin,
 
            'active': active,
 
            'active_from_extern': crowd_user.get('active'),
 
            'extern_name': crowd_user["name"],
 
            'extern_type': extern_type,
 
        }
 

	
 
        # set an admin if we're in admin_groups of crowd
 
        for group in settings["admin_groups"].split(","):
 
            if group in user_attrs["groups"]:
 
                user_attrs["admin"] = True
 
        log.debug("Final crowd user object: \n%s" % (formatted_json(user_attrs)))
 
        log.info('user %s authenticated correctly' % user_attrs['username'])
 
        return user_attrs
 
            if group in user_data["groups"]:
 
                user_data["admin"] = True
 
        log.debug("Final crowd user object: \n%s" % (formatted_json(user_data)))
 
        log.info('user %s authenticated correctly' % user_data['username'])
 
        return user_data
kallithea/lib/auth_modules/auth_internal.py
Show inline comments
 
@@ -59,42 +59,42 @@ class KallitheaAuthPlugin(auth_modules.K
 
        return super(KallitheaAuthPlugin, self).accepts(user,
 
                                                        accepts_empty=False)
 

	
 
    def auth(self, userobj, username, password, settings, **kwargs):
 
        if not userobj:
 
            log.debug('userobj was:%s skipping' % (userobj, ))
 
            return None
 
        if userobj.extern_type != self.name:
 
            log.warning("userobj:%s extern_type mismatch got:`%s` expected:`%s`"
 
                     % (userobj, userobj.extern_type, self.name))
 
            return None
 

	
 
        user_attrs = {
 
        user_data = {
 
            "username": userobj.username,
 
            "firstname": userobj.firstname,
 
            "lastname": userobj.lastname,
 
            "groups": [],
 
            "email": userobj.email,
 
            "admin": userobj.admin,
 
            "active": userobj.active,
 
            "active_from_extern": userobj.active,
 
            "extern_name": userobj.user_id,
 
            'extern_type': userobj.extern_type,
 
        }
 

	
 
        log.debug(formatted_json(user_attrs))
 
        log.debug(formatted_json(user_data))
 
        if userobj.active:
 
            from kallithea.lib import auth
 
            password_match = auth.KallitheaCrypto.hash_check(password, userobj.password)
 
            if userobj.username == User.DEFAULT_USER and userobj.active:
 
                log.info('user %s authenticated correctly as anonymous user' %
 
                         username)
 
                return user_attrs
 
                return user_data
 

	
 
            elif userobj.username == username and password_match:
 
                log.info('user %s authenticated correctly' % user_attrs['username'])
 
                return user_attrs
 
                log.info('user %s authenticated correctly' % user_data['username'])
 
                return user_data
 
            log.error("user %s had a bad password" % username)
 
            return None
 
        else:
 
            log.warning('user %s tried auth but is disabled' % username)
 
            return None
kallithea/lib/auth_modules/auth_ldap.py
Show inline comments
 
@@ -331,33 +331,33 @@ class KallitheaAuthPlugin(auth_modules.K
 
            log.debug('Got ldap DN response %s' % user_dn)
 

	
 
            get_ldap_attr = lambda k: ldap_attrs.get(settings.get(k), [''])[0]
 

	
 
            # old attrs fetched from Kallithea database
 
            admin = getattr(userobj, 'admin', False)
 
            active = getattr(userobj, 'active', self.user_activation_state())
 
            email = getattr(userobj, 'email', '')
 
            firstname = getattr(userobj, 'firstname', '')
 
            lastname = getattr(userobj, 'lastname', '')
 
            extern_type = getattr(userobj, 'extern_type', '')
 

	
 
            user_attrs = {
 
            user_data = {
 
                'username': username,
 
                'firstname': safe_unicode(get_ldap_attr('attr_firstname') or firstname),
 
                'lastname': safe_unicode(get_ldap_attr('attr_lastname') or lastname),
 
                'groups': [],
 
                'email': get_ldap_attr('attr_email') or email,
 
                'admin': admin,
 
                'active': active,
 
                "active_from_extern": None,
 
                'extern_name': user_dn,
 
                'extern_type': extern_type,
 
            }
 
            log.info('user %s authenticated correctly' % user_attrs['username'])
 
            return user_attrs
 
            log.info('user %s authenticated correctly' % user_data['username'])
 
            return user_data
 

	
 
        except (LdapUsernameError, LdapPasswordError, LdapImportError):
 
            log.error(traceback.format_exc())
 
            return None
 
        except (Exception,):
 
            log.error(traceback.format_exc())
 
            return None
kallithea/lib/auth_modules/auth_pam.py
Show inline comments
 
@@ -102,39 +102,39 @@ class KallitheaAuthPlugin(auth_modules.K
 
                return None
 
        else:
 
            log.debug("Using cached auth for user: %s" % (username,))
 

	
 
        # old attrs fetched from Kallithea database
 
        admin = getattr(userobj, 'admin', False)
 
        active = getattr(userobj, 'active', True)
 
        email = getattr(userobj, 'email', '') or "%s@%s" % (username, socket.gethostname())
 
        firstname = getattr(userobj, 'firstname', '')
 
        lastname = getattr(userobj, 'lastname', '')
 
        extern_type = getattr(userobj, 'extern_type', '')
 

	
 
        user_attrs = {
 
        user_data = {
 
            'username': username,
 
            'firstname': firstname,
 
            'lastname': lastname,
 
            'groups': [g.gr_name for g in grp.getgrall() if username in g.gr_mem],
 
            'email': email,
 
            'admin': admin,
 
            'active': active,
 
            "active_from_extern": None,
 
            'extern_name': username,
 
            'extern_type': extern_type,
 
        }
 

	
 
        try:
 
            user_data = pwd.getpwnam(username)
 
            regex = settings["gecos"]
 
            match = re.search(regex, user_data.pw_gecos)
 
            if match:
 
                user_attrs["firstname"] = match.group('first_name')
 
                user_attrs["lastname"] = match.group('last_name')
 
                user_data["firstname"] = match.group('first_name')
 
                user_data["lastname"] = match.group('last_name')
 
        except Exception:
 
            log.warning("Cannot extract additional info for PAM user %s", username)
 
            pass
 

	
 
        log.debug("pamuser: \n%s" % formatted_json(user_attrs))
 
        log.info('user %s authenticated correctly' % user_attrs['username'])
 
        return user_attrs
 
        log.debug("pamuser: \n%s" % formatted_json(user_data))
 
        log.info('user %s authenticated correctly' % user_data['username'])
 
        return user_data
kallithea/lib/base.py
Show inline comments
 
@@ -399,31 +399,31 @@ class BaseController(WSGIController):
 
                # the fly can throw UserCreationError to signal issues with
 
                # user creation. Explanation should be provided in the
 
                # exception object.
 
                from kallithea.lib import helpers as h
 
                h.flash(e, 'error', logf=log.error)
 

	
 
        # Authenticate by auth_container plugin (if enabled)
 
        if any(
 
            auth_modules.importplugin(name).is_container_auth
 
            for name in Setting.get_auth_plugins()
 
        ):
 
            try:
 
                auth_info = auth_modules.authenticate('', '', request.environ)
 
                user_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 is not None:
 
                    username = auth_info['username']
 
                if user_info is not None:
 
                    username = user_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
 
        return AuthUser()
 

	
 
    def __call__(self, environ, start_response):
 
        """Invoke the Controller"""
 

	
 
        # WSGIController.__call__ dispatches to the Controller method
 
        # the request is routed to. This routing information is
0 comments (0 inline, 0 general)