Пример #1
0
    def get_user(self, username):
        """ Get a user's attributes

        :param username: '******' attribute of the user
        :type username: string
        :rtype: dict ( {<attr>: <value>} )

        .. warning:: raise UserDoesntExist if user doesn't exist
        """
        mysql_client = self._connect()
        cursor = mysql_client.cursor()

        query = 'SELECT * FROM user WHERE user = %s'
        cursor.execute(query, [username])
        result = cursor.fetchall()

        if not result:
            cursor.close()
            mysql_client.close()
            raise UserDoesntExist(username, self.backend_name)

        cols = cursor.column_names
        ret = dict(zip(cols, result[0]))

        cursor.close()
        mysql_client.close()

        return ret
Пример #2
0
 def _get_princ(self, principal, as_admin=False):
     with self.kadm(as_admin) as kadm:
         obj = kadm.getprinc(principal)
         if obj:
             return obj
         else:
             raise UserDoesntExist(principal, self.backend_name)
Пример #3
0
 def del_from_groups(self, username, groups):
     """Delete user from groups"""
     # it follows the same logic than add_to_groups
     # but with MOD_DELETE
     ldap_client = self._bind()
     tmp = self._get_user(self._str(username), ALL_ATTRS)
     if tmp is None:
         raise UserDoesntExist(username, self.backend_name)
     dn = tmp[0]
     attrs = tmp[1]
     attrs['dn'] = dn
     self._normalize_group_attrs(attrs)
     dn = self._str(tmp[0])
     for group in groups:
         group = self._str(group)
         for attr in self.group_attrs:
             content = self._str(self.group_attrs[attr] % attrs)
             ldif = [(ldap.MOD_DELETE, attr, content)]
             try:
                 ldap_client.modify_s(group, ldif)
             except ldap.NO_SUCH_ATTRIBUTE as e:
                 self._logger(severity=logging.INFO,
                              msg="%(backend)s: user '%(user)s'"
                              " wasn't member of group '%(group)s'"
                              " (attribute '%(attr)s')" % {
                                  'user': username,
                                  'group': self._uni(group),
                                  'attr': attr,
                                  'backend': self.backend_name
                              })
             except Exception as e:
                 ldap_client.unbind_s()
                 self._exception_handler(e)
     ldap_client.unbind_s()
Пример #4
0
    def set_attrs(self, username, attrs):
        """ Set a list of attributes for a given user

        :param username: '******' attribute of the user
        :type username: string
        :param attrs: attributes of the user
        :type attrs: dict ({<attr>: <value>})
        """
        mysql_client = self._connect()
        cursor = mysql_client.cursor()

        query = ("SELECT user  FROM user WHERE user = %s")
        cursor.execute(query, [username])
        result = cursor.fetchall()

        if not result:
            cursor.close()
            mysql_client.close()
            raise UserDoesntExist(username, self.backend_name)

        if 'password' in attrs:
            attrs['password'] = hashlib.sha1(attrs['password']).hexdigest()

        query = 'UPDATE user SET {} WHERE user = %s'.format(', '.join(
            '{}=%s'.format(k) for k in attrs))
        cursor.execute(query, attrs.values() + [username])
        mysql_client.commit()
        cursor.close()
        mysql_client.close()
Пример #5
0
    def set_attrs(self, username, attrs):
        """ set user attributes"""
        ldap_client = self._bind()
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        if tmp is None:
            raise UserDoesntExist(username, self.backend_name)
        dn = self._byte_p2(tmp[0])
        old_attrs = tmp[1]
        for attr in attrs:
            # skip equal attributes
            if not self.__isModify(username, attrs, old_attrs, attr):
                continue
            else:
                self._logger(severity=logging.DEBUG,
                             msg="%(backend)s: modifying user '%(user)s':"
                             " '%(attr)s' vs. '%(oldAttr)s'" % {
                                 'user': username,
                                 'attr': attrs[attr],
                                 'oldAttr': old_attrs.get(attr),
                                 'backend': self.backend_name
                             })
            bcontent = self._byte_p2(attrs[attr])
            battr = self._byte_p2(attr)
            new = {battr: self._modlist(self._byte_p3(bcontent))}
            # if attr is dn entry, use rename
            if attr.lower() == self.dn_user_attr.lower():
                ldap_client.rename_s(dn,
                                     ldap.dn.dn2str([[(battr, bcontent, 1)]]))
                dn = ldap.dn.dn2str([[(battr, bcontent, 1)]] +
                                    ldap.dn.str2dn(dn)[1:])
            else:
                # if attr is already set, replace the value
                # (see dict old passed to modifyModlist)
                if attr in old_attrs:
                    if type(old_attrs[attr]) is list:
                        tmp = []
                        for value in old_attrs[attr]:
                            tmp.append(self._byte_p2(value))
                        bold_value = tmp
                    else:
                        bold_value = self._modlist(
                            self._byte_p3(old_attrs[attr]))
                    old = {battr: bold_value}
                # attribute is not set, just add it
                else:
                    old = {}
                ldif = modlist.modifyModlist(old, new)
                if ldif:
                    try:
                        ldap_client.modify_s(dn, ldif)
                    except Exception as e:
                        ldap_client.unbind_s()
                        self._exception_handler(e)

        ldap_client.unbind_s()
Пример #6
0
    def get_groups(self, username):
        """ Get a user's groups

        :param username: '******' attribute of the user
        :type username: string
        :rtype: list of groups
        """
        try:
            return self.users[username]['groups']
        except:
            raise UserDoesntExist(username, self.backend_name)
Пример #7
0
    def del_user(self, username):
        """ Delete a user from the backend

        :param username: '******' attribute of the user
        :type username: string

        """
        self._check_fix_users(username)
        try:
            del self.users[username]
        except:
            raise UserDoesntExist(username, self.backend_name)
Пример #8
0
 def del_user(self, username):
     """delete a user"""
     ldap_client = self._bind()
     # recover the user dn
     dn = self._str(self._get_user(self._str(username), NO_ATTR))
     # delete
     if dn is not None:
         ldap_client.delete_s(dn)
     else:
         ldap_client.unbind_s()
         raise UserDoesntExist(username, self.backend_name)
     ldap_client.unbind_s()
Пример #9
0
    def set_attrs(self, username, attrs):
        """ set user attributes"""
        ldap_client = self._bind()
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        if tmp is None:
            raise UserDoesntExist(username, self.backend_name)
        dn = self._byte_p2(tmp[0])
        old_attrs = tmp[1]

        for attr in self._remove_hidden_attrs(attrs):
            bcontent = self._byte_p2(attrs[attr])
            battr = self._byte_p2(attr)
            new = {battr: self._modlist(self._byte_p3(bcontent))}
            # if attr is dn entry, use rename
            if attr.lower() == self.dn_user_attr.lower():
                # ... but only if username changes
                if attrs[attr] != username:
                    ldap_client.rename_s(
                        dn,
                        ldap.dn.dn2str([[(battr, bcontent, 1)]])
                        )
                    dn = ldap.dn.dn2str(
                        [[(battr, bcontent, 1)]] + ldap.dn.str2dn(dn)[1:]
                        )
            else:
                # if attr is already set, replace the value
                # (see dict old passed to modifyModlist)
                if attr in old_attrs:
                    if type(old_attrs[attr]) is list:
                        tmp = []
                        for value in old_attrs[attr]:
                            tmp.append(self._byte_p2(value))
                        bold_value = tmp
                    else:
                        bold_value = self._modlist(
                            self._byte_p3(old_attrs[attr])
                        )
                    old = {battr: bold_value}
                # attribute is not set, just add it
                else:
                    old = {}
                ldif = modlist.modifyModlist(old, new)
                if ldif:
                    try:
                        ldap_client.modify_s(dn, ldif)
                    except ldap.INSUFFICIENT_ACCESS as e:
                        raise PermissionDenied(dn, self.backend_name)
                    except Exception as e:
                        ldap_client.unbind_s()
                        self._exception_handler(e)

        ldap_client.unbind_s()
Пример #10
0
    def get_user(self, username):
        """ Get a user's attributes

        :param username: '******' attribute of the user
        :type username: string
        :rtype: dict ( {<attr>: <value>} )

        .. warning:: raise UserDoesntExist if user doesn't exist
        """
        try:
            return self.users[username]
        except:
            raise UserDoesntExist(username, self.backend_name)
Пример #11
0
 def get_user(self, username):
     """Gest a specific user"""
     ret = {}
     tmp = self._get_user(self._str(username), ALL_ATTRS)
     if tmp is None:
         raise UserDoesntExist(username, self.backend_name)
     attrs_tmp = tmp[1]
     for attr in attrs_tmp:
         value_tmp = attrs_tmp[attr]
         if len(value_tmp) == 1:
             ret[attr] = value_tmp[0]
         else:
             ret[attr] = value_tmp
     return ret
Пример #12
0
 def get_user(self, username):
     """Gest a specific user"""
     ret = {}
     tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
     if tmp is None:
         raise UserDoesntExist(username, self.backend_name)
     ret['_dn'] = tmp[0]
     ret['_parent_dn'] = ','.join(tmp[0].split(',')[1:])
     attrs_tmp = tmp[1]
     for attr in attrs_tmp:
         value_tmp = attrs_tmp[attr]
         if len(value_tmp) == 1:
             ret[attr] = value_tmp[0]
         else:
             ret[attr] = value_tmp
     return ret
Пример #13
0
    def set_attrs(self, username, attrs):
        """ Set user attributes"""
        ldap_client = self._bind()
        tmp = self._get_user(self._str(username), ALL_ATTRS)
        if tmp is None:
            raise UserDoesntExist(username, self.backend_name)
        dn = self._str(tmp[0])
        old_attrs = tmp[1]
        for attr in attrs:
            bcontent = self._str(attrs[attr])
            battr = self._str(attr)
            new = {battr: [bcontent]}
            # if attr is dn entry, use rename
            if attr.lower() == self.dn_user_attr.lower():
                ldap_client.rename_s(dn,
                                     ldap.dn.dn2str([[(battr, bcontent, 1)]]))
                dn = ldap.dn.dn2str([[(battr, bcontent, 1)]] +
                                    ldap.dn.str2dn(dn)[1:])
            else:
                # if attr is already set, replace the value
                # (see dict old passed to modifyModlist)
                if attr in old_attrs:
                    if type(old_attrs[attr]) is list:
                        tmp = []
                        for value in old_attrs[attr]:
                            tmp.append(self._str(value))
                        bold_value = tmp
                    else:
                        bold_value = [self._str(old_attrs[attr])]
                    old = {battr: bold_value}
                # attribute is not set, just add it
                else:
                    old = {}

                ldif = modlist.modifyModlist(old, new)

                if not ldif:
                    continue

                try:
                    ldap_client.modify_s(dn, ldif)
                except Exception as e:
                    ldap_client.unbind_s()
                    self._exception_handler(e)

        ldap_client.unbind_s()
Пример #14
0
 def get_user_email(self, user_or_email):
     """Get a specific user by username or email address"""
     if not (self.user_email_filter_tmpl and self.email_user_attr):
         return None
     ret = {}
     tmp = self._get_user_email(self._byte_p2(user_or_email))
     if tmp is None:
         raise UserDoesntExist(user_or_email, self.backend_name)
     ret['_dn'] = tmp[0]
     ret['_parent_dn'] = ','.join(tmp[0].split(',')[1:])
     attrs_tmp = tmp[1]
     for attr in attrs_tmp:
         value_tmp = attrs_tmp[attr]
         if len(value_tmp) == 1:
             ret[attr] = value_tmp[0]
         else:
             ret[attr] = value_tmp
     return ret
Пример #15
0
 def del_user(self, username):
     """delete a user"""
     ldap_client = self._bind()
     # recover the user dn
     dn = self._byte_p2(self._get_user(self._byte_p2(username), NO_ATTR))
     # delete
     if dn is not None:
         groups = self.get_groups(username)
         self._logger(
             severity=logging.DEBUG,
             msg="%(backend)s: removing user '%(user)s' from '%(group)s'" %
             {
                 'user': username,
                 'group': groups,
                 'backend': self.backend_name
             })
         self.del_from_groups(username, groups)
         ldap_client.delete_s(dn)
     else:
         ldap_client.unbind_s()
         raise UserDoesntExist(username, self.backend_name)
     ldap_client.unbind_s()
Пример #16
0
    def del_user(self, username):
        """ Delete a user from the backend

        :param username: '******' attribute of the user
        :type username: string

        """
        mysql_client = self._connect()
        cursor = mysql_client.cursor()

        query = ("SELECT user  FROM user WHERE user = %s")
        cursor.execute(query, [username])
        result = cursor.fetchall()

        if not result:
            cursor.close()
            mysql_client.close()
            raise UserDoesntExist(username, self.backend_name)

        query = ("DELETE FROM user WHERE user = %s")
        cursor.execute(query, [username])
        mysql_client.commit()
        cursor.close()
        mysql_client.close()
Пример #17
0
 def _del_princ(self, principal):
     with self.kadm() as kadm:
         try:
             kadm.delprinc(principal)
         except kadmin.UnknownPrincipalError:
             raise UserDoesntExist(principal, self.backend_name)
Пример #18
0
    def set_attrs(self, username, attrs):
        """ set user attributes"""
        ldap_client = self._bind()
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        if tmp is None:
            raise UserDoesntExist(username, self.backend_name)
        dn = self._byte_p2(tmp[0])
        old_attrs = tmp[1]
        self._logger(
           severity=logging.DEBUG,
           msg="DN,"
           "<====" + str(dn) + "===>",
        )            
        self._logger(
           severity=logging.DEBUG,
           msg="New attributes,"
           "<====" + str(attrs) + "===>",
        )            
        self._logger(
           severity=logging.DEBUG,
           msg="Old Attributes,"
           "<====" + str(old_attrs) + "====>",
        )            
        for attr in attrs:
            bcontent = self._byte_p2(attrs[attr])
            battr = self._byte_p2(attr)
            new = {battr: self._modlist(self._byte_p3(bcontent))}
            # if attr is dn entry, use rename
            if attr.lower() == self.dn_user_attr.lower():
                ldap_client.rename_s(
                    dn,
                    ldap.dn.dn2str([[(battr, bcontent, 1)]])
                    )
                dn = ldap.dn.dn2str(
                    [[(battr, bcontent, 1)]] + ldap.dn.str2dn(dn)[1:]
                    )
            else:
                # if attr is already set, replace the value
                # (see dict old passed to modifyModlist)
                if attr in old_attrs:
                    if type(old_attrs[attr]) is list:
                        tmp = []
                        for value in old_attrs[attr]:
                            tmp.append(self._byte_p2(value))
                        bold_value = tmp
                    else:
                        bold_value = self._modlist(
                            self._byte_p3(old_attrs[attr])
                        )
                    old = {battr: bold_value}
                # attribute is not set, just add it
                else:
                    old = {}
                ldif = modlist.modifyModlist(old, new)
                if ldif:
                    try:
                        ldap_client.modify_s(dn, ldif)
                    except Exception as e:
                        ldap_client.unbind_s()
                        self._exception_handler(e)

        ldap_client.unbind_s()