Пример #1
0
 def setUp(self):
     ServerTests.setUp(self)
     roles = []
     User.get_collection().remove()
     manager = managers.user_manager()
     roles.append(managers.role_manager().super_user_role)
     manager.create_user(login=self.USER[0], password=self.USER[1], roles=roles)
Пример #2
0
 def setUp(self):
     ServerTests.setUp(self)
     roles = []
     User.get_collection().remove()
     manager = managers.user_manager()
     roles.append(managers.role_manager().super_user_role)
     manager.create_user(login=self.USER[0], password=self.USER[1], roles=roles)
Пример #3
0
    def delete_user(login):
        """
        Deletes the given user. Deletion of last superuser is not permitted.

        @param login: identifies the user being deleted
        @type  login: str

        @raise MissingResource: if the given user does not exist
        @raise InvalidValue: if login value is invalid
        """

        # Raise exception if login is invalid
        if login is None or invalid_type(login, basestring):
            raise InvalidValue(['login'])

        # Check whether user exists
        found = User.get_collection().find_one({'login': login})
        if found is None:
            raise MissingResource(login)

        # Make sure user is not the last super user
        if factory.user_query_manager().is_last_super_user(login):
            raise PulpDataException(_("The last superuser [%s] cannot be deleted" % login))

        # Revoke all permissions from the user
        permission_manager = factory.permission_manager()
        permission_manager.revoke_all_permissions_from_user(login)

        User.get_collection().remove({'login': login})
Пример #4
0
    def add_user_to_role(self, role_id, login):
        """
        Add a user to a role. This has the side-effect of granting all the
        permissions granted to the role to the user.
        
        @type role_id: str
        @param role_id: role identifier
        
        @type login: str
        @param login: login of user
        
        @rtype: bool
        @return: True on success
        
        @raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        if role_id in user['roles']:
            return

        user['roles'].append(role_id)
        User.get_collection().save(user, safe=True)

        for resource, operations in role['permissions'].items():
            factory.permission_manager().grant(resource, login, operations)
Пример #5
0
    def add_user_to_role(role_id, login):
        """
        Add a user to a role. This has the side-effect of granting all the
        permissions granted to the role to the user.

        :param role_id:         role identifier
        :type  role_id:         str
        :param login:           login of user
        :type  login:           str
        :raise MissingResource: if the given role does not exist
        :raise InvalidValue: if some params are invalid
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        if role_id in user['roles']:
            return

        user['roles'].append(role_id)
        User.get_collection().save(user, safe=True)

        for item in role['permissions']:
            factory.permission_manager().grant(item['resource'], login,
                                               item.get('permission', []))
Пример #6
0
Файл: cud.py Проект: nbetm/pulp
    def add_user_to_role(role_id, login):
        """
        Add a user to a role. This has the side-effect of granting all the
        permissions granted to the role to the user.

        :param role_id:         role identifier
        :type  role_id:         str
        :param login:           login of user
        :type  login:           str
        :raise MissingResource: if the given role does not exist
        :raise InvalidValue: if some params are invalid
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        if role_id in user['roles']:
            return

        user['roles'].append(role_id)
        User.get_collection().save(user, safe=True)

        for item in role['permissions']:
            factory.permission_manager().grant(item['resource'], login,
                                               item.get('permission', []))
Пример #7
0
    def add_user_to_role(role_id, login):
        """
        Add a user to a role. This has the side-effect of granting all the
        permissions granted to the role to the user.

        :param role_id:         role identifier
        :type  role_id:         str
        :param login:           login of user
        :type  login:           str
        :raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        if role_id in user['roles']:
            return

        user['roles'].append(role_id)
        User.get_collection().save(user, safe=True)

        for resource, operations in role['permissions'].items():
            factory.permission_manager().grant(resource, login, operations)
Пример #8
0
    def create_user(login, password=None, name=None, roles=None):
        """
        Creates a new Pulp user and adds it to specified to roles.

        @param login: login name / unique identifier for the user
        @type  login: str

        @param password: password for login credentials
        @type  password: str

        @param name: user's full name
        @type  name: str

        @param roles: list of roles user will belong to
        @type  roles: list

        @raise DuplicateResource: if there is already a user with the requested login
        @raise InvalidValue: if any of the fields are unacceptable
        """

        existing_user = User.get_collection().find_one({'login': login})
        if existing_user is not None:
            raise DuplicateResource(login)

        invalid_values = []

        if login is None or _USER_LOGIN_REGEX.match(login) is None:
            invalid_values.append('login')
        if invalid_type(name, basestring):
            invalid_values.append('name')
        if invalid_type(roles, list):
            invalid_values.append('roles')

        if invalid_values:
            raise InvalidValue(invalid_values)

        # Use the login for name of the user if one was not specified
        name = name or login
        roles = roles or None

        # Encode plain-text password
        hashed_password = None
        if password:
            hashed_password = factory.password_manager().hash_password(password)

        # Creation
        create_me = User(login=login, password=hashed_password, name=name, roles=roles)
        User.get_collection().save(create_me)

        # Grant permissions
        permission_manager = factory.permission_manager()
        permission_manager.grant_automatic_permissions_for_user(create_me['login'])

        # Retrieve the user to return the SON object
        created = User.get_collection().find_one({'login': login})
        created.pop('password')

        return created
Пример #9
0
    def test_user_default_permissions(self):
        """
        Tests default permissions given to the user after creation.
        """

        # Setup
        params = {
            'login': '******',
            'name': 'User 1',
            'password': '******',
        }

        # Test
        self.post('/v2/users/', params=params)

        # Verify
        user = User.get_collection().find_one({'login': '******'})
        self.assertTrue(user is not None)

        permission = Permission.get_collection().find_one(
            {'resource': '/v2/users/user-1/'})
        self.assertTrue(permission is not None)
        self.assertTrue(
            next(d for (index, d) in enumerate(permission['users'])
                 if d['username'] == 'user-1') is not None)
        self.assertTrue(
            next(d for (index, d) in enumerate(permission['users'])
                 if d['username'] == 'ws-user') is not None)
Пример #10
0
    def is_last_super_user(self, login):
        """
        Check to see if a user is the last super user

        @type user: str
        @param user: login of user to check

        @rtype: bool
        @return: True if the user is the last super user, False otherwise

        @raise PulpDataException: if no super users are found
        """
        user = User.get_collection().find_one({'login': login})
        role_manager = factory.role_manager()
        if SUPER_USER_ROLE not in user['roles']:
            return False

        users = self.find_users_belonging_to_role(SUPER_USER_ROLE)
        if not users:
            raise PulpDataException(_('no super users defined'))

        if len(users) >= 2:
            return False

        return users[0]['_id'] == user['_id'] # this should be True
Пример #11
0
    def is_last_super_user(self, login):
        """
        Check to see if a user is the last super user

        @type user: str
        @param user: login of user to check

        @rtype: bool
        @return: True if the user is the last super user, False otherwise

        @raise PulpDataException: if no super users are found
        """
        user = User.get_collection().find_one({'login': login})
        role_manager = factory.role_manager()
        if SUPER_USER_ROLE not in user['roles']:
            return False

        users = self.find_users_belonging_to_role(SUPER_USER_ROLE)
        if not users:
            raise PulpDataException(_('no super users defined'))

        if len(users) >= 2:
            return False

        return users[0]['_id'] == user['_id']  # this should be True
Пример #12
0
    def grant(resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.

        :param resource: uri path representing a pulp resource
        :type resource: str
        :param login: login of user to grant permissions to
        :type login: str
        :param operations:list of allowed operations being granted
        :type operations: list or tuple of integers
        """
        # we don't grant permissions to the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(user=login)

        # Make sure resource is a valid string or unicode
        if not isinstance(resource, basestring):
            raise InvalidValue(resource)

        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one({'resource' : resource})
        if permission is None:
            permission = PermissionManager.create_permission(resource)

        current_ops = permission['users'].setdefault(user['login'], [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
Пример #13
0
    def test_user_default_permissions(self):
        """
        Tests default permissions given to the user after creation.
        """

        # Setup
        params = {
            'login' : 'user-1',
            'name' : 'User 1',
            'password' : 'test-password',
        }

        # Test
        self.post('/v2/users/', params=params)

        # Verify
        user = User.get_collection().find_one({'login' : 'user-1'})
        self.assertTrue(user is not None)
        
        permission = Permission.get_collection().find_one({'resource' : '/v2/users/user-1/'})
        self.assertTrue(permission is not None)
        self.assertTrue(next(d for (index, d) in enumerate(permission['users'])
                             if d['username'] == 'user-1') is not None)
        self.assertTrue(next(d for (index, d) in enumerate(permission['users'])
                             if d['username'] == 'ws-user') is not None)
Пример #14
0
Файл: cud.py Проект: ehelms/pulp
    def grant(self, resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.
        
        @type resource: str
        @param resource: uri path representing a pulp resource
        
        @type user: str
        @param user: login of user to grant permissions to
        
        @type operations: list or tuple of integers
        @param operations:list of allowed operations being granted
        """
        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(user=login)
        
        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one({'resource' : resource})
        if permission is None:
            permission = self.create_permission(resource)
            
        current_ops = permission['users'].setdefault(user['login'], [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
Пример #15
0
    def test_post(self):
        """
        Tests using post to create a user.
        """

        # Setup
        params = {
            'login': '******',
            'name': 'User 1',
            'password': '******',
        }

        # Test
        status, body = self.post('/v2/users/', params=params)

        # Verify
        self.assertEqual(201, status)

        self.assertEqual(body['login'], 'user-1')

        user = User.get_collection().find_one({'login': '******'})
        self.assertTrue(user is not None)
        self.assertEqual(params['name'], user['name'])
        self.assertTrue(
            self.password_manager.check_password(user['password'],
                                                 params['password']))
Пример #16
0
    def test_pass_in_principal(self):
        principal = User('me', 'letmein')
        call = ScheduledCall('PT1M',
                             'pulp.tasks.dosomething',
                             principal=principal)

        self.assertEqual(call.principal, principal)
Пример #17
0
    def test_associate_from_repo_no_criteria(self):
        # Setup
        source_repo_id = 'source-repo'
        dest_repo_id = 'dest-repo'

        self.repo_manager.create_repo(source_repo_id)
        self.importer_manager.set_importer(source_repo_id, 'mock-importer', {})

        self.repo_manager.create_repo(dest_repo_id)
        self.importer_manager.set_importer(dest_repo_id, 'mock-importer', {})

        self.content_manager.add_content_unit('mock-type', 'unit-1',
                                              {'key-1': 'unit-1'})
        self.content_manager.add_content_unit('mock-type', 'unit-2',
                                              {'key-1': 'unit-2'})
        self.content_manager.add_content_unit('mock-type', 'unit-3',
                                              {'key-1': 'unit-3'})

        self.manager.associate_unit_by_id(source_repo_id, 'mock-type',
                                          'unit-1')
        self.manager.associate_unit_by_id(source_repo_id, 'mock-type',
                                          'unit-2')
        self.manager.associate_unit_by_id(source_repo_id, 'mock-type',
                                          'unit-3')

        fake_user = User('associate-user', '')
        manager_factory.principal_manager().set_principal(principal=fake_user)

        mock_plugins.MOCK_IMPORTER.import_units.return_value = [
            Unit('mock-type', {'k': 'v'}, {}, '')
        ]

        # Test
        results = self.manager.associate_from_repo(source_repo_id,
                                                   dest_repo_id)
        associated = results['units_successful']

        # Verify
        self.assertEqual(1, len(associated))
        self.assertEqual(associated[0]['type_id'], 'mock-type')
        self.assertEqual(associated[0]['unit_key'], {'k': 'v'})

        self.assertEqual(1, mock_plugins.MOCK_IMPORTER.import_units.call_count)

        args = mock_plugins.MOCK_IMPORTER.import_units.call_args[0]
        kwargs = mock_plugins.MOCK_IMPORTER.import_units.call_args[1]
        self.assertTrue(isinstance(args[0],
                                   Repository))  # repository transfer object
        self.assertEqual(args[0].id,
                         'source-repo')  # repo importing units from
        self.assertEqual(args[1].id, 'dest-repo')  # repo importing units into
        self.assertEqual(None, kwargs['units'])  # units to import
        self.assertTrue(isinstance(args[3], PluginCallConfiguration))  # config

        conduit = args[2]
        self.assertTrue(isinstance(conduit, ImportUnitConduit))

        # Clean Up
        manager_factory.principal_manager().set_principal(principal=None)
Пример #18
0
def _validate_user():
    """
    Validate the User model
    @rtype: int
    @return: number of errors found during validation
    """
    objectdb = User.get_collection()
    reference = User(u'', u'', None, None)
    return _validate_model(User.__name__, objectdb, reference)
Пример #19
0
    def remove_user_from_role(self, role_id, login):
        """
        Remove a user from a role. This has the side-effect of revoking all the
        permissions granted to the role from the user, unless the permissions are
        also granted by another role.
        
        @type role_id: str
        @param role_id: role identifier
    
        @type login: str
        @param login: name of user
        
        @rtype: bool
        @return: True on success
                        
        @raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        if role_id == self.super_user_role and factory.user_query_manager(
        ).is_last_super_user(login):
            raise PulpDataException(
                _('%s cannot be empty, and %s is the last member') %
                (self.super_user_role, login))

        if role_id not in user['roles']:
            return

        user['roles'].remove(role_id)
        User.get_collection().save(user, safe=True)

        for resource, operations in role['permissions'].items():
            other_roles = factory.role_query_manager().get_other_roles(
                role, user['roles'])
            user_ops = _operations_not_granted_by_roles(
                resource, operations, other_roles)
            factory.permission_manager().revoke(resource, login, user_ops)
Пример #20
0
    def find_by_login(self, login):
        """
        Returns a serialized version of the given user if it exists.
        If a user cannot be found with the given login, None is returned.

        @return: serialized data describing the user
        @rtype:  dict or None
        """
        user = User.get_collection().find_one({'login': login})
        return user
Пример #21
0
    def find_by_login(self, login):
        """
        Returns a serialized version of the given user if it exists.
        If a user cannot be found with the given login, None is returned.

        @return: serialized data describing the user
        @rtype:  dict or None
        """
        user = User.get_collection().find_one({'login' : login})
        return user
Пример #22
0
    def remove_user_from_role(role_id, login):
        """
        Remove a user from a role. This has the side-effect of revoking all the
        permissions granted to the role from the user, unless the permissions are
        also granted by another role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param login:           name of user
        :type  login:           str
        :raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        if role_id == SUPER_USER_ROLE and factory.user_query_manager(
        ).is_last_super_user(login):
            raise PulpDataException(
                _('%(role)s cannot be empty, and %(login)s is the last member')
                % {
                    'role': SUPER_USER_ROLE,
                    'login': login
                })

        if role_id not in user['roles']:
            return

        user['roles'].remove(role_id)
        User.get_collection().save(user, safe=True)

        for item in role['permissions']:
            other_roles = factory.role_query_manager().get_other_roles(
                role, user['roles'])
            user_ops = _operations_not_granted_by_roles(
                item['resource'], item['permission'], other_roles)
            factory.permission_manager().revoke(item['resource'], login,
                                                user_ops)
Пример #23
0
    def find_all(self):
        """
        Returns serialized versions of all users in the database.

        @return: list of serialized users
        @rtype:  list of dict
        """
        all_users = list(User.get_collection().find())
        for user in all_users:
            user.pop('password')
        return all_users
Пример #24
0
    def find_all(self):
        """
        Returns serialized versions of all users in the database.

        @return: list of serialized users
        @rtype:  list of dict
        """
        all_users = list(User.get_collection().find())
        for user in all_users:
            user.pop('password')
        return all_users
Пример #25
0
Файл: cud.py Проект: bartwo/pulp
    def remove_user_from_role(self, role_id, login):
        """
        Remove a user from a role. This has the side-effect of revoking all the
        permissions granted to the role from the user, unless the permissions are
        also granted by another role.
        
        @type role_id: str
        @param role_id: role identifier
    
        @type login: str
        @param login: name of user
        
        @rtype: bool
        @return: True on success
                        
        @raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id' : role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(login)

        if role_id == self.super_user_role and factory.user_query_manager().is_last_super_user(login):
            raise PulpDataException(_('%s cannot be empty, and %s is the last member') %
                                     (self.super_user_role, login))

        if role_id not in user['roles']:
            return
        
        user['roles'].remove(role_id)
        User.get_collection().save(user, safe=True)

        for resource, operations in role['permissions'].items():
            other_roles = factory.role_query_manager().get_other_roles(role, user['roles'])
            user_ops = _operations_not_granted_by_roles(resource,
                                                        operations,
                                                        other_roles)
            factory.permission_manager().revoke(resource, login, user_ops)
Пример #26
0
    def find_by_criteria(criteria):
        """
        Return a list of users that match the provided criteria.

        @param criteria:    A Criteria object representing a search you want
                            to perform
        @type  criteria:    pulp.server.db.model.criteria.Criteria

        @return:    list of User instances
        @rtype:     list
        """
        return User.get_collection().query(criteria)
Пример #27
0
    def find_by_criteria(criteria):
        """
        Return a list of users that match the provided criteria.

        @param criteria:    A Criteria object representing a search you want
                            to perform
        @type  criteria:    pulp.server.db.model.criteria.Criteria

        @return:    list of User instances
        @rtype:     list
        """
        return User.get_collection().query(criteria)
Пример #28
0
    def update_user(self, login, delta):
        """
        Updates the user. Following fields may be updated through this call:
        * password
        * name
        * roles

        Other fields found in delta will be ignored.

        @param login: identifies the user
        @type  login: str

        @param delta: list of attributes and their new values to change
        @type  delta: dict

        @raise MissingResource: if there is no user with login
        """

        user_coll = User.get_collection()

        user = user_coll.find_one({'login' : login})
        if user is None:
            raise MissingResource(login)

        # Check
        invalid_values = []
        if 'password' in delta:
            if not isinstance(delta['password'], basestring):
                invalid_values.append('password')
            else:
                user['password'] = password_util.hash_password(delta['password'])

        if 'name' in delta:
            if delta['name'] is not None and not isinstance(delta['name'], basestring):
                invalid_values.append('name')
            else:
                user['name'] = delta['name']

        if 'roles' in delta:
            if delta['roles'] is not None and not isinstance(delta['roles'], list):
                invalid_values.append('roles')
            else:
                user['roles'] = delta['roles']

        if invalid_values:
            raise InvalidValue(invalid_values)

        user_coll.save(user, safe=True)

        return user
Пример #29
0
    def find_by_id_list(self, login_list):
        """
        Returns serialized versions of all of the given users. Any
        login that does not refer to valid user are ignored and will not
        raise an error.

        @param login_list: list of logins
        @type  login_list: list of str

        @return: list of serialized users
        @rtype:  list of dict
        """
        users = list(User.get_collection().find({'id' : {'$in' : login_list}}))
        return users
Пример #30
0
Файл: cud.py Проект: nbetm/pulp
    def remove_user_from_role(role_id, login):
        """
        Remove a user from a role. This has the side-effect of revoking all the
        permissions granted to the role from the user, unless the permissions are
        also granted by another role.

        :param role_id:         role identifier
        :type  role_id:         str
        :param login:           name of user
        :type  login:           str
        :raise MissingResource: if the given role or user does not exist
        """
        role = Role.get_collection().find_one({'id': role_id})
        if role is None:
            raise MissingResource(role_id)

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        if role_id == SUPER_USER_ROLE and factory.user_query_manager().is_last_super_user(login):
            raise PulpDataException(
                _('%(role)s cannot be empty, and %(login)s is the last member') %
                {'role': SUPER_USER_ROLE, 'login': login})

        if role_id not in user['roles']:
            return

        user['roles'].remove(role_id)
        User.get_collection().save(user, safe=True)

        for item in role['permissions']:
            other_roles = factory.role_query_manager().get_other_roles(role, user['roles'])
            user_ops = _operations_not_granted_by_roles(item['resource'],
                                                        item['permission'],
                                                        other_roles)
            factory.permission_manager().revoke(item['resource'], login, user_ops)
Пример #31
0
Файл: query.py Проект: beav/pulp
    def is_superuser(self, login):
        """
        Return True if the user with given login is a super user

        @type user: str
        @param user: login of user to check

        @rtype: bool
        @return: True if the user is a super user, False otherwise
        """
        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        return SUPER_USER_ROLE in user['roles']
Пример #32
0
    def delete_user(self, login):
        """
        Deletes the given user. Deletion of 'admin' user is not permitted.

        @param login: identifies the user being deleted
        @type  login: str

        @raise MissingResource: if the given user does not exist
        @raise InvalidValue: if login value is invalid or
        """

        # Raise exception if login is invalid or 'admin'
        if login is None or not isinstance(login, basestring) or login == 'admin':
            raise InvalidValue(['login'])

        # Validation
        found = User.get_collection().find_one({'login' : login})
        if found is None:
            raise MissingResource(login)

        # Revoke all permissions from the user
        revoke_all_permissions_from_user(login)

        User.get_collection().remove({'login' : login}, safe=True)
Пример #33
0
    def is_superuser(self, login):
        """
        Return True if the user with given login is a super user

        @type user: str
        @param user: login of user to check

        @rtype: bool
        @return: True if the user is a super user, False otherwise
        """
        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        return SUPER_USER_ROLE in user['roles']
Пример #34
0
    def revoke(resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        :param resource:   uri path representing a pulp resource
        :type  resource:   str
        :param login:      login of user to revoke permissions from
        :type  login:      str
        :param operations: list of allowed operations being revoked
        :type  operations: list or tuple of integers

        :raises InvalidValue: if some params are invalid
        """
        permission_query_manager = factory.permission_query_manager()
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        permission = Permission.get_collection().find_one(
            {'resource': resource})
        if permission is None:
            return

        current_ops = permission_query_manager.find_user_permission(
            permission, user['login'])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user from this permission if there are no more allowed operations
        if not current_ops:
            permission_query_manager.delete_user_permission(
                permission, user['login'])

        # delete the permission if there are no more users
        if not permission['users']:
            PermissionManager.delete_permission(resource)
            return

        Permission.get_collection().save(permission)
Пример #35
0
    def test_delete(self):
        """
        Tests deleting an existing user.
        """

        # Setup
        self.user_manager.create_user('doomed')

        # Test
        status, body = self.delete('/v2/users/doomed/')

        # Verify
        self.assertEqual(200, status)

        user = User.get_collection().find_one({'login' : 'doomed'})
        self.assertTrue(user is None)
Пример #36
0
    def find_by_login_list(self, login_list):
        """
        Returns serialized versions of all of the given users. Any
        login that does not refer to valid user are ignored and will not
        raise an error.

        @param login_list: list of logins
        @type  login_list: list of str

        @return: list of serialized users
        @rtype:  list of dict
        """
        users = list(User.get_collection().find({'login' : {'$in' : login_list}}))
        for user in users:
            user.pop('password')
        return users
Пример #37
0
    def test_delete(self):
        """
        Tests deleting an existing user.
        """

        # Setup
        self.user_manager.create_user('doomed')

        # Test
        status, body = self.delete('/v2/users/doomed/')

        # Verify
        self.assertEqual(200, status)

        user = User.get_collection().find_one({'login': '******'})
        self.assertTrue(user is None)
Пример #38
0
    def test_delete(self):
        """
        Tests removing a user from a role.
        """

        # Setup
        self.role_manager.create_role(role_id="role-1")
        self.user_manager.create_user(login="******", roles=["role-1"])

        # Test
        status, body = self.delete("/v2/roles/role-1/users/user-1/")

        # Verify
        self.assertEqual(200, status)

        user = User.get_collection().find_one({"login": "******"})
        self.assertFalse("role-1" in user["roles"])
Пример #39
0
    def test_delete(self):
        """
        Tests removing a user from a role.
        """

        # Setup
        self.role_manager.create_role(role_id='role-1')
        self.user_manager.create_user(login='******', roles=['role-1'])

        # Test
        status, body = self.delete('/v2/roles/role-1/users/user-1/')

        # Verify
        self.assertEqual(200, status)

        user = User.get_collection().find_one({'login': '******'})
        self.assertFalse('role-1' in user['roles'])
Пример #40
0
    def revoke(resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        :param resource:   uri path representing a pulp resource
        :type  resource:   str
        :param login:      login of user to revoke permissions from
        :type  login:      str
        :param operations: list of allowed operations being revoked
        :type  operations: list or tuple of integers

        :raises InvalidValue: if some params are invalid
        """
        permission_query_manager = factory.permission_query_manager()
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        permission = Permission.get_collection().find_one({'resource': resource})
        if permission is None:
            return

        current_ops = permission_query_manager.find_user_permission(permission, user['login'])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user from this permission if there are no more allowed operations
        if not current_ops:
            permission_query_manager.delete_user_permission(permission, user['login'])

        # delete the permission if there are no more users
        if not permission['users']:
            PermissionManager.delete_permission(resource)
            return

        Permission.get_collection().save(permission, safe=True)
Пример #41
0
    def revoke(self, resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        @type resource: str
        @param resource: uri path representing a pulp resource

        @type user: str
        @param user: login of user to revoke permissions from

        @type operations: list or tuple of integers
        @param operations:list of allowed operations being revoked
        """
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(user=login)

        permission = Permission.get_collection().find_one(
            {'resource': resource})
        if permission is None:
            return

        current_ops = permission['users'].get(user['login'], [])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user if there are no more allowed operations
        if not current_ops:
            del permission['users'][user['login']]

        # delete the permission if there are no more users
        if not permission['users']:
            self.delete_permission(resource)
            return

        Permission.get_collection().save(permission, safe=True)
Пример #42
0
    def test_delete(self):
        """
        Tests removing a user from a role.
        """

        # Setup
        self.role_manager.create_role(role_id = 'role-1')
        self.user_manager.create_user(login = '******', roles = ['role-1'])


        # Test
        status, body = self.delete('/v2/roles/role-1/users/user-1/')

        # Verify
        self.assertEqual(200, status)

        user = User.get_collection().find_one({'login' : 'user-1'})
        self.assertFalse('role-1' in user['roles'])
Пример #43
0
    def revoke(self, resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        @type resource: str
        @param resource: uri path representing a pulp resource

        @type user: str
        @param user: login of user to revoke permissions from

        @type operations: list or tuple of integers
        @param operations:list of allowed operations being revoked
        """
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(user=login)

        permission = Permission.get_collection().find_one({'resource' : resource})
        if permission is None:
            return

        current_ops = permission['users'].get(user['login'], [])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user if there are no more allowed operations
        if not current_ops:
            del permission['users'][user['login']]

        # delete the permission if there are no more users
        if not permission['users']:
            self.delete_permission(resource)
            return

        Permission.get_collection().save(permission, safe=True)
Пример #44
0
    def ensure_admin(self):
        """
        This function ensures that there is at least one super user for the system.
        If no super users are found, the default admin user (from the pulp config)
        is looked up or created and added to the super users role.
        """
        role_manager = factory.role_manager()
        if self.get_admins():
            return

        default_login = config.config.get('server', 'default_login')

        admin = User.get_collection().find_one({'login': default_login})
        if admin is None:
            default_password = config.config.get('server', 'default_password')
            admin = UserManager.create_user(login=default_login,
                                            password=default_password)

        role_manager.add_user_to_role(SUPER_USER_ROLE, default_login)
Пример #45
0
    def test_user_default_permissions(self):
        """
        Tests default permissions given to the user after creation.
        """

        # Setup
        params = {"login": "******", "name": "User 1", "password": "******"}

        # Test
        self.post("/v2/users/", params=params)

        # Verify
        user = User.get_collection().find_one({"login": "******"})
        self.assertTrue(user is not None)

        permission = Permission.get_collection().find_one({"resource": "/v2/users/user-1/"})
        self.assertTrue(permission is not None)
        self.assertTrue("user-1" in permission["users"])
        self.assertTrue("ws-user" in permission["users"])
Пример #46
0
    def test_post(self):
        """
        Tests adding a user to a role.
        """

        # Setup
        self.user_manager.create_user(login="******")
        self.role_manager.create_role(role_id="role-1")

        req_body = {"login": "******"}

        # Test
        status, body = self.post("/v2/roles/role-1/users/", params=req_body)

        # Verify
        self.assertEqual(200, status)

        user = User.get_collection().find_one({"login": "******"})
        self.assertTrue(user is not None)
        self.assertEqual(user["roles"], ["role-1"])
Пример #47
0
    def test_post(self):
        """
        Tests using post to create a user.
        """

        # Setup
        params = {"login": "******", "name": "User 1", "password": "******"}

        # Test
        status, body = self.post("/v2/users/", params=params)

        # Verify
        self.assertEqual(201, status)

        self.assertEqual(body["login"], "user-1")

        user = User.get_collection().find_one({"login": "******"})
        self.assertTrue(user is not None)
        self.assertEqual(params["name"], user["name"])
        self.assertTrue(self.password_manager.check_password(user["password"], params["password"]))
Пример #48
0
    def _add_from_ldap(self, username, userdata):
        """
        @param username:  Username to be added
        @param user: tuple of user data as returned by lookup_user

        Adds a user to the pulp user database with no password and
        returns a pulp.server.db.model.User object
        """
        user = User.get_collection().find_one({'login' : username})
        if user is None:
            attrs = userdata[1]
            try:
                name = attrs['gecos']
            except KeyError:
                name = username
            user =  self.user_manager.create_user(login=username, name=name)
            if config.has_option('ldap', 'default_role'):
                role_id = config.get('ldap', 'default_role')
                self.role_manager.add_user_to_role(role_id, username)
                              
        return user
Пример #49
0
    def _add_from_ldap(self, username, userdata):
        """
        @param username:  Username to be added
        @param userdata: tuple of user data as returned by lookup_user

        Adds a user to the pulp user database with no password and
        returns a pulp.server.db.model.User object
        """
        user = User.get_collection().find_one({'login' : username})
        if user is None:
            attrs = userdata[1]
            if 'gecos' in attrs and isinstance(attrs['gecos'], basestring):
                name = attrs['gecos']
            else:
                name = username
            user =  self.user_manager.create_user(login=username, name=name)
            if config.has_option('ldap', 'default_role'):
                role_id = config.get('ldap', 'default_role')
                self.role_manager.add_user_to_role(role_id, username)
                              
        return user
Пример #50
0
 def ensure_admin(self):
     """
     This function ensures that there is at least one super user for the system.
     If no super users are found, the default admin user (from the pulp config)
     is looked up or created and added to the super users role.
     """
     user_query_manager = factory.user_query_manager()
     role_manager = factory.role_manager()
     
     super_users = user_query_manager.find_users_belonging_to_role(role_manager.super_user_role)
     if super_users:
         return
     
     default_login = config.config.get('server', 'default_login')
     
     admin = User.get_collection().find_one({'login' : default_login})
     if admin is None:
         default_password = config.config.get('server', 'default_password')
         admin = factory.user_manager().create_user(login=default_login, password=default_password)
     
     role_manager.add_user_to_role(role_manager.super_user_role, default_login)
Пример #51
0
    def grant(resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.

        :param resource: uri path representing a pulp resource
        :type resource: str
        :param login: login of user to grant permissions to
        :type login: str
        :param operations:list of allowed operations being granted
        :type operations: list or tuple of integers

        :raises InvalidValue: if some params are invalid
        """
        # we don't grant permissions to the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        # Make sure resource is a valid string or unicode
        if not isinstance(resource, basestring):
            raise InvalidValue(resource)

        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one({'resource': resource})
        if permission is None:
            permission = PermissionManager.create_permission(resource)

        current_ops = factory.permission_query_manager().find_user_permission(permission,
                                                                              user['login'],
                                                                              create=True)
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
Пример #52
0
    def test_post(self):
        """
        Tests adding a user to a role.
        """

        # Setup
        self.user_manager.create_user(login='******')
        self.role_manager.create_role(role_id='role-1')

        req_body = {
            'login': '******',
        }

        # Test
        status, body = self.post('/v2/roles/role-1/users/', params=req_body)

        # Verify
        self.assertEqual(200, status)

        user = User.get_collection().find_one({'login': '******'})
        self.assertTrue(user is not None)
        self.assertEqual(user['roles'], ['role-1'])
Пример #53
0
    def test_import_uploaded_unit(self):
        # Setup
        self.repo_manager.create_repo('repo-u')
        self.importer_manager.set_importer('repo-u', 'mock-importer', {})

        key = {'key': 'value'}
        metadata = {'k1': 'v1'}

        importer_return_report = object()
        mock_plugins.MOCK_IMPORTER.upload_unit.return_value = importer_return_report

        upload_id = self.upload_manager.initialize_upload()
        file_path = self.upload_manager._upload_file_path(upload_id)

        fake_user = User('import-user', '')
        manager_factory.principal_manager().set_principal(principal=fake_user)

        # Test
        self.upload_manager.import_uploaded_unit('repo-u', 'mock-type', key,
                                                 metadata, upload_id)

        # Verify
        call_args = mock_plugins.MOCK_IMPORTER.upload_unit.call_args[0]
        self.assertTrue(isinstance(call_args[0], Repository))
        self.assertEqual(call_args[1], 'mock-type')
        self.assertEqual(call_args[2], key)
        self.assertEqual(call_args[3], metadata)
        self.assertEqual(call_args[4], file_path)

        conduit = call_args[5]
        self.assertTrue(isinstance(conduit, UploadConduit))
        self.assertEqual(call_args[5].repo_id, 'repo-u')
        self.assertEqual(conduit.association_owner_type, OWNER_TYPE_USER)
        self.assertEqual(conduit.association_owner_id, fake_user.login)

        # Clean up
        mock_plugins.MOCK_IMPORTER.upload_unit.return_value = None
        manager_factory.principal_manager().set_principal(principal=None)
Пример #54
0
    def grant(self, resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.

        @type resource: str
        @param resource: uri path representing a pulp resource

        @type user: str
        @param user: login of user to grant permissions to

        @type operations: list or tuple of integers
        @param operations:list of allowed operations being granted
        """
        # we don't grant permissions to the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(user=login)

        # Make sure resource is a valid string or unicode
        if not isinstance(resource, basestring):
            raise InvalidValue(resource)

        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one(
            {'resource': resource})
        if permission is None:
            permission = self.create_permission(resource)

        current_ops = permission['users'].setdefault(user['login'], [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
Пример #55
0
    def test_import_uploaded_unit(self):
        self.repo_manager.create_repo('repo-u')
        self.importer_manager.set_importer('repo-u', 'mock-importer', {})

        key = {'key': 'value'}
        metadata = {'k1': 'v1'}

        importer_return_report = object()
        mock_plugins.MOCK_IMPORTER.upload_unit.return_value = importer_return_report

        upload_id = self.upload_manager.initialize_upload()
        file_path = self.upload_manager._upload_file_path(upload_id)

        fake_user = User('import-user', '')
        manager_factory.principal_manager().set_principal(principal=fake_user)

        response = self.upload_manager.import_uploaded_unit(
            'repo-u', 'mock-type', key, metadata, upload_id)

        # import_uploaded_unit() should have returned our importer_return_report
        self.assertTrue(response is importer_return_report)

        call_args = mock_plugins.MOCK_IMPORTER.upload_unit.call_args[0]
        self.assertTrue(isinstance(call_args[0], Repository))
        self.assertEqual(call_args[1], 'mock-type')
        self.assertEqual(call_args[2], key)
        self.assertEqual(call_args[3], metadata)
        self.assertEqual(call_args[4], file_path)

        conduit = call_args[5]
        self.assertTrue(isinstance(conduit, UploadConduit))
        self.assertEqual(call_args[5].repo_id, 'repo-u')

        # Clean up
        mock_plugins.MOCK_IMPORTER.upload_unit.return_value = None
        manager_factory.principal_manager().set_principal(principal=None)
Пример #56
0
    def ensure_admin(self):
        """
        This function ensures that there is at least one super user for the system.
        If no super users are found, the default admin user (from the pulp config)
        is looked up or created and added to the super users role.
        """
        user_query_manager = factory.user_query_manager()
        role_manager = factory.role_manager()

        super_users = user_query_manager.find_users_belonging_to_role(
            role_manager.super_user_role)
        if super_users:
            return

        default_login = config.config.get('server', 'default_login')

        admin = User.get_collection().find_one({'login': default_login})
        if admin is None:
            default_password = config.config.get('server', 'default_password')
            admin = factory.user_manager().create_user(
                login=default_login, password=default_password)

        role_manager.add_user_to_role(role_manager.super_user_role,
                                      default_login)
Пример #57
0
    def test_put(self):
        """
        Tests using put to update a user.
        """

        # Setup
        self.user_manager.create_user('user-1', name='original name')

        req_body = {'delta': {'name': 'new name', 'password': '******'}}

        # Test
        status, body = self.put('/v2/users/user-1/', params=req_body)

        # Verify
        self.assertEqual(200, status)

        self.assertEqual(body['name'], req_body['delta']['name'])

        user = User.get_collection().find_one({'login': '******'})
        self.assertEqual(user['name'], req_body['delta']['name'])

        self.assertTrue(
            self.password_manager.check_password(
                user['password'], req_body['delta']['password']))