예제 #1
0
 def save_storage(self, storage):
     args = {
         "id": storage["id"],
         "scheme": storage["scheme"],
         "username": storage["username"],
         "password": storage["password"],
         "netloc": storage["netloc"],
         "port": storage["port"],
         "path": storage["path"],
         "params": storage["params"],
         "query": storage["query"],
         "fragment": storage["fragment"],
         "mangle_id": storage["mangle_id"],
         "expires": storage["expires"],
         "public": coerce_value(storage["public"], "bool"),
         "internal_url": storage["internal_url"],
         "external_url": storage["external_url"],
         "internal_thumb_url": storage["internal_thumb_url"],
         "external_thumb_url": storage["external_thumb_url"],
         "content_type": storage["content_type"],
         "charset": storage["charset"],
         "size": storage["size"],
         "file_path": storage["file_path"],
         "file_path_thumb": storage["file_path_thumb"],
         "variables": self._Tools.data_pickle(storage['variables']),
         "created_at": storage["created_at"],
     }
     yield self.dbconfig.insert("storage", args)
예제 #2
0
 def update_attributes(self, record=None, stay_clean=None):
     """
     Update various attributes
     
     :param record:
     :return: 
     """
     if record is None:
         return
     if 'is_valid' in record:
         self.is_valid = coerce_value(record['is_valid'], 'bool')
     if 'label' in record:
         self.label = record['label']
     if 'label' in record:
         self.label = record['label']
     if 'description' in record:
         self.description = record['description']
     if 'permissions' in record:
         self.permissions = record['permissions']
     if 'last_access' in record:
         self.last_access = record['last_access']
     if 'created_at' in record:
         self.created_at = record['created_at']
     if 'updated_at' in record:
         self.updated_at = record['updated_at']
     if 'auth_data' in record:
         if isinstance(record['auth_data'], dict):
             self.auth_data.update(record['auth_data'])
     if stay_clean is not True:
         self.is_dirty = 2000
예제 #3
0
        def page_user_login_user_get(webinterface, request, session):
            if session.enabled is True and session.is_valid(
            ) is True and session.has_user is True:
                print("login, but already have a valid user user....")
                return request.redirect("/")
            host = request.getHost()
            hostname = request.getRequestHostname().decode('utf-8')
            session["login_request_id"] = yombo.utils.random_string(length=50)

            auto_login_redirect_input = coerce_value(
                request.args.get('autoredirect', 0), 'int')
            auto_login_redirect = 0
            if isinstance(auto_login_redirect_input, int):
                if auto_login_redirect == 1:
                    auto_login_redirect = 1
            if auto_login_redirect == 0 and "auto_login_redirect" in session:
                auto_login_redirect = session["auto_login_redirect"]

            return webinterface.render(
                request,
                session,
                webinterface.wi_dir + "/pages/user/login_user.html",
                request_id=session["login_request_id"],
                secure=1 if request.isSecure() else 0,
                hostname=hostname,
                port=host.port,
                gateway_id=webinterface.gateway_id,
                autoredirect=auto_login_redirect,
            )
예제 #4
0
def setup_login_redirect(request, login_redirect):
    """
    If login_redirect is not none, return a session. Either create a new session or
    update the existing session.

    :param request:
    :param login_redirect:
    :return:
    """
    session = request.auth
    if login_redirect is None:  # only create a new session if we need too
        login_redirect = request.uri.decode('utf-8')

    try:
        session["auto_login_redirect"] = coerce_value(request.args.get('autologinredirect', [0])[0], 'int')
    except:
        session["auto_login_redirect"] = 0

    session.created_by = "setup_login_redirect"
    # request.received_cookies[webinterface._WebSessions.config.cookie_session_name] = session.auth.auth_id

    # If login redirect end with something silly, ignore it
    if login_redirect.endswith(('.js', '.jpg', '.png', '.css')):
        login_redirect = "/"

    # If we already have a login redirect url and a new one ends with something silly, ignore it
    if "login_redirect" not in session:
        session["login_redirect"] = login_redirect
    else:  # Just display a warning...
        logger.debug("Already have login redirect: {login_redirect}", login_redirect=session['login_redirect'])
예제 #5
0
    def load_states(self):
        states = yield self._LocalDB.get_states()

        for state in states:
            if state['name'] not in self.__States[self.gateway_id]:
                self.__States[self.gateway_id][state['name']] = {
                    'gateway_id': state['gateway_id'],
                    'value': coerce_value(state['value'], state['value_type']),
                    'value_human': self.convert_to_human(state['value'], state['value_type']),
                    'value_type': state['value_type'],
                    'live': state['live'],
                    'created_at': state['created_at'],
                    'updated_at': state['updated_at'],
                }
        self.init_deferred.callback(10)
        def parse_record(data):
            auth_data = data_unpickle(data.auth_data)

            return {
                "id": data.id,
                "enabled": coerce_value(data.enabled, "bool"),
                "user_id": data.user_id,
                "auth_data": auth_data,
                "refresh_token": data.refresh_token,
                "access_token": data.access_token,
                "refresh_token_expires_at": data.refresh_token_expires_at,
                "access_token_expires_at": data.access_token_expires_at,
                "created_at": data.created_at,
                "last_access_at": data.last_access_at,
                "updated_at": data.updated_at,
            }
예제 #7
0
def setup_login_redirect(webinterface, request, session, login_redirect):
    """
    If login_redirect is not none, return a session. Either create a new session or
    update the existing session.

    :param webinterface:
    :param request:
    :param login_redirect:
    :return:
    """
    if login_redirect is None:  # only create a new session if we need too
        login_redirect = request.uri.decode('utf-8')

    if session is None:
        try:
            session = webinterface._WebSessions.create_from_web_request(request)
            # print(f"setup_login_redirect: created new session: {session.asdict()}")
        except YomboWarning as e:
            logger.warn("Discarding request, appears to be malformed request. Unable to create session.")
            return return_need_login(webinterface, request, None,
                                     api_message="Malformed request headers.",
                                     )
        except RateLimitException as e:
            logger.warn("Too many sessions being created!")
            return _("ui::messages::rate_limit_exceeded", "Too many attempts, try again later.")

    try:
        auto_login_redirect = coerce_value(request.args.get('autologinredirect', [0])[0], 'int')
    except:
        auto_login_redirect = 0

    session.created_by = "login_redirect"
    request.received_cookies[webinterface._WebSessions.config.cookie_session_name] = session.auth_id

    # If login redirect end with something silly, ignore it
    if login_redirect.endswith(('.js', '.jpg', '.png', '.css')):
        login_redirect = "/"

    # If we already have a login redirect url and a new one ends with something silly, ignore it
    if "login_redirect" not in session:
        session["login_redirect"] = login_redirect
    else:  # Just display a warning...
        logger.debug("Already have login redirect: {login_redirect}", login_redirect=session['login_redirect'])

    session["auto_login_redirect"] = auto_login_redirect
    return session
 def update_web_session(self, session):
     logger.debug("update_web_session: session.auth_id: {auth_id}", auth_id=session._auth_id)
     save_data = data_pickle({
         "auth_data": session.auth_data,
         "auth_type": session.auth_type,
         "auth_at": session.auth_at,
     })
     args = {
         "enabled": coerce_value(session.enabled, "int"),
         "auth_data": save_data,
         "refresh_token": session._refresh_token,
         "access_token": session._access_token,
         "refresh_token_expires_at": session.refresh_token_expires_at,
         "access_token_expires_at": session.access_token_expires_at,
         "user_id": session.user_id,
         "last_access_at": session.last_access_at,
         "updated_at": session.updated_at,
         }
     yield self.dbconfig.update("webinterface_sessions", args, where=["id = ?", session._auth_id])
예제 #9
0
 def load_states(self):
     states = yield self._LocalDB.get_states()
     for state in states:
         if state["gateway_id"] not in self.states:
             self.states[state["gateway_id"]] = {}
         if state["name"] not in self.states[state["gateway_id"]]:
             self.states[state["gateway_id"]][state["name"]] = {
                 "gateway_id":
                 state["gateway_id"],
                 "value":
                 coerce_value(state["value"], state["value_type"]),
                 "value_human":
                 self.convert_to_human(state["value"], state["value_type"]),
                 "value_type":
                 state["value_type"],
                 "live":
                 state["live"],
                 "created_at":
                 state["created_at"],
             }
    def save_web_session(self, session):
        logger.debug("save_web_session: session.auth_id: {auth_id}", auth_id=session._auth_id)
        logger.debug("save_web_session: session.auth_data: {auth_data}", auth_data=session.auth_data)
        auth_data = data_pickle({
            "auth_data": session.auth_data,
            "auth_type": session.auth_type,
            "auth_at": session.auth_at,
        })

        args = {
            "id": session._auth_id,
            "enabled": coerce_value(session.enabled, "int"),
            "auth_data": auth_data,
            "refresh_token": session._refresh_token,
            "access_token": session._access_token,
            "refresh_token_expires_at": session.refresh_token_expires_at,
            "access_token_expires_at": session.access_token_expires_at,
            "user_id": session.user_id,
            "created_at": session.created_at,
            "last_access_at": session.last_access_at,
            "updated_at": session.updated_at,
        }
        yield self.dbconfig.insert("webinterface_sessions", args, None, "OR IGNORE")
예제 #11
0
    def update_attributes(self, record, source=None):
        """
        Update various attributes
        
        :param record:
        :return: 
        """
        if record is None:
            return
        # if "auth_data" in record:
        #     if isinstance(record["auth_data"], dict):
        #         temp = self.auth_data.copy()
        #         temp.update(record["auth_data"])
        #         record["auth_data"] = temp
        if "enabled" in record:
            record["enabled"] = coerce_value(record["enabled"], "bool")
        if "scope" in record:
            if record["scope"] not in ("local", "cluster"):
                raise YomboWarning(
                    f"Auth key scope must be one of: local, cluster.  '{record['scope']}'"
                    " is not permitted.")
        if "item_permissions" in record:
            if isinstance(record["item_permissions"], dict) is False:
                del record["item_permissions"]
        if "roles" in record:
            if isinstance(record["roles"], list):
                for role_id in record["roles"]:
                    try:
                        self.attach_role(role_id,
                                         save=False,
                                         flush_cache=False)
                    except KeyError:
                        logger.warn(
                            "Auth key {label} was unable to add role_id (don't exist)",
                            label=self.label)

        super().update_attributes(record, source=source)
예제 #12
0
        def page_automation_action_edit_state_post(webinterface, request,
                                                   session, rule_id,
                                                   action_id):
            session.has_access("automation", rule_id, "edit", raise_error=True)
            try:
                rule = webinterface._Automation.get(rule_id)
            except YomboWarning as e:
                webinterface.add_alert(e.message, "warning")
                return webinterface.redirect(request, "/automation/index")
            rule_id = rule.rule_id

            try:
                action = webinterface._Automation.get_action_items(
                    rule_id, action_id)
            except YomboWarning as e:
                webinterface.add_alert(
                    "Requested action id could not be located.", "warning")
                return webinterface.redirect(request,
                                             f"/automation/{rule_id}/details")
            data = {
                "action_type":
                "state",
                "name":
                webinterface.request_get_default(request, "name", ""),
                "value":
                webinterface.request_get_default(request, "value", ""),
                "value_type":
                webinterface.request_get_default(request, "value_type", ""),
                "gateway_id":
                webinterface.request_get_default(request, "gateway_id",
                                                 webinterface.gateway_id),
                "weight":
                int(
                    webinterface.request_get_default(request, "weight", (len(
                        webinterface._Automation.get_action_items(rule_id)) +
                                                                         1) *
                                                     10)),
            }

            if data["name"] == "":
                webinterface.add_alert("Must enter a state name.", "warning")
                return page_automation_action_state_form(
                    webinterface, request, session, rule, data, "add",
                    "Edit action action: State")

            if data["value"] == "":
                webinterface.add_alert("Must enter a state value to set.",
                                       "warning")
                return page_automation_action_state_form(
                    webinterface, request, session, rule, data, "add",
                    "Edit action action: State")

            if data["value_type"] == "" or data["value_type"] not in (
                    "integer", "string", "boolean", "float"):
                webinterface.add_alert(
                    "Must enter a state value_type to ensure validity.",
                    "warning")
                return page_automation_action_state_form(
                    webinterface, request, session, rule, data, "add",
                    "Edit action action: State")

            value_type = data["value_type"]
            if value_type == "string":
                data["value"] = coerce_value(data["value"], "string")
            elif value_type == "integer":
                try:
                    data["value"] = coerce_value(data["value"], "int")
                except Exception:
                    webinterface.add_alert(
                        "Cannot coerce state value into an integer", "warning")
                    return page_automation_action_state_form(
                        webinterface, request, session, rule, data, "add",
                        "Edit rule action: State")
            elif value_type == "float":
                try:
                    data["value"] = coerce_value(data["value"], "float")
                except Exception:
                    webinterface.add_alert(
                        "Cannot coerce state value into an float", "warning")
                    return page_automation_action_state_form(
                        webinterface, request, session, rule, data, "add",
                        "Edit rule action: State")
            elif value_type == "boolean":
                try:
                    data["value"] = coerce_value(data["value"], "bool")
                    if isinstance(data["value"], bool) is False:
                        raise Exception()
                except Exception:
                    webinterface.add_alert(
                        "Cannot coerce state value into an boolean", "warning")
                    return page_automation_action_state_form(
                        webinterface, request, session, rule, data, "add",
                        "Edit rule action: State")
            else:
                webinterface.add_alert("Unknown value type.", "warning")
                return page_automation_action_state_form(
                    webinterface, request, session, rule, data, "add",
                    "Edit rule action: State")

            try:
                data["weight"] = int(data["weight"])
            except Exception:
                webinterface.add_alert("Must enter a number for a weight.",
                                       "warning")
                return page_automation_action_state_form(
                    webinterface, request, session, rule, data, "add",
                    "Edit action action: State")

            try:
                webinterface._Automation.edit_action_item(
                    rule_id, action_id, **data)
            except YomboWarning as e:
                webinterface.add_alert(
                    f"Cannot edit state within rule. {e.message}", "warning")
                return page_automation_action_state_form(
                    webinterface, request, session, rule, data, "add",
                    "Edit action action: State")

            webinterface.add_alert("Edited state action for rule.")
            return webinterface.redirect(request,
                                         f"/automation/{rule_id}/details")
예제 #13
0
        def page_scenes_action_state_add_post(webinterface, request, session,
                                              scene_id):
            session.has_access("scene", scene_id, "edit", raise_error=True)
            try:
                scene = webinterface._Scenes.get(scene_id)
            except KeyError as e:
                webinterface.add_alert(e.message, "warning")
                return webinterface.redirect(request, "/scenes/index")

            data = {
                "action_type":
                "state",
                "name":
                webinterface.request_get_default(request, "name", ""),
                "value":
                webinterface.request_get_default(request, "value", ""),
                "value_type":
                webinterface.request_get_default(request, "value_type", ""),
                "gateway_id":
                webinterface.request_get_default(request, "gateway_id",
                                                 webinterface.gateway_id),
                "weight":
                int(
                    webinterface.request_get_default(
                        request, "weight",
                        (len(webinterface._Scenes.get_action_items(scene_id)) +
                         1) * 10)),
            }

            if data["name"] == "":
                webinterface.add_alert("Must enter a state name.", "warning")
                return page_scenes_form_state(webinterface, request, session,
                                              scene, data, "add",
                                              "Add state to scene")

            if data["value"] == "":
                webinterface.add_alert("Must enter a state value to set.",
                                       "warning")
                return page_scenes_form_state(webinterface, request, session,
                                              scene, data, "add",
                                              "Add state to scene")

            if data["value_type"] == "" or data["value_type"] not in (
                    "integer", "string", "boolean", "float"):
                webinterface.add_alert(
                    "Must enter a state value_type to ensure validity.",
                    "warning")
                return page_scenes_form_state(webinterface, request, session,
                                              scene, data, "add",
                                              "Add state to scene")

            value_type = data["value_type"]
            if value_type == "string":
                data["value"] = coerce_value(data["value"], "string")
            elif value_type == "integer":
                try:
                    data["value"] = coerce_value(data["value"], "int")
                except Exception:
                    webinterface.add_alert(
                        "Cannot coerce state value into an integer", "warning")
                    return page_scenes_form_state(webinterface, request,
                                                  session, scene, data, "add",
                                                  "Add state to scene")
            elif value_type == "float":
                try:
                    data["value"] = coerce_value(data["value"], "float")
                except Exception:
                    webinterface.add_alert(
                        "Cannot coerce state value into an float", "warning")
                    return page_scenes_form_state(webinterface, request,
                                                  session, scene, data, "add",
                                                  "Add state to scene")
            elif value_type == "boolean":
                try:
                    data["value"] = coerce_value(data["value"], "bool")
                    if isinstance(data["value"], bool) is False:
                        raise Exception()
                except Exception:
                    webinterface.add_alert(
                        "Cannot coerce state value into an boolean", "warning")
                    return page_scenes_form_state(webinterface, request,
                                                  session, scene, data, "add",
                                                  "Add state to scene")

            try:
                data["weight"] = int(data["weight"])
            except Exception:
                webinterface.add_alert("Must enter a number for a weight.",
                                       "warning")
                return page_scenes_form_state(webinterface, request, session,
                                              scene, data, "add",
                                              "Add state to scene")

            try:
                webinterface._Scenes.add_action_item(scene_id, **data)
            except KeyError as e:
                webinterface.add_alert(
                    f"Cannot add state to scene. {e.message}", "warning")
                return page_scenes_form_state(webinterface, request, session,
                                              scene, data, "add",
                                              "Add state to scene")

            webinterface.add_alert("Added state action to scene.")
            return webinterface.redirect(request,
                                         f"/scenes/{scene.scene_id}/details")