Beispiel #1
0
 def init_nodes(self):
     logManager.info('Initialize nodes')
     all_nodes = self.node.query.all()
     for n in all_nodes:
         if n.authorized is True:
             self.activate_node(n)
     self.db.session.commit()
Beispiel #2
0
 def handle(self, action, user, workspace, actionManager):
     # userManager = actionManager.userManager
     menuBuilder = actionManager.menuBuilder
     logManager.info("Execute registration action")
     menu = menuBuilder.buildMenu(user)
     updateMenu_action = webclientActions.UpdateMenuAction.generate(menu)
     return 'success', [updateMenu_action]
Beispiel #3
0
    def discoverNodeClasses(self, workspaceSource):
        # for _, node_class, ispkg in pkgutil.iter_modules(imported_source.__path__, imported_source.__name__ + '.'):
        #    if ispkg:
        #        print(node_class)

        node_sources = workspaceSource + '.' + self.name + '.' + 'nodes'
        imported_source = __import__(node_sources, fromlist=['blah'])

        for _, nodename, ispkg in pkgutil.iter_modules(
                imported_source.__path__, imported_source.__name__ + '.'):
            if not ispkg:
                node_module = __import__(nodename, fromlist=['blah'])
                clsmembers = inspect.getmembers(node_module, inspect.isclass)
                for (_, c) in clsmembers:
                    # Check for DataView classes
                    if issubclass(c, NodeClass) & (c is not NodeClass):
                        if c.disable is False:
                            logManager.info(
                                f'NodeClass: "{c.__module__}" loaded from "{node_sources}"'
                            )
                            nodeManager.register_node_class(self, c)
                        else:
                            logManager.info(
                                f'NodeClass: "{c.__module__}" is diabled and wont show up"'
                            )
        '''
Beispiel #4
0
    def handle(self, action, user, workspace, actionManager):
        logManager.info("Execute lost password action")
        notification_action = webclientActions.NotificationAction.generate(
            "A email to reset the password will be send to you", "success")
        ref = request.referrer.split('/')
        if ref[0] != 'http:' and ref[0] != 'https:':
            ref = '/'.join(ref[:1])
        else:
            ref = '/'.join(ref[:3])

        resetUser = userManager.getUser(action.username)
        if resetUser is not None:
            key = ''.join(
                random.choices(string.ascii_letters + string.digits, k=96))
            resetUser.password_reset_expired_date = arrow.utcnow().shift(
                hours=2)
            resetUser.password_reset_hash = key
            link = ref + '/user/resetpassword' + '?key=' + key
            data = {
                'username': resetUser.firstname + ' ' + resetUser.lastname,
                'reset_link': link
            }
            print(key)
            send_mail([resetUser.email], "Reset your password", workspace,
                      'lostPassword.mail', data)

        return 'success', [notification_action]
    def discoverModels(self):
        source = self.workspaceSource
        imported_source = __import__(source, fromlist=['blah'])
        all_current_paths = []

        # all_current_paths.append(imported_source.__path__._path)

        if isinstance(imported_source.__path__, str):
            all_current_paths.append(imported_source.__path__)
        else:
            all_current_paths.extend([x for x in imported_source.__path__])

        # remove duplicates
        all_current_paths = list(set(all_current_paths))

        for pkg_path in all_current_paths:
            # Walk through all sub directories
            child_pkgs = [
                p for p in os.listdir(pkg_path)
                if os.path.isdir(os.path.join(pkg_path, p))
            ]

            for child_pkg in child_pkgs:
                try:
                    __import__(source + '.' + child_pkg + '.models',
                               fromlist=['blah'])
                except ModuleNotFoundError:
                    modelmodule = source + '.' + child_pkg + '.models'
                    logManager.info(f'No model found for {modelmodule}')
                print(child_pkg)
        print("Finished")
Beispiel #6
0
    def handle(self, action, user, workspace, actionManager):
        logManager.info("Execute registration action")
        replyActions = []
        userdata = action['userdata']
        if userManager.checkUserExist(userdata['email']):
            replyActions.append(
                webclientActions.NotificationAction.generate(
                    "User already exist", "error"))
        else:
            u = userManager.registerUser(userdata)
            link = generateActionLink(workspace, 'verifyUser',
                                      {'email': userdata['email']},
                                      "user/login", True, False)
            data = {
                'username': userdata['firstname'] + ' ' + userdata['lastname'],
                'action_link': link
            }
            send_mail([userdata['email']], "#Rosenwerk Account verifizieren",
                      workspace, 'requestVerification.mail', data)
            send_message(u, "Welcome", workspace, 'welcome.message', data,
                         'Roseguarden', False, 'welcome.mail')
            replyActions.append(
                webclientActions.NotificationAction.generate(
                    "User registered", "success"))
            replyActions.append(
                webclientActions.RouteAction.generate("dashboard", 3))

        return 'success', replyActions
Beispiel #7
0
    def handle(self, action, user, workspace, actionManager):
        logManager.info("Execute get view action for", action['view'])

        viewname = action['view']
        print(workspace.dataViews)
        if viewname in workspace.dataViews:
            print('found view', viewname, 'in', workspace.name,
                  workspace.dataViews[viewname])
            view = workspace.dataViews[viewname]

            # check if login required for this view
            if view.requireLogin is True and user is None:
                raise RequireLoginError
            else:
                # build actions to get view
                meta_data = view.getViewMetaHandler(user, workspace)
                entries = view.getViewHandler(user, workspace, None)
                properties = view.getProperties()
                uri = workspace.uri + '/' + view.uri
                loadviewaction = webclientActions.LoadViewAction.generate(
                    uri, properties, entries, meta_data)
                return 'success', [loadviewaction]

        # view not found
        notification_action = webclientActions.NotificationAction.generate(
            "View >" + viewname + "< not found", "error")
        return 'success', [notification_action]
Beispiel #8
0
    def handle(self, action, user, workspace, actionManager):
        logManager.info("Execute action '{}' on view '{}'",
                        action['viewAction'], action['view'])
        viewname = action['view']
        if viewname in workspace.dataViews:
            print('found view', viewname, 'in', workspace.name,
                  workspace.dataViews[viewname])
            view = workspace.dataViews[viewname]

            # check if login required for this view
            if view.requireLogin is True and user is None:
                raise RequireLoginError
            else:
                # build actions to get view
                response_actions = []
                response_data = None
                try:
                    view.dataSyncs = []
                    dictionary = action
                    response_data = view.executeViewActionHandler(
                        user, workspace, ObjDict(dictionary))
                    notification_action = webclientActions.NotificationAction.generate(
                        "Action '" + str(action['viewAction']) + "' executed",
                        "info")
                    response_actions.append(notification_action)
                    self.db.session.commit()
                    for v in view.dataSyncs:
                        updateView = workspace.dataViews[v['view']]
                        meta_data = updateView.getViewMetaHandler(
                            user, workspace)
                        entries = updateView.getViewHandler(
                            user, workspace, None)
                        properties = updateView.getProperties()
                        uri = workspace.uri + '/' + updateView.uri
                        loadviewaction = webclientActions.LoadViewAction.generate(
                            uri, properties, entries, meta_data)
                        response_actions.append(loadviewaction)

                except Exception as e:
                    notification_action = webclientActions.NotificationAction.generate(
                        "Action '" + str(action['viewAction']) +
                        "' failed with: ", "error")
                    response_actions = [notification_action]
                    logManager.error(
                        str(type(e).__name__) +
                        'in ExecuteViewActionsActionHandler', action['view'])
                    traceback.print_exc(file=sys.stdout)
                # entries = view.getViewHandler(user, workspace)
                # properties = view.getProperties()
                # uri = view.uri
                # loadviewaction = webclientActions.LoadViewAction.generate(uri, properties, entries)
                if response_data is not None:
                    return 'success', response_actions, response_data
                else:
                    return 'success', response_actions

        # view not found
        notification_action = webclientActions.NotificationAction.generate(
            "View >" + viewname + "< not found", "error")
        return 'success', [notification_action]
Beispiel #9
0
    def mapWorkspaces(self, app):
        logManager.info("")
        logManager.info("ActionManager map workspaces")
        self.workspacesMap = {}
        for w in self.workspaceManager.workspaces:
            self.workspacesMap[str(w.uri)] = w

        pprint(self.workspacesMap, indent=2)
Beispiel #10
0
 def addDateArgument(self,
                     name,
                     label="",
                     description="",
                     optional=False,
                     group=None):
     logManager.info("Add date tyme argument for job {}".format(self.name))
     self.addArgument(name, 'date', label, description, optional, group)
Beispiel #11
0
 def addDoubleArgument(self,
                       name,
                       label="",
                       description="",
                       optional=False,
                       group=None):
     logManager.info("Add double type argument to job {}".format(self.name))
     self.addArgument(name, 'double', label, description, optional, group)
Beispiel #12
0
 def addStringArgument(self,
                       name,
                       label="",
                       description="",
                       optional=False,
                       group=None):
     logManager.info("Add string type argument to job {}".format(self.name))
     self.addArgument(name, 'string', label, description, optional, group)
Beispiel #13
0
 def handle(self, action, user, workspace, actionManager):
     logManager.info("Request user verification")
     user = User.query.filter_by(email=action.email).first()
     if user is None:
         raise Exception("User not found")
     else:
         user.account_verified = True
     return 'success', []
Beispiel #14
0
def trigger_job(job_key, args, user):
    logManager.info("User {} triggered job {}".format(user.email, job_key))
    job_id = jobManager.run_job(user,
                                job_key,
                                args,
                                datetime.now() + timedelta(seconds=5),
                                log_trigger=True)
    return job_id
Beispiel #15
0
    def handle(self, action, user, workspace, actionManager):
        logManager.info("Execute login action")
        replyActions = []
        user = (actionManager.userManager.getUser(action['username']))

        if user is not None:
            if user.account_verified is False:
                replyActions.append(
                    webclientActions.NotificationAction.generate(
                        "Your account need to be verified before login.",
                        "warning"))
                return 'success', replyActions
            if user.checkPassword(action['password']):
                userManager = actionManager.userManager
                menuBuilder = actionManager.menuBuilder
                # update serverside jwt token
                access_token = userManager.updateAccessToken(
                    action['username'])
                # update menu
                menu = menuBuilder.buildMenu(user)
                # build up
                replyActions.append(
                    webclientActions.UpdateSessionTokenAction.generate(
                        access_token))
                replyActions.append(
                    webclientActions.UpdateMenuAction.generate(menu))
                replyActions.append(
                    webclientActions.NotificationAction.generate(
                        "Login successful.", "success"))

                if 'options' in action and 'redirect' in action['options']:
                    if action['options']['redirect'] != "":
                        replyActions.append(
                            webclientActions.RouteAction.generate(
                                action['options']['redirect'], 2))
                    else:
                        replyActions.append(
                            webclientActions.RouteAction.generate(
                                "dashboard", 2))

                replyActions.append(
                    webclientActions.UpdateUserInfoAction.generate(
                        user.firstname, user.lastname, user.email))
                user.sessionValid = True
                user.last_login_date = arrow.utcnow()
                # actionManager.db.session.commit()
            else:
                replyActions.append(
                    webclientActions.NotificationAction.generate(
                        "Login failed, username or password is wrong.",
                        "error"))
        else:
            replyActions.append(
                webclientActions.NotificationAction.generate(
                    "Login failed, username or password is wrong.", "error"))

        return 'success', replyActions
Beispiel #16
0
 def addIntegerArgument(self,
                        name,
                        label="",
                        description="",
                        optional=False,
                        group=None):
     logManager.info("Add integer type argument for job {}".format(
         self.name))
     self.addArgument(name, 'integer', label, description, optional, group)
Beispiel #17
0
 def addBooleanArgument(self,
                        name,
                        label="",
                        description="",
                        optional=False,
                        group=None):
     logManager.info("Add boolean type argument for job {}".format(
         self.name))
     self.addArgument(name, 'boolean', label, description, optional, group)
Beispiel #18
0
    def init_manager(self, app, db, workspaceManager):
        self.app = app
        self.db = db
        self.workspaceManager = workspaceManager
        logManager.info("NodeManager initialized")

        from core.nodes.models import Node, NodeLog
        self.node = Node
        self.nodeLog = NodeLog
Beispiel #19
0
    def handle(self, action, user, workspace, actionManager):
        logManager.info("Execute update of view entry for '{}'",
                        action['view'])
        viewname = action['view']

        if viewname in workspace.dataViews:
            view = workspace.dataViews[viewname]
            # check if login required for this view
            if view.requireLogin is True and user is None:
                raise RequireLoginError
            else:
                # build actions to get view
                responseActions = []
                try:
                    if view.entrykey not in action['entry']:
                        notification_action = webclientActions.NotificationAction.generate(
                            "UpdateViewEntryActionHandler miss entrykey",
                            "error")
                        responseActions = [notification_action]
                    else:
                        view.dataSyncs = []
                        dictionary = action['entry']
                        view.updateViewEntryHandler(
                            user, workspace,
                            action['entry'][str(view.entrykey)],
                            ObjDict(dictionary))
                        self.db.session.commit()
                        for v in view.dataSyncs:
                            updateView = workspace.dataViews[v['view']]
                            entries = updateView.getViewHandler(
                                user, workspace, None)
                            meta_data = updateView.getViewMetaHandler(
                                user, workspace)
                            properties = updateView.getProperties()
                            uri = workspace.uri + '/' + updateView.uri
                            loadviewaction = webclientActions.LoadViewAction.generate(
                                uri, properties, entries, meta_data)
                            responseActions.append(loadviewaction)
                    responseActions.append(
                        webclientActions.NotificationAction.generate(
                            "Updated successfully", "success"))
                    return 'success', responseActions
                except Exception as e:
                    notification_action = webclientActions.NotificationAction.generate(
                        "UpdateViewEntry '" + str(action['view']) +
                        "' failed with: " + str(e), "error")
                    responseActions = [notification_action]
                    logManager.error(
                        str(type(e).__name__) +
                        'in ExecuteViewActionsActionHandler ' + action['view'])
                    traceback.print_exc(file=sys.stdout)
                return 'success', responseActions

        notification_action = webclientActions.NotificationAction.generate(
            "View >" + viewname + "< not found", "error")
        return 'success', [notification_action]
 def reloadWorkspaces(self):
     """Reset the list of all plugins and initiate the walk over the main
     provided plugin package to load all available plugins
     """
     self.workspaces = []
     self.seen_paths = []
     logManager.info("")
     logManager.info(
         f'Discover workspaces in path : {self.workspaceSource}')
     self.discoverWorkspaces(self.workspaceSource)
 def init_app(self, app, db):
     self.app = app
     self.db = db
     with self.app.app_context():
         self.reloadWorkspaces()
         self.registerWorkspacePlugins()
         self.registerWorkspacePermissions()
         logManager.info("Workspaces initialized")
         self.register_command_line_client()
         logManager.info("Command line client initialized")
Beispiel #22
0
 def handle(self, action, user, workspace, actionManager):
     logManager.info("Trigger job")
     response_actions = []
     job_execution_id = trigger_job(action.jobId, {}, user)
     notification_action = webclientActions.NotificationAction.generate(
         "Action triggered", "info")
     response_actions.append(notification_action)
     return 'success', response_actions, {
         "job_execution_id": job_execution_id
     }
Beispiel #23
0
    def discoverCommands(self, workspaceSource):

        command_source_path = workspaceSource + '.' + self.name + '.' + 'commands'
        # print("Discover actions for", self.uri, "from", actionsSource)
        try:
            command_source = __import__(command_source_path, fromlist=['blah'])
            self.app.register_blueprint(command_source.bp, cli_group=self.uri)
        except ModuleNotFoundError:
            logManager.info(
                f'No commands found for for workspace "{self.name}"')
Beispiel #24
0
    def handle(self, action, user, workspace, actionManager):
        user_to_assign = User.query.filter_by(email=action.userId).first()
        authenticator = Authenticator.query.filter_by(
            code=action.authenticatorCode).first()
        notification_action = webclientActions.NotificationAction.generate(
            "Assign authenticator was succesful.", "success")

        if user is None:
            notification_action = webclientActions.NotificationAction.generate(
                "You need to be logged in to do this action.", "error")
            return 'success', [notification_action], {
                'succeed': False,
                'message': "You have to be logged in to do this action."
            }

        logManager.info("Request for authenticator assign for {} by {}".format(
            action.userId, user.email))

        if user_to_assign is None:
            notification_action = webclientActions.NotificationAction.generate(
                "Failed to assign authenticator to user.", "error")
            return 'success', [notification_action], {
                'succeed': False,
                'message': "Failed to assign authenticator to user."
            }

        # there is no authenticator for the given authenticator code
        if authenticator is None or action.authenticatorCode == '' or action.authenticatorCode is None:
            notification_action = webclientActions.NotificationAction.generate(
                "Failed to assign authenticator to user.", "error")
            return 'success', [notification_action], {
                'succeed': False,
                'message': "Failed to assign authenticator to user."
            }

        # other user can only set authenticator if not already set
        if user.email != user_to_assign.email:
            if user_to_assign.authenticator_status is not UserAuthenticatorStatus.UNSET:
                notification_action = webclientActions.NotificationAction.generate(
                    "Failed to assign authenticator to user", "error")
                return 'success', [notification_action], {
                    'succeed': False,
                    'message': "Failed to assign authenticator to user."
                }

        user_to_assign.setAuthenticatorHash(authenticator.authenticator)
        user_to_assign.authenticator_public_key = authenticator.authenticator_public_key
        user_to_assign.authenticator_status = UserAuthenticatorStatus.VALID

        return 'success', [notification_action], {
            'succeed': True,
            'message': "Assign successful"
        }
Beispiel #25
0
    def init_manager(self, app, db, workspaceManager, config):
        self.config = config
        self.app = app
        self.db = db
        self.workspaceManager = workspaceManager

        from core.messages.models import Message
        self.message = Message

        jobManager.register_job(None, MailFromFileTemplateJob)

        logManager.info("MessageManager initialized")
Beispiel #26
0
    def init_manager(self, app, db, workspaceManager, config):
        self.config = config
        self.app = app
        self.db = db
        self.workspaceManager = workspaceManager
        self.pinAttemptLimit = 6
        logManager.info("UserManager initialized")

        from core.users.models import User, Authenticator
        self.user = User
        self.authenticator_request = Authenticator
        self.user_authenticator_cache = {}
Beispiel #27
0
    def mapActions(self, app):
        logManager.info("")
        logManager.info("ActionManager map actions")

        # register workspaces
        for w in self.workspaceManager.workspaces:
            self.actionsMap[str(w.uri)] = {}
            # map actions for every workspace by there uri
            for a in w.actions:
                self.actionsMap[str(w.uri)][a.uri] = a

        pprint(self.actionsMap, indent=2)
Beispiel #28
0
 def listener(self, event):
     if type(event) is SchedulerEvent:
         logManager.info("Got SchedulerEvent: {}".format(str(event)))
     elif type(event) is JobEvent:
         # logManager.info("Got JobEvent: {}".format(str(event)))
         pass
     elif type(event) is JobExecutionEvent:
         if event.exception:
             logManager.info("Got JobExecutionEvent: {}".format(str(event)))
     elif type(event) is JobSubmissionEvent:
         # logManager.info("Got JobSubmissionEvent: {}".format(str(event)))
         pass
     else:
         logManager.warning("Unknown JobEvent")
Beispiel #29
0
    def discoverJobs(self, workspaceSource):
        jobSource = workspaceSource + '.' + self.name + '.' + 'jobs'
        imported_source = __import__(jobSource, fromlist=['blah'])

        for _, jobname, ispkg in pkgutil.iter_modules(
                imported_source.__path__, imported_source.__name__ + '.'):
            if not ispkg:
                job_module = __import__(jobname, fromlist=['blah'])
                clsmembers = inspect.getmembers(job_module, inspect.isclass)
                for (_, c) in clsmembers:
                    # Check for DataView classes
                    if issubclass(c, Job) & (c is not Job):
                        if c.disable is False:
                            logManager.info(
                                f'Job registered from "{c.__module__}"')
                            jobManager.register_job(self, c, True)
Beispiel #30
0
    def handle(self, action, user, workspace, actionManager):
        logManager.info("Execute change password action")
        if user is not None:
            if user.checkPassword(action['oldpassword']):
                user.password = action['newpassword']
                notification_action = webclientActions.NotificationAction.generate(
                    "Password changed", "success")
            else:
                notification_action = webclientActions.NotificationAction.generate(
                    "Wrong current password!", "error")

        else:
            notification_action = webclientActions.NotificationAction.generate(
                "Internal error (user not found)", "error")

        return 'success', [notification_action]