예제 #1
0
    def init_keys(self):
        from cmdb.security.key.generator import KeyGenerator
        kg = KeyGenerator()
        LOGGER.info('KEY ROUTINE: Generate RSA keypair')
        kg.generate_rsa_keypair()
        LOGGER.info('KEY ROUTINE: Generate aes key')
        kg.generate_symmetric_aes_key()

        self.__check_database()

        from cmdb.user_management.user_manager import UserManager
        from cmdb.utils.security import SecurityManager
        scm = SecurityManager(self.setup_database_manager)
        usm = UserManager(self.setup_database_manager)

        try:
            admin_user = usm.get_user(1)
            LOGGER.warning('KEY ROUTINE: Admin user detected')
            LOGGER.info(
                f'KEY ROUTINE: Enter new password for user: {admin_user.get_username()}'
            )
            admin_pass = str(input('New admin password: '******'KEY ROUTINE: Password was updated for user: {admin_user.get_username()}'
            )
        except Exception as ex:
            LOGGER.info(
                f'KEY ROUTINE: Password was updated for user failed: {ex}')
        LOGGER.info('KEY ROUTINE: FINISHED')
예제 #2
0
 def __init__(self, object_list: List[CmdbObject], request_user: UserModel, dt_render=False, ref_render=False,
              object_manager: CmdbObjectManager = None):
     self.object_list: List[CmdbObject] = object_list
     self.request_user = request_user
     self.dt_render = dt_render
     self.ref_render = ref_render
     from cmdb.utils.system_config import SystemConfigReader
     database_manager = DatabaseManagerMongo(
         **SystemConfigReader().get_all_values_from_section('Database')
     )
     self.object_manager = object_manager or CmdbObjectManager(database_manager=database_manager)
     self.user_manager = UserManager(database_manager=database_manager)
예제 #3
0
class RenderList:

    def __init__(self, object_list: List[CmdbObject], request_user: UserModel, dt_render=False, ref_render=False,
                 object_manager: CmdbObjectManager = None):
        self.object_list: List[CmdbObject] = object_list
        self.request_user = request_user
        self.dt_render = dt_render
        self.ref_render = ref_render
        from cmdb.utils.system_config import SystemConfigReader
        database_manager = DatabaseManagerMongo(
            **SystemConfigReader().get_all_values_from_section('Database')
        )
        self.object_manager = object_manager or CmdbObjectManager(database_manager=database_manager)
        self.user_manager = UserManager(database_manager=database_manager)

    @timing('RenderList')
    def render_result_list(self, raw: bool = False) -> List[Union[RenderResult, dict]]:
        complete_user_list: List[UserModel] = self.user_manager.get_users()

        preparation_objects: List[RenderResult] = []
        for passed_object in self.object_list:
            tmp_render = CmdbRender(
                type_instance=self.object_manager.get_type(passed_object.type_id),
                object_instance=passed_object,
                render_user=self.request_user, user_list=complete_user_list,
                object_manager=self.object_manager, dt_render=self.dt_render, ref_render=self.ref_render)
            if raw:
                current_render_result = tmp_render.result().__dict__
            else:
                current_render_result = tmp_render.result()
            preparation_objects.append(current_render_result)
        return preparation_objects
예제 #4
0
    def __init__(self, event, state=False):
        super(ExportdThread, self).__init__()
        self.job = None
        self.job_id = event.get_param("id")
        self.type_id = event.get_param("type_id")
        self.user_id = event.get_param("user_id")
        self.event = event
        self.is_active = state
        self.exception_handling = None

        scr = SystemConfigReader()
        database_options = scr.get_all_values_from_section('Database')
        self.__dbm = DatabaseManagerMongo(**database_options)
        self.log_manager = ExportdLogManager(database_manager=self.__dbm)
        self.exportd_job_manager = ExportdJobManagement(
            database_manager=self.__dbm)
        self.user_manager = UserManager(database_manager=self.__dbm)
예제 #5
0
 def authenticate(self, user_name: str, password: str, **kwargs) -> User:
     __dbm = DatabaseManagerMongo(
         **SystemConfigReader().get_all_values_from_section('Database'))
     __scm = SecurityManager(__dbm)
     __user_manager = UserManager(__dbm)
     LOGGER.info(
         f'[LocalAuthenticationProvider] Try login for user {user_name}')
     try:
         user: User = __user_manager.get_user_by_name(user_name=user_name)
     except UserManagerGetError as umge:
         raise AuthenticationError(LocalAuthenticationProvider.get_name(),
                                   umge.message)
     login_pass = __scm.generate_hmac(password)
     if login_pass == user.get_password():
         return user
     raise AuthenticationError(LocalAuthenticationProvider.get_name(),
                               'User not exists')
예제 #6
0
    def insert_data(self) -> list:
        """insert data into database"""
        if self._database_manager is None:
            raise NoDatabaseManagerError()
        from cmdb.framework.cmdb_object_manager import CmdbObjectManager
        from cmdb.user_management.user_manager import UserManager

        obm = CmdbObjectManager(database_manager=self._database_manager)
        usm = UserManager(database_manager=self._database_manager)

        error = []
        for group_element in self.groups:
            try:
                usm.insert_group(group_element)
            except CMDBError as e:
                error.append(e.message)
                continue
        for user_element in self.users:
            try:
                usm.insert_user(user_element)
            except CMDBError as e:
                error.append(e.message)
                continue
        for type_element in self.types:
            try:
                obm.insert_type(type_element)
            except CMDBError as e:
                error.append(e.message)
                continue
        for category_element in self.categories:
            try:
                obm.insert_category(category_element)
            except CMDBError as e:
                error.append(e.message)
                continue

        for object_element in self.objects:
            try:
                obm.insert_object(object_element)
            except CMDBError as e:
                error.append(e.message)
                continue

        return error
예제 #7
0
    def __create_user_management(self):
        from cmdb.user_management.user_manager import UserManager, User
        from cmdb.user_management import __FIXED_GROUPS__
        from cmdb.utils.security import SecurityManager
        scm = SecurityManager(self.setup_database_manager)
        usm = UserManager(self.setup_database_manager)

        for group in __FIXED_GROUPS__:
            usm.insert_group(group)

        # setting the initial user to admin/admin as default
        admin_name = 'admin'
        admin_pass = '******'

        import datetime
        admin_user = User(public_id=1,
                          user_name=admin_name,
                          password=scm.generate_hmac(admin_pass),
                          group_id=__FIXED_GROUPS__[0].get_public_id(),
                          registration_time=datetime.datetime.utcnow())
        usm.insert_user(admin_user)
        return True
예제 #8
0
class ExportdThread(Thread):
    def __init__(self, event, state=False):
        super(ExportdThread, self).__init__()
        self.job = None
        self.job_id = event.get_param("id")
        self.type_id = event.get_param("type_id")
        self.user_id = event.get_param("user_id")
        self.event = event
        self.is_active = state
        self.exception_handling = None

        scr = SystemConfigReader()
        database_options = scr.get_all_values_from_section('Database')
        self.__dbm = DatabaseManagerMongo(**database_options)
        self.log_manager = ExportdLogManager(database_manager=self.__dbm)
        self.exportd_job_manager = ExportdJobManagement(
            database_manager=self.__dbm)
        self.user_manager = UserManager(database_manager=self.__dbm)

    def run(self):
        try:
            if self.type_id:
                for obj in self.exportd_job_manager.get_job_by_event_based(
                        True):
                    if next((item for item in obj.get_sources()
                             if item["type_id"] == self.type_id), None):
                        if obj.get_active(
                        ) and obj.scheduling["event"]["active"]:
                            self.job = obj
                            self.worker()
            elif self.is_active:
                self.job = self.exportd_job_manager.get_job(self.job_id)
                self.worker()
        except Exception as ex:
            LOGGER.error(ex)
            return ex

    def worker(self):
        cur_user = None
        try:
            # update job for UI
            self.job.state = ExecuteState.RUNNING.name
            self.job.last_execute_date = datetime.utcnow()

            # get current user
            cur_user = self.user_manager.get_user(self.user_id)

            self.exportd_job_manager.update_job(self.job,
                                                self.user_manager.get_user(
                                                    self.user_id),
                                                event_start=False)
            # execute Exportd job
            job = cmdb.exportd.exporter_base.ExportdManagerBase(self.job)
            job.execute(self.event, cur_user.get_public_id(),
                        cur_user.get_name())

        except Exception as err:
            LOGGER.error(err)
            self.exception_handling = err
            # Generate Error log
            try:
                log_params = {
                    'job_id': self.job.get_public_id(),
                    'state': False,
                    'user_id': cur_user.get_public_id(),
                    'user_name': cur_user.get_name(),
                    'event': self.event.get_type(),
                    'message': ['Successful'] if not err else err.args,
                }
                self.log_manager.insert_log(action=LogAction.EXECUTE,
                                            log_type=ExportdJobLog.__name__,
                                            **log_params)
            except LogManagerInsertError as err:
                LOGGER.error(err)
        finally:
            # update job for UI
            self.job.state = ExecuteState.SUCCESSFUL.name if not self.exception_handling else ExecuteState.FAILED.name
            self.exportd_job_manager.update_job(self.job,
                                                self.user_manager.get_user(
                                                    self.user_id),
                                                event_start=False)