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', []))
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)
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})
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)
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)
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
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)
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)
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)
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']))
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
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)
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)
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)
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
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
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)
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
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)
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)
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
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
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)
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']
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)
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)
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)
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)
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
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'])
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"])
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)
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)
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'])
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)
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"])
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)
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"]))
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"])
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
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)
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
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)
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'])
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)
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']))
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)
def tearDown(self): ServerTests.tearDown(self) User.get_collection().remove()
def clean(self): base.PulpServerTests.clean(self) User.get_collection().remove() Role.get_collection().remove()
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
def tearDown(self): super(PulpWebserviceTests, self).tearDown() User.get_collection().remove(safe=True) TaskStatus.get_collection().remove(safe=True)