Example #1
0
    def test_syntactic_sugar_methods(self):
        """
        Tests the syntactic sugar methods for retrieving specific managers.
        """
        # Setup
        factory.initialize()

        # Test
        self.assertTrue(isinstance(factory.authentication_manager(), AuthenticationManager))
        self.assertTrue(isinstance(factory.cert_generation_manager(), CertGenerationManager))
        self.assertTrue(isinstance(factory.certificate_manager(), CertificateManager))
        self.assertTrue(isinstance(factory.password_manager(), PasswordManager))
        self.assertTrue(isinstance(factory.permission_manager(), PermissionManager))
        self.assertTrue(isinstance(factory.permission_query_manager(), PermissionQueryManager))
        self.assertTrue(isinstance(factory.role_manager(), RoleManager))
        self.assertTrue(isinstance(factory.role_query_manager(), RoleQueryManager))
        self.assertTrue(isinstance(factory.user_manager(), UserManager))             
        self.assertTrue(isinstance(factory.user_query_manager(), UserQueryManager))
        self.assertTrue(isinstance(factory.repo_manager(), RepoManager))
        self.assertTrue(isinstance(factory.repo_unit_association_manager(), RepoUnitAssociationManager))
        self.assertTrue(isinstance(factory.repo_publish_manager(), RepoPublishManager))
        self.assertTrue(isinstance(factory.repo_query_manager(), RepoQueryManager))
        self.assertTrue(isinstance(factory.repo_sync_manager(), RepoSyncManager))
        self.assertTrue(isinstance(factory.content_manager(), ContentManager))
        self.assertTrue(isinstance(factory.content_query_manager(), ContentQueryManager))
        self.assertTrue(isinstance(factory.content_upload_manager(), ContentUploadManager))
        self.assertTrue(isinstance(factory.consumer_manager(), ConsumerManager))
        self.assertTrue(isinstance(factory.topic_publish_manager(), TopicPublishManager))
Example #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)
Example #3
0
    def post(self, request):
        """
        Revoke permissions from a role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: An empty response
        :rtype: django.http.HttpResponse
        """

        params = request.body_as_json
        role_id = params.get('role_id', None)
        resource = params.get('resource', None)
        operation_names = params.get('operations', None)

        _validate_params({'role_id': role_id,
                          'resource': resource,
                          'operation_names': operation_names})

        role_manager = factory.role_manager()
        permission_manager = factory.permission_manager()
        operations = permission_manager.operation_names_to_values(operation_names)
        remove_perm = role_manager.remove_permissions_from_role(role_id, resource, operations)
        return generate_json_response(remove_perm)
Example #4
0
    def post(self, request):
        """
        Grant permissions to a role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: An empty response
        :rtype: django.http.HttpResponse
        """
        params = request.body_as_json
        role_id = params.get('role_id', None)
        resource = params.get('resource', None)
        operation_names = params.get('operations', None)

        _check_invalid_params({'role_id': role_id,
                               'resource': resource,
                               'operation_names': operation_names})

        # Grant permission synchronously
        role_manager = factory.role_manager()
        permission_manager = factory.permission_manager()
        operations = permission_manager.operation_names_to_values(operation_names)
        add_perm = role_manager.add_permissions_to_role(role_id, resource, operations)
        return generate_json_response(add_perm)
Example #5
0
    def POST(self):

        # Params
        params = self.params()
        role_id = params.get('role_id', None)
        resource = params.get('resource', None)
        operation_names = params.get('operations', None)

        _check_invalid_params({
            'role_id': role_id,
            'resource': resource,
            'operation_names': operation_names
        })

        operations = _get_operations(operation_names)

        # Grant permission synchronously
        role_manager = managers.role_manager()

        tags = [
            resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
            action_tag('remove_permission_from_role')
        ]

        call_request = CallRequest(role_manager.remove_permissions_from_role,
                                   [role_id, resource, operations],
                                   tags=tags)
        call_request.updates_resource(dispatch_constants.RESOURCE_ROLE_TYPE,
                                      role_id)

        return self.ok(execution.execute_sync(call_request))
Example #6
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
Example #7
0
def _initialize_pulp():
    # XXX ORDERING COUNTS
    # This initialization order is very sensitive, and each touches a number of
    # sub-systems in pulp. If you get this wrong, you will have pulp tripping
    # over itself on start up. If you do not know where to add something, ASK!
    global _IS_INITIALIZED, STACK_TRACER
    if _IS_INITIALIZED:
        return
    _IS_INITIALIZED = True

    # check our db version and other support
    migration_models.check_package_versions()

    # pulp generic content initialization
    manager_factory.initialize()
    plugin_api.initialize()

    # new async dispatch initialization
    dispatch_factory.initialize()
    dispatch_history.start_reaper_thread()

    # ensure necessary infrastructure
    role_manager = manager_factory.role_manager()
    role_manager.ensure_super_user_role()
    user_manager = manager_factory.user_manager()
    user_manager.ensure_admin()

    # agent services
    AgentServices.start()

    # setup debugging, if configured
    if config.config.getboolean('server', 'debugging_mode'):
        STACK_TRACER = StacktraceDumper()
        STACK_TRACER.start()
Example #8
0
 def populate(self):
     role_manager = manager_factory.role_manager()
     role_manager.create_role(self.ROLE_ID)
     
     for login in self.USER_LOGINS:
         user_manager = manager_factory.user_manager()
         user_manager.create_user(login=login, password=login, roles=[self.ROLE_ID])
Example #9
0
    def POST(self):

        # Params
        params = self.params()
        role_id = params.get('role_id', None)
        resource = params.get('resource', None)
        operation_names = params.get('operations', None)
        
        _check_invalid_params({'role_id':role_id,
                               'resource':resource,
                               'operation_names':operation_names})

        operations = _get_operations(operation_names)
        
        # Grant permission synchronously
        role_manager = managers.role_manager()
        
        tags = [resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
                action_tag('remove_permission_from_role')]

        call_request = CallRequest(role_manager.remove_permissions_from_role,
                                   [role_id, resource, operations],
                                   tags=tags)
        call_request.updates_resource(dispatch_constants.RESOURCE_ROLE_TYPE, role_id)
        
        return self.ok(execution.execute_sync(call_request))
Example #10
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)
Example #11
0
    def test_syntactic_sugar_methods(self):
        """
        Tests the syntactic sugar methods for retrieving specific managers.
        """
        # Setup
        factory.initialize()

        # Test
        self.assertTrue(isinstance(factory.authentication_manager(), AuthenticationManager))
        self.assertTrue(isinstance(factory.cert_generation_manager(), CertGenerationManager))
        self.assertTrue(isinstance(factory.certificate_manager(), CertificateManager))
        self.assertTrue(isinstance(factory.password_manager(), PasswordManager))
        self.assertTrue(isinstance(factory.permission_manager(), PermissionManager))
        self.assertTrue(isinstance(factory.permission_query_manager(), PermissionQueryManager))
        self.assertTrue(isinstance(factory.role_manager(), RoleManager))
        self.assertTrue(isinstance(factory.role_query_manager(), RoleQueryManager))
        self.assertTrue(isinstance(factory.user_manager(), UserManager))
        self.assertTrue(isinstance(factory.user_query_manager(), UserQueryManager))
        self.assertTrue(isinstance(factory.repo_manager(), RepoManager))
        self.assertTrue(isinstance(factory.repo_unit_association_manager(),
                                   RepoUnitAssociationManager))
        self.assertTrue(isinstance(factory.repo_publish_manager(), RepoPublishManager))
        self.assertTrue(isinstance(factory.repo_query_manager(), RepoQueryManager))
        self.assertTrue(isinstance(factory.repo_sync_manager(), RepoSyncManager))
        self.assertTrue(isinstance(factory.content_manager(), ContentManager))
        self.assertTrue(isinstance(factory.content_query_manager(), ContentQueryManager))
        self.assertTrue(isinstance(factory.content_upload_manager(), ContentUploadManager))
        self.assertTrue(isinstance(factory.consumer_manager(), ConsumerManager))
        self.assertTrue(isinstance(factory.topic_publish_manager(), TopicPublishManager))
Example #12
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
Example #13
0
    def POST(self):

        # Pull all the roles data
        role_data = self.params()
        role_id = role_data.get('role_id', None)
        display_name = role_data.get('display_name', None)
        description = role_data.get('description', None)

        # Creation
        manager = managers.role_manager()
        args = [role_id, display_name, description]
        weight = pulp_config.config.getint('tasks', 'create_weight')
        tags = [resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
                action_tag('create')]
        call_request = CallRequest(manager.create_role,
                                   args,
                                   weight=weight,
                                   tags=tags)
        call_request.creates_resource(dispatch_constants.RESOURCE_ROLE_TYPE, role_id)

        role = execution.execute_sync(call_request)
        role_link = serialization.link.child_link_obj(role_id)
        role.update(role_link)
        
        return self.created(role_id, role)
Example #14
0
    def POST(self):

        # Pull all the roles data
        role_data = self.params()
        role_id = role_data.get('role_id', None)
        display_name = role_data.get('display_name', None)
        description = role_data.get('description', None)

        # Creation
        manager = managers.role_manager()
        resources = {
            dispatch_constants.RESOURCE_ROLE_TYPE: {
                role_id: dispatch_constants.RESOURCE_CREATE_OPERATION
            }
        }
        args = [role_id, display_name, description]
        weight = pulp_config.config.getint('tasks', 'create_weight')
        tags = [
            resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
            action_tag('create')
        ]
        call_request = CallRequest(manager.create_role,
                                   args,
                                   resources=resources,
                                   weight=weight,
                                   tags=tags)

        role = execution.execute_sync(call_request)
        role_link = serialization.link.child_link_obj(role_id)
        role.update(role_link)

        return self.created(role_id, role)
Example #15
0
def _initialize_pulp():

    # This initialization order is very sensitive, and each touches a number of
    # sub-systems in pulp. If you get this wrong, you will have pulp tripping
    # over itself on start up.

    global _IS_INITIALIZED, STACK_TRACER
    if _IS_INITIALIZED:
        return

    # Verify the database has been migrated to the correct version. This is
    # very likely a reason the server will fail to start.
    try:
        migration_models.check_package_versions()
    except Exception:
        msg  = 'The database has not been migrated to the current version. '
        msg += 'Run pulp-manage-db and restart the application.'
        raise InitializationException(msg), None, sys.exc_info()[2]

    # Load plugins and resolve against types. This is also a likely candidate
    # for causing the server to fail to start.
    try:
        plugin_api.initialize()
    except Exception:
        msg  = 'One or more plugins failed to initialize. If a new type has '
        msg += 'been added, run pulp-manage-db to load the type into the '
        msg += 'database and restart the application.'
        raise InitializationException(msg), None, sys.exc_info()[2]

    # There's a significantly smaller chance the following calls will fail.
    # The previous two are likely user errors, but the remainder represent
    # something gone horribly wrong. As such, I'm not going to account for each
    # and instead simply let the exception itself bubble up.

    # Load the mappings of manager type to managers
    manager_factory.initialize()

    # Initialize the tasking subsystem
    dispatch_factory.initialize()

    # Ensure the minimal auth configuration
    role_manager = manager_factory.role_manager()
    role_manager.ensure_super_user_role()
    user_manager = manager_factory.user_manager()
    user_manager.ensure_admin()

    # database document reaper
    reaper.initialize()

    # agent services
    AgentServices.start()

    # Setup debugging, if configured
    if config.config.getboolean('server', 'debugging_mode'):
        STACK_TRACER = StacktraceDumper()
        STACK_TRACER.start()

    # If we got this far, it was successful, so flip the flag
    _IS_INITIALIZED = True
Example #16
0
    def populate(self):
        role_manager = manager_factory.role_manager()
        role_manager.create_role(self.ROLE_ID)

        for login in self.USER_LOGINS:
            user_manager = manager_factory.user_manager()
            user_manager.create_user(login=login,
                                     password=login,
                                     roles=[self.ROLE_ID])
Example #17
0
 def __init__(self, admin=None, password=None,
              server='ldap://localhost:389',
              tls=False):
     self.ldapserver = server
     self.ldapadmin = admin
     self.ldappassword = password
     self.ldaptls = tls
     self.lconn = None
     self.role_manager = factory.role_manager()
Example #18
0
    def POST(self, role_id):

        # Params (validation will occur in the manager)
        params = self.params()
        login = params.get('login', None)
        if login is None:
            raise exceptions.InvalidValue(login)

        role_manager = managers.role_manager()
        return self.ok(role_manager.add_user_to_role(role_id, login))
Example #19
0
    def POST(self, role_id):

        # Params (validation will occur in the manager)
        params = self.params()
        login = params.get('login', None)
        if login is None:
            raise exceptions.InvalidValue(login)

        role_manager = managers.role_manager()
        return self.ok(role_manager.add_user_to_role(role_id, login))
Example #20
0
 def __init__(self, admin=None, password=None,
              server='ldap://localhost:389',
              tls=False):
     self.ldapserver =  server
     self.ldapadmin  =  admin
     self.ldappassword = password
     self.ldaptls = tls
     self.lconn = None
     self.user_manager = factory.user_manager()
     self.role_manager = factory.role_manager()
Example #21
0
    def PUT(self, role_id):

        # Pull all the role update data
        role_data = self.params()
        delta = role_data.get('delta', None)

        manager = managers.role_manager()
        role = manager.update_role(role_id, delta)

        role.update(serialization.link.current_link_obj())
        return self.ok(role)
Example #22
0
    def PUT(self, role_id):

        # Pull all the role update data
        role_data = self.params()
        delta = role_data.get('delta', None)

        manager = managers.role_manager()
        role = manager.update_role(role_id, delta)

        role.update(serialization.link.current_link_obj())
        return self.ok(role)
Example #23
0
    def DELETE(self, role_id, login):

        role_manager = managers.role_manager()
        tags = [resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
                action_tag('remove_user_from_role')]
        call_request = CallRequest(role_manager.remove_user_from_role,
                                   [role_id, login],
                                   tags=tags,
                                   archive=True)
        call_request.updates_resource(dispatch_constants.RESOURCE_USER_TYPE, login)
        call_request.reads_resource(dispatch_constants.RESOURCE_ROLE_TYPE, role_id)
        return  self.ok(execution.execute_sync(call_request))
Example #24
0
    def setUp(self):
        super(AuthControllersTests, self).setUp()
        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager()
        self.password_manager = manager_factory.password_manager()

        self.role_manager.ensure_super_user_role()
        self.user_manager.ensure_admin()
Example #25
0
    def setUp(self):
        super(PermissionManagerTests, self).setUp()

        self.alpha_num = string.letters + string.digits

        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager()

        self.role_manager.ensure_super_user_role()
        manager_factory.principal_manager().clear_principal()
Example #26
0
File: roles.py Project: bartwo/pulp
    def DELETE(self, role_id):

        manager = managers.role_manager()
        
        resources = {dispatch_constants.RESOURCE_ROLE_TYPE: {role_id: dispatch_constants.RESOURCE_DELETE_OPERATION}}
        tags = [resource_tag(dispatch_constants.RESOURCE_CONSUMER_TYPE, role_id),
                action_tag('delete')]
        call_request = CallRequest(manager.delete_role,
                                   [role_id],
                                   resources=resources,
                                   tags=tags)
        return self.ok(execution.execute(call_request))
Example #27
0
    def setUp(self):
        super(RoleManagerTests, self).setUp()

        self.alpha_num = string.letters + string.digits

        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager()

        self.role_manager.ensure_super_user_role()
        manager_factory.principal_manager().clear_principal()
Example #28
0
    def DELETE(self, role_id):

        manager = managers.role_manager()
        
        tags = [resource_tag(dispatch_constants.RESOURCE_CONSUMER_TYPE, role_id),
                action_tag('delete')]
        call_request = CallRequest(manager.delete_role,
                                   [role_id],
                                   tags=tags)
        call_request.deletes_resource(dispatch_constants.RESOURCE_ROLE_TYPE, role_id)

        return self.ok(execution.execute(call_request))
Example #29
0
def _initialize_pulp():

    # This initialization order is very sensitive, and each touches a number of
    # sub-systems in pulp. If you get this wrong, you will have pulp tripping
    # over itself on start up.

    global _IS_INITIALIZED, STACK_TRACER
    if _IS_INITIALIZED:
        return

    # Even though this import does not get used anywhere, we must import it for the Celery
    # application to be initialized. Also, this import cannot happen in the usual PEP-8 location,
    # as it calls initialization code at the module level. Calling that code at the module level
    # is necessary for the Celery application to initialize.
    from pulp.server.async import app

    # configure agent services
    AgentServices.init()

    # Verify the database has been migrated to the correct version. This is
    # very likely a reason the server will fail to start.
    try:
        migration_models.check_package_versions()
    except Exception:
        msg  = 'The database has not been migrated to the current version. '
        msg += 'Run pulp-manage-db and restart the application.'
        raise initialization.InitializationException(msg), None, sys.exc_info()[2]

    # There's a significantly smaller chance the following calls will fail.
    # The previous two are likely user errors, but the remainder represent
    # something gone horribly wrong. As such, I'm not going to account for each
    # and instead simply let the exception itself bubble up.

    # Initialize the tasking subsystem
    dispatch_factory.initialize()

    # Ensure the minimal auth configuration
    role_manager = manager_factory.role_manager()
    role_manager.ensure_super_user_role()
    user_manager = manager_factory.user_manager()
    user_manager.ensure_admin()

    # start agent services
    AgentServices.start()

    # Setup debugging, if configured
    if config.config.getboolean('server', 'debugging_mode'):
        STACK_TRACER = StacktraceDumper()
        STACK_TRACER.start()

    # If we got this far, it was successful, so flip the flag
    _IS_INITIALIZED = True
Example #30
0
    def setUp(self):
        super(UserManagerTests, self).setUp()

        # Hardcoded to /var/lib/pulp, so change here to avoid permissions issues
        self.default_sn_path = SerialNumber.PATH
        SerialNumber.PATH = '/tmp/sn.dat'
        sn = SerialNumber()
        sn.reset()

        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.cert_generation_manager = manager_factory.cert_generation_manager()
Example #31
0
    def setUp(self):
        super(AuthControllersTests, self).setUp()
        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.role_query_manager = manager_factory.role_query_manager()
        self.permission_manager = manager_factory.permission_manager()
        self.permission_query_manager = manager_factory.permission_query_manager(
        )
        self.password_manager = manager_factory.password_manager()

        self.role_manager.ensure_super_user_role()
        self.user_manager.ensure_admin()
Example #32
0
    def setUp(self):
        super(UserManagerTests, self).setUp()

        # Hardcoded to /var/lib/pulp, so change here to avoid permissions issues
        self.default_sn_path = SerialNumber.PATH
        SerialNumber.PATH = '/tmp/sn.dat'
        sn = SerialNumber()
        sn.reset()

        self.user_manager = manager_factory.user_manager()
        self.user_query_manager = manager_factory.user_query_manager()
        self.role_manager = manager_factory.role_manager()
        self.cert_generation_manager = manager_factory.cert_generation_manager()
Example #33
0
File: roles.py Project: bartwo/pulp
    def DELETE(self, role_id, login):

        role_manager = managers.role_manager()
        resources = {dispatch_constants.RESOURCE_USER_TYPE: {login: dispatch_constants.RESOURCE_UPDATE_OPERATION},
                     dispatch_constants.RESOURCE_ROLE_TYPE: {role_id: dispatch_constants.RESOURCE_READ_OPERATION}}
        tags = [resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
                action_tag('remove_user_from_role')]
        call_request = CallRequest(role_manager.remove_user_from_role,
                                   [role_id, login],
                                   resources=resources,
                                   tags=tags,
                                   archive=True)
        return  self.ok(execution.execute_sync(call_request))
Example #34
0
    def setUp(self):
        super(PulpWebserviceTests, self).setUp()
        self.coordinator = dispatch_factory.coordinator()
        self.success_failure = None
        self.result = None
        self.exception = None
        self.traceback = None

        # The built in PulpTest clean will automatically delete users between
        # test runs, so we can't just create the user in the class level setup.
        user_manager = manager_factory.user_manager()
        roles = []
        roles.append(manager_factory.role_manager().super_user_role)
        user_manager.create_user(login='******', password='******', roles=roles)
Example #35
0
File: base.py Project: ehelms/pulp
    def setUp(self):
        super(PulpWebserviceTests, self).setUp()
        self.coordinator = dispatch_factory.coordinator()
        self.success_failure = None
        self.result = None
        self.exception = None
        self.traceback = None

        # The built in PulpTest clean will automatically delete users between
        # test runs, so we can't just create the user in the class level setup.
        user_manager = manager_factory.user_manager()
        roles = []
        roles.append(manager_factory.role_manager().super_user_role)
        user_manager.create_user(login='******', password='******', roles=roles)
Example #36
0
    def delete(self, request, role_id):
        """
        Delete a  role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: An empty response
        :rtype: django.http.HttpResponse
        """
        manager = factory.role_manager()
        result = manager.delete_role(role_id)
        return generate_json_response(result)
Example #37
0
    def POST(self):

        # Pull all the roles data
        role_data = self.params()
        role_id = role_data.get('role_id', None)
        display_name = role_data.get('display_name', None)
        description = role_data.get('description', None)

        # Creation
        manager = managers.role_manager()
        role = manager.create_role(role_id, display_name, description)
        role_link = serialization.link.child_link_obj(role_id)
        role.update(role_link)

        return self.created(role_id, role)
Example #38
0
    def POST(self):

        # Params
        params = self.params()
        role_id = params.get("role_id", None)
        resource = params.get("resource", None)
        operation_names = params.get("operations", None)

        _check_invalid_params({"role_id": role_id, "resource": resource, "operation_names": operation_names})

        # Grant permission synchronously
        role_manager = managers.role_manager()
        permission_manager = managers.permission_manager()
        operations = permission_manager.operation_names_to_values(operation_names)
        return self.ok(role_manager.add_permissions_to_role(role_id, resource, operations))
Example #39
0
    def delete(self, request, role_id):
        """
        Delete a  role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: An empty response
        :rtype: django.http.HttpResponse
        """
        manager = factory.role_manager()
        result = manager.delete_role(role_id)
        return generate_json_response(result)
Example #40
0
    def POST(self):

        # Pull all the roles data
        role_data = self.params()
        role_id = role_data.get('role_id', None)
        display_name = role_data.get('display_name', None)
        description = role_data.get('description', None)

        # Creation
        manager = managers.role_manager()
        role = manager.create_role(role_id, display_name, description)
        role_link = serialization.link.child_link_obj(role_id)
        role.update(role_link)

        return self.created(role_id, role)
Example #41
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)

        role_manager = factory.role_manager()
        return SUPER_USER_ROLE in user['roles']
Example #42
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)

        role_manager = factory.role_manager()
        return SUPER_USER_ROLE in user['roles']
Example #43
0
    def POST(self, role_id):

        # Params (validation will occur in the manager)
        params = self.params()
        login = params.get('login', None)
        if login is None:
            raise exceptions.InvalidValue(login)

        role_manager = managers.role_manager()
        tags = [resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
                action_tag('add_user_to_role')]

        call_request = CallRequest(role_manager.add_user_to_role,
                                   [role_id, login],
                                   tags=tags)
        call_request.updates_resource(dispatch_constants.RESOURCE_USER_TYPE, login)
        return self.ok(execution.execute_sync(call_request))
Example #44
0
    def delete(self, request, role_id, login):
        """
        Remove user from a role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str
        :param login: id for the requested user
        :type login: str

        :return: An empty response
        :rtype: django.http.HttpResponse
        """
        role_manager = factory.role_manager()
        remove_user = role_manager.remove_user_from_role(role_id, login)
        return generate_json_response(remove_user)
Example #45
0
    def delete(self, request, role_id, login):
        """
        Remove user from a role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str
        :param login: id for the requested user
        :type login: str

        :return: An empty response
        :rtype: django.http.HttpResponse
        """
        role_manager = factory.role_manager()
        remove_user = role_manager.remove_user_from_role(role_id, login)
        return generate_json_response(remove_user)
Example #46
0
    def POST(self):

        # Params
        params = self.params()
        role_id = params.get('role_id', None)
        resource = params.get('resource', None)
        operation_names = params.get('operations', None)

        _check_invalid_params({'role_id': role_id,
                               'resource': resource,
                               'operation_names': operation_names})

        # Grant permission synchronously
        role_manager = managers.role_manager()
        permission_manager = managers.permission_manager()
        operations = permission_manager.operation_names_to_values(operation_names)
        return self.ok(role_manager.remove_permissions_from_role(role_id, resource, operations))
Example #47
0
    def DELETE(self, role_id):

        manager = managers.role_manager()

        resources = {
            dispatch_constants.RESOURCE_ROLE_TYPE: {
                role_id: dispatch_constants.RESOURCE_DELETE_OPERATION
            }
        }
        tags = [
            resource_tag(dispatch_constants.RESOURCE_CONSUMER_TYPE, role_id),
            action_tag('delete')
        ]
        call_request = CallRequest(manager.delete_role, [role_id],
                                   resources=resources,
                                   tags=tags)
        return self.ok(execution.execute(call_request))
Example #48
0
    def PUT(self, role_id):

        # Pull all the role update data
        role_data = self.params()
        delta = role_data.get('delta', None)

        # Perform update        
        manager = managers.role_manager()
        tags = [resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
                action_tag('update')]
        call_request = CallRequest(manager.update_role,
                                   [role_id, delta],
                                   tags=tags)
        call_request.updates_resource(dispatch_constants.RESOURCE_ROLE_TYPE, role_id)

        role = execution.execute(call_request)
        role.update(serialization.link.current_link_obj())
        return self.ok(role)
Example #49
0
def update_user(login, delta):
    """
    Updates the user with a delta dict. The delta can only contain fields that may be changed,
    which are name, password, and roles.

    :param login: identifies the user
    :type  login: str
    :param delta: user attributes and their new values
    :type  delta: dict

    :raise InvalidValue: if extra params are passed or params contain invalid values
    """

    user = model.User.objects.get_or_404(login=login)
    user.name = delta.pop('name', user.name)

    password = delta.pop('password', None)
    if password is not None:
        user.set_password(password)

    roles = delta.pop('roles', None)
    if roles:
        if not isinstance(roles, list):
            raise pulp_exceptions.InvalidValue('roles')
        else:
            # Add new roles and remove deleted roles from the user
            role_manager = manager_factory.role_manager()
            roles_to_add = list(set(roles) - set(user.roles))
            roles_to_remove = list(set(user.roles) - set(roles))

            for new_role in roles_to_add:
                role_manager.add_user_to_role(new_role, login)
            for remove_role in roles_to_remove:
                role_manager.remove_user_from_role(remove_role, login)
            user.roles = roles

    # Raise before save if extra values were passed
    if delta:
        raise pulp_exceptions.InvalidValue(delta.keys())

    try:
        user.save()
    except ValidationError, e:
        raise pulp_exceptions.InvalidValue(e.to_dict().keys())
Example #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.
        """
        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)
Example #51
0
    def put(self, request, role_id):
        """
        Update a specific role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: Response containing the role
        :rtype: django.http.HttpResponse
        """
        role_data = request.body_as_json
        delta = role_data.get('delta', None)
        manager = factory.role_manager()
        role = manager.update_role(role_id, delta)
        link = {'_href': reverse('role_resource',
                kwargs={'role_id': role['id']})}
        role.update(link)
        return generate_json_response_with_pulp_encoder(role)
Example #52
0
    def DELETE(self, role_id, login):

        role_manager = managers.role_manager()
        resources = {
            dispatch_constants.RESOURCE_USER_TYPE: {
                login: dispatch_constants.RESOURCE_UPDATE_OPERATION
            },
            dispatch_constants.RESOURCE_ROLE_TYPE: {
                role_id: dispatch_constants.RESOURCE_READ_OPERATION
            }
        }
        tags = [
            resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
            action_tag('remove_user_from_role')
        ]
        call_request = CallRequest(role_manager.remove_user_from_role,
                                   [role_id, login],
                                   resources=resources,
                                   tags=tags,
                                   archive=True)
        return self.ok(execution.execute_sync(call_request))
Example #53
0
    def post(self, request, role_id):
        """
        Add user to a role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: An empty response
        :rtype: django.http.HttpResponse
        :raises: InvalidValue some parameters are invalid
        """
        params = request.body_as_json
        login = params.get('login', None)
        if login is None:
            raise pulp_exceptions.InvalidValue(login)

        role_manager = factory.role_manager()
        add_user = role_manager.add_user_to_role(role_id, login)
        return generate_json_response(add_user)
Example #54
0
    def POST(self):

        # Params
        params = self.params()
        role_id = params.get('role_id', None)
        resource = params.get('resource', None)
        operation_names = params.get('operations', None)

        _check_invalid_params({
            'role_id': role_id,
            'resource': resource,
            'operation_names': operation_names
        })

        # Grant permission synchronously
        role_manager = managers.role_manager()
        permission_manager = managers.permission_manager()
        operations = permission_manager.operation_names_to_values(
            operation_names)
        return self.ok(
            role_manager.remove_permissions_from_role(role_id, resource,
                                                      operations))
Example #55
0
    def post(self, request):
        """
        Create a new role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing the role
        :rtype: django.http.HttpResponse
        """
        role_data = request.body_as_json
        role_id = role_data.get('role_id', None)
        display_name = role_data.get('display_name', None)
        description = role_data.get('description', None)
        manager = factory.role_manager()
        role = manager.create_role(role_id, display_name, description)
        link = {'_href': reverse('role_resource',
                kwargs={'role_id': role['id']})}
        role.update(link)
        response = generate_json_response_with_pulp_encoder(role)
        redirect_response = generate_redirect_response(response, link['_href'])
        return redirect_response
Example #56
0
    def PUT(self, role_id):

        # Pull all the role update data
        role_data = self.params()
        delta = role_data.get('delta', None)

        # Perform update
        manager = managers.role_manager()
        resources = {
            dispatch_constants.RESOURCE_ROLE_TYPE: {
                role_id: dispatch_constants.RESOURCE_UPDATE_OPERATION
            }
        }
        tags = [
            resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
            action_tag('update')
        ]
        call_request = CallRequest(manager.update_role, [role_id, delta],
                                   resources=resources,
                                   tags=tags)
        role = execution.execute(call_request)
        role.update(serialization.link.current_link_obj())
        return self.ok(role)
Example #57
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)
Example #58
0
    def POST(self, role_id):

        # Params (validation will occur in the manager)
        params = self.params()
        login = params.get('login', None)
        if login is None:
            raise exceptions.InvalidValue(login)

        role_manager = managers.role_manager()
        resources = {
            dispatch_constants.RESOURCE_USER_TYPE: {
                login: dispatch_constants.RESOURCE_UPDATE_OPERATION
            }
        }
        tags = [
            resource_tag(dispatch_constants.RESOURCE_ROLE_TYPE, role_id),
            action_tag('add_user_to_role')
        ]

        call_request = CallRequest(role_manager.add_user_to_role,
                                   [role_id, login],
                                   resources=resources,
                                   tags=tags)
        return self.ok(execution.execute_sync(call_request))
Example #59
0
    def update_user(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 = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(login)

        # Check invalid values
        invalid_values = []
        if 'password' in delta:
            password = delta.pop('password')
            if password is None or invalid_type(password, basestring):
                invalid_values.append('password')
            else:
                user['password'] = factory.password_manager().hash_password(password)

        if 'name' in delta:
            name = delta.pop('name')
            if name is None or invalid_type(name, basestring):
                invalid_values.append('name')
            else:
                user['name'] = name

        if 'roles' in delta:
            roles = delta.pop('roles')
            if roles is None or invalid_type(roles, list):
                invalid_values.append('roles')
            else:
                # Add new roles to the user and remove deleted roles from the user according to
                # delta
                role_manager = factory.role_manager()
                old_roles = user['roles']
                for new_role in roles:
                    if new_role not in old_roles:
                        role_manager.add_user_to_role(new_role, login)
                for old_role in old_roles:
                    if old_role not in roles:
                        role_manager.remove_user_from_role(old_role, login)
                user['roles'] = roles

        if invalid_values:
            raise InvalidValue(invalid_values)
        if delta:
            raise InvalidValue(delta.keys())

        User.get_collection().save(user)

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

        return updated