Exemple #1
0
    def __create_user_management(self):
        from cmdb.user_management.models.user import UserModel

        from cmdb.user_management.managers.user_manager import UserManager
        from cmdb.user_management.managers.group_manager import GroupManager
        from cmdb.user_management import __FIXED_GROUPS__
        from cmdb.security.security import SecurityManager
        scm = SecurityManager(self.setup_database_manager)
        group_manager = GroupManager(self.setup_database_manager)
        user_manager = UserManager(self.setup_database_manager)

        for group in __FIXED_GROUPS__:
            group_manager.insert(group)

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

        import datetime
        admin_user = UserModel(
            public_id=1,
            user_name=admin_name,
            active=True,
            group_id=__FIXED_GROUPS__[0].get_public_id(),
            registration_time=datetime.datetime.now(),
            password=scm.generate_hmac(admin_pass),
        )
        user_manager.insert(admin_user)
        return True
Exemple #2
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.managers.user_manager import UserManager, UserModel
        from cmdb.security.security import SecurityManager
        scm = SecurityManager(self.setup_database_manager)
        usm = UserManager(self.setup_database_manager)

        try:
            admin_user: UserModel = usm.get(1)
            LOGGER.warning('KEY ROUTINE: Admin user detected')
            LOGGER.info(
                f'KEY ROUTINE: Enter new password for user: {admin_user.user_name}'
            )
            admin_pass = str(input('New admin password: '******'KEY ROUTINE: Password was updated for user: {admin_user.user_name}'
            )
        except Exception as ex:
            LOGGER.info(
                f'KEY ROUTINE: Password was updated for user failed: {ex}')
        LOGGER.info('KEY ROUTINE: FINISHED')
 def authenticate(self, user_name: str, password: str, **kwargs) -> UserModel:
     __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: UserModel = __user_manager.get_by({'user_name': user_name})
     except ManagerGetError as umge:
         raise AuthenticationError(LocalAuthenticationProvider.get_name(), umge.message)
     login_pass = __scm.generate_hmac(password)
     if login_pass == user.password:
         return user
     raise AuthenticationError(LocalAuthenticationProvider.get_name(), 'UserModel not exists')
Exemple #4
0
def insert_user(data: dict):
    """
    HTTP `POST` route for insert a single user resource.

    Args:
        data (UserModel.SCHEMA): Insert data of a new user.

    Raises:
        ManagerGetError: If the inserted user could not be found after inserting.
        ManagerInsertError: If something went wrong during insertion.

    Returns:
        InsertSingleResponse: Insert response with the new user and its public_id.
    """
    user_manager: UserManager = UserManager(
        database_manager=current_app.database_manager)
    security_manager: SecurityManager = SecurityManager(
        database_manager=current_app.database_manager)
    try:
        data['password'] = security_manager.generate_hmac(data['password'])
        result_id: PublicID = user_manager.insert(data)
        user = user_manager.get(public_id=result_id)
    except ManagerGetError as err:
        return abort(404, err.message)
    except ManagerInsertError as err:
        return abort(400, err.message)
    api_response = InsertSingleResponse(result_id=result_id,
                                        raw=UserModel.to_dict(user),
                                        url=request.url,
                                        model=UserModel.MODEL)
    return api_response.make_response(prefix='users')
Exemple #5
0
def change_user_password(public_id: int):
    """
    HTTP `PATCH` route for updating a single user password.

    Args:
        public_id (int): Public ID of the user.

    Raises:
        ManagerGetError: When the user with the `public_id` was not found.
        ManagerUpdateError: When something went wrong during the updated.

    Returns:
        UpdateSingleResponse: User with new password
    """
    user_manager: UserManager = UserManager(
        database_manager=current_app.database_manager)
    security_manager: SecurityManager = SecurityManager(
        database_manager=current_app.database_manager)
    try:
        user = user_manager.get(public_id=public_id)
        password = security_manager.generate_hmac(request.json.get('password'))
        user.password = password
        user_manager.update(public_id=PublicID(public_id), user=user)
        api_response = UpdateSingleResponse(result=UserModel.to_dict(user),
                                            url=request.url,
                                            model=UserModel.MODEL)
    except ManagerGetError as err:
        return abort(404, err.message)
    except ManagerUpdateError as err:
        return abort(400, err.message)

    return api_response.make_response()
Exemple #6
0
    def __create_user_management(self):
        from cmdb.user_management.user_manager import UserManager, User
        from cmdb.user_management import __FIXED_GROUPS__
        from cmdb.security.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
Exemple #7
0
def preset_database(database_manager, database_name):
    from cmdb.database.errors.database_errors import DatabaseNotExists
    from cmdb.security.key.generator import KeyGenerator
    from cmdb.security.security import SecurityManager
    from cmdb.user_management.managers.group_manager import GroupManager
    from cmdb.user_management.managers.user_manager import UserManager
    try:
        database_manager.drop_database(database_name)
    except DatabaseNotExists:
        pass
    from cmdb.user_management import __FIXED_GROUPS__
    from datetime import datetime

    kg = KeyGenerator(database_manager=database_manager)
    kg.generate_rsa_keypair()
    kg.generate_symmetric_aes_key()

    group_manager = GroupManager(database_manager=database_manager)
    user_manager = UserManager(database_manager=database_manager)
    security_manager = SecurityManager(database_manager=database_manager)

    for group in __FIXED_GROUPS__:
        group_manager.insert(group)

    admin_name = 'admin'
    admin_pass = '******'
    from cmdb.user_management import UserModel
    admin_user = UserModel(
        public_id=1,
        user_name=admin_name,
        active=True,
        group_id=__FIXED_GROUPS__[0].public_id,
        registration_time=datetime.now(),
        password=security_manager.generate_hmac(admin_pass),
    )
    user_manager.insert(admin_user)
Exemple #8
0
def post_login():
    user_manager: UserManager = UserManager(current_app.database_manager)
    group_manager: GroupManager = GroupManager(
        current_app.database_manager, right_manager=RightManager(rights))
    security_manager: SecurityManager = SecurityManager(
        current_app.database_manager)
    login_data = request.json
    if not request.json:
        return abort(400, 'No valid JSON data was provided')

    request_user_name = login_data['user_name']
    request_password = login_data['password']

    auth_module = AuthModule(
        system_settings_reader.get_all_values_from_section(
            'auth', default=AuthModule.__DEFAULT_SETTINGS__),
        user_manager=user_manager,
        group_manager=group_manager,
        security_manager=security_manager)
    user_instance = None
    try:
        user_instance = auth_module.login(request_user_name, request_password)
    except (AuthenticationProviderNotExistsError,
            AuthenticationProviderNotActivated) as err:
        return abort(503, err.message)
    except Exception as e:
        return abort(401)
    finally:
        # If login success generate user instance with token
        if user_instance:
            tg = TokenGenerator()
            token: bytes = tg.generate_token(
                payload={'user': {
                    'public_id': user_instance.get_public_id()
                }})
            token_issued_at = int(datetime.now().timestamp())
            token_expire = int(tg.get_expire_time().timestamp())

            login_response = LoginResponse(user_instance, token,
                                           token_issued_at, token_expire)

            return login_response.make_response()

        # Login not success
        else:
            return abort(401, 'Could not login')
Exemple #9
0
 def __init__(self, database_manager: DatabaseManagerMongo):
     self.scm = SecurityManager(database_manager)
     self.rights = self._load_rights()
     super(UserManager, self).__init__(database_manager)
Exemple #10
0
def parse_authorization_header(header):
    """
    Parses the HTTP Auth Header to a JWT Token
    Args:
        header: Authorization header of the HTTP Request
    Examples:
        request.headers['Authorization'] or something same
    Returns:
        Valid JWT token
    """
    if not header:
        return None
    value = wsgi_to_bytes(header)
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        # Fallback for old versions
        auth_type = b"bearer"
        auth_info = value

    if auth_type == b"basic":
        try:
            username, password = base64.b64decode(auth_info).split(b":", 1)

            with current_app.app_context():
                username = to_unicode(username, "utf-8")
                password = to_unicode(password, "utf-8")

                user_manager: UserManager = UserManager(current_app.database_manager)
                group_manager: GroupManager = GroupManager(current_app.database_manager,
                                                           right_manager=RightManager(rights))
                security_manager: SecurityManager = SecurityManager(current_app.database_manager)
                auth_settings = SystemSettingsReader(current_app.database_manager).get_all_values_from_section(
                    'auth', default=AuthModule.__DEFAULT_SETTINGS__)
                auth_module = AuthModule(auth_settings, user_manager=user_manager,
                                         group_manager=group_manager, security_manager=security_manager)

                try:
                    user_instance = auth_module.login(username, password)
                except Exception as e:
                    return None
                if user_instance:
                    tg = TokenGenerator(current_app.database_manager)
                    return tg.generate_token(payload={'user': {
                        'public_id': user_instance.get_public_id()
                    }})
                else:
                    return None
        except Exception:
            return None

    if auth_type == b"bearer":
        try:
            with current_app.app_context():
                tv = TokenValidator(current_app.database_manager)
                decoded_token = tv.decode_token(auth_info)
                tv.validate_token(decoded_token)
            return auth_info
        except Exception:
            return None
    return None
Exemple #11
0
def create_rest_api(event_queue):
    from cmdb.interface.config import app_config
    from cmdb.utils.system_config import SystemConfigReader
    system_config_reader = SystemConfigReader()

    # Create managers
    from cmdb.data_storage.database_manager import DatabaseManagerMongo
    app_database = DatabaseManagerMongo(
        **system_config_reader.get_all_values_from_section('Database'))
    object_manager = CmdbObjectManager(database_manager=app_database,
                                       event_queue=event_queue)

    log_manager = CmdbLogManager(database_manager=app_database)

    security_manager = SecurityManager(database_manager=app_database)

    user_manager = UserManager(database_manager=app_database)

    exportd_job_manager = ExportdJobManagement(database_manager=app_database,
                                               event_queue=event_queue)

    exportd_log_manager = ExportdLogManager(database_manager=app_database)

    media_file_manager = MediaFileManagement(database_manager=app_database)

    docapi_tpl_manager = DocapiTemplateManager(database_manager=app_database)

    # Create APP
    from cmdb.interface.cmdb_app import BaseCmdbApp

    app = BaseCmdbApp(__name__,
                      database_manager=app_database,
                      docapi_tpl_manager=docapi_tpl_manager,
                      media_file_manager=media_file_manager,
                      exportd_manager=exportd_job_manager,
                      exportd_log_manager=exportd_log_manager,
                      object_manager=object_manager,
                      log_manager=log_manager,
                      user_manager=user_manager,
                      security_manager=security_manager)

    app.url_map.strict_slashes = True

    # Import App Extensions
    from flask_cors import CORS
    CORS(app, expose_headers=['X-API-Version', 'X-Total-Count'])

    import cmdb
    if cmdb.__MODE__ == 'DEBUG':
        config = app_config['development']
        config.APPLICATION_ROOT = '/rest/'
        app.config.from_object(config)
    else:
        config = app_config['production']
        config.APPLICATION_ROOT = '/rest/'
        app.config.from_object(config)

    with app.app_context():
        register_converters(app)
        register_error_pages(app)
        register_blueprints(app)

    return app
Exemple #12
0
def create_rest_api(event_queue):
    from cmdb.interface.config import app_config
    from cmdb.utils.system_config import SystemConfigReader
    system_config_reader = SystemConfigReader()

    try:
        cache_config = {
            'DEBUG':
            True,
            'CACHE_TYPE':
            system_config_reader.get_value('name', 'Cache'),
            'CACHE_REDIS_HOST':
            system_config_reader.get_value('host', 'Cache'),
            'CACHE_REDIS_PORT':
            system_config_reader.get_value('port', 'Cache'),
            'CACHE_REDIS_PASSWORD':
            system_config_reader.get_value('password', 'Cache'),
        }
    except (ImportError, CMDBError) as e:
        LOGGER.debug(e.message)
        cache_config = {'CACHE_TYPE': 'simple'}
    from flask_caching import Cache

    cache = Cache(config=cache_config)

    # Create managers
    from cmdb.data_storage.database_manager import DatabaseManagerMongo
    app_database = DatabaseManagerMongo(
        **system_config_reader.get_all_values_from_section('Database'))
    object_manager = CmdbObjectManager(database_manager=app_database,
                                       event_queue=event_queue)

    log_manager = CmdbLogManager(database_manager=app_database)

    security_manager = SecurityManager(database_manager=app_database)

    user_manager = UserManager(database_manager=app_database)

    exportd_job_manager = ExportdJobManagement(database_manager=app_database,
                                               event_queue=event_queue)

    exportd_log_manager = ExportdLogManager(database_manager=app_database)

    media_file_manager = MediaFileManagement(database_manager=app_database)

    docapi_tpl_manager = DocapiTemplateManager(database_manager=app_database)

    # Create APP
    from cmdb.interface.cmdb_app import BaseCmdbApp

    app = BaseCmdbApp(__name__,
                      database_manager=app_database,
                      docapi_tpl_manager=docapi_tpl_manager,
                      media_file_manager=media_file_manager,
                      exportd_manager=exportd_job_manager,
                      exportd_log_manager=exportd_log_manager,
                      object_manager=object_manager,
                      log_manager=log_manager,
                      user_manager=user_manager,
                      security_manager=security_manager)

    app.url_map.strict_slashes = True

    # Import App Extensions
    from flask_cors import CORS
    CORS(app, expose_headers=['X-API-Version', 'X-Total-Count'])
    import cmdb
    cache.init_app(app)
    cache.clear()
    app.cache = cache

    if cmdb.__MODE__ == 'DEBUG':
        app.config.from_object(app_config['rest_development'])
        LOGGER.info('RestAPI starting with config mode {}'.format(
            app.config.get("ENV")))
    elif cmdb.__MODE__ == 'TESTING':
        app.config.from_object(app_config['testing'])
    else:
        app.config.from_object(app_config['rest'])
        LOGGER.info('RestAPI starting with config mode {}'.format(
            app.config.get("ENV")))

    with app.app_context():
        register_converters(app)
        register_error_pages(app)
        register_blueprints(app)

    return app