예제 #1
0
    def render(self, template_path, theme=None, status_code=200, **kwargs):
        if not theme:
            theme = self.get_active()

        # @TO-DO: use a context processor
        kwargs["env"] = {z: app.config[z] for z in app.config if z.islower()}
        kwargs["env"]["application_root"] = app.config["APPLICATION_ROOT"]

        user = UserController.get_current_user()
        user_context = get_current_user_data()

        if user_context:
            if not session.get("locale"):
                session["locale"] = user.locale

            elif session["locale"] != user.locale:
                session["locale"] = user.locale

        kwargs["user"] = user
        try:
            return render_template("%s/templates/%s.html" %
                                   (theme, template_path),
                                   url_for=url_for,
                                   **kwargs), status_code
        except TemplateNotFound as e:
            return "Template \"%s\" not found" % str(e)
        except Exception as ex:
            print(ex)
            if config("findex:findex:debug"):
                return "Jinja2 error!\n\n%s" % str(ex)
            return "Jinja2 error!"
예제 #2
0
    def add(content: str, title: str, current_user: User = None):
        if not isinstance(current_user, User):
            current_user = UserController.get_current_user()

        post = Post(content=content, title=title, created_by=current_user)
        db.session.add(post)
        db.session.commit()
        return post
예제 #3
0
    def remove_resource(resource_id, auto_remove_server=True, **kwargs):
        """
        Removes a resource from the database.
        :param resource_id: The resource ID
        :param auto_remove_server: removes the server this resource
        has a relationship with, but only when that server does not
        have any other existing resource members/childs
        :param kwargs:
        :return:
        """
        user = UserController.get_current_user()

        if not user.admin:
            resources = ResourceController.get_resources(by_owner=user.id)
            resource = [r for r in resources if r.id == resource_id]
            if not resource or isinstance(resource, Exception):
                raise FindexException("Could not fetch resource id \"%d\"" %
                                      resource_id)
            else:
                resource = resource[0]
        else:
            resource = db.session.query(Resource).filter(
                Resource.id == resource_id).first()
            if not resource:
                raise FindexException("Could not fetch resource id \"%d\"" %
                                      resource_id)

        if auto_remove_server:
            # check for other server resource members before trying to delete
            server = resource.server
            if [z for z in server.resources if z.id != resource_id]:
                # cant remove server, it still has one or more member(s)
                db.session.delete(resource)
            else:
                db.session.delete(resource)
                db.session.delete(server)
        else:
            db.session.delete(resource)

        db.session.commit()
        db.session.flush()
예제 #4
0
def check_role(requirements, **kwargs):
    """Raises exception on bad role"""
    from findex_gui.controllers.user.user import UserController
    if "skip_authorization" in kwargs:
        return

    def check_requirements(_user):
        for requirement in requirements:
            roles = [r.name for r in _user.roles]
            if requirement not in roles:
                raise RoleException("current user does not have the "
                                    "required role \"%s\"" % requirement)
        return _user

    try:
        user = UserController.get_current_user(apply_timeout=False)
    except RuntimeError:
        return

    if user:
        if user.admin:
            return user
        return check_requirements(user)
예제 #5
0
    def add_resource(resource_port,
                     resource_protocol,
                     server_name=None,
                     server_address=None,
                     server_id=None,
                     description="",
                     display_url="/",
                     basepath="/",
                     recursive_sizes=True,
                     auth_user=None,
                     auth_pass=None,
                     auth_type=None,
                     user_agent=static_variables.user_agent,
                     throttle_connections=-1,
                     current_user=None,
                     group="Default"):
        """
        Adds a local or remote file resource
        :param server_name: Server name
        :param server_address: ipv4 'str' - clean hostname or IP
        :param server_id: server DB id
        :param resource_port: valid port number
        :param resource_protocol: valid protocol number 'int' - see `findex_common.static_variables.FileProtocols`
        :param description: resource description 'str'
        :param display_url: url prefix as it will be shown on the front-end 'str'
        :param basepath: the absolute crawl root path 'str'
        :param recursive_sizes: recursively calculate directory sizes (performance impact during crawl)
        :param auth_user: resource user authentication 'str'
        :param auth_pass: resource pass authentication 'str'
        :param auth_type: resource type authentication 'str'
        :param user_agent: The string to identify ourselves with against the service 'str'
        :param throttle_connections: Wait X millisecond(s) between each request/connection 'int'
        :return: resource
        """
        if server_id:
            _server = db.session.query(Server).filter(
                Server.id == server_id).first()
        elif server_address:
            _server = db.session.query(Server).filter(
                Server.address == server_address).first()
        else:
            raise FindexException(
                "Either use server_id to refer to an existing Server "
                "object or supply a valid `server_name`, `server_port` "
                "and/or `server_address` parameters.")
        if not _server:
            if not isinstance(server_address, str) or not \
                    isinstance(resource_port, int) or not isinstance(resource_protocol, int):
                raise FindexException(
                    "Could not auto-add server for resource - requires "
                    "`resource_port`, `resource_protocol` and `server_address`"
                )
            if resource_port > 65535 or resource_port < 1:
                raise FindexException("invalid port")
            _server = ResourceController.add_server(name=server_name,
                                                    hostname=server_address)
        if not basepath:
            basepath = "/"
        elif not basepath.startswith("/") and len(basepath) > 1:
            basepath = "/%s" % basepath

        if _server.resources:
            for parent in _server.resources:
                if parent.port == resource_port and parent.protocol == resource_protocol \
                        and parent.basepath == basepath:
                    raise FindexException(
                        "Duplicate resource previously defined with resource id \"%d\""
                        % parent.id)

        resource = Resource(server=_server,
                            protocol=resource_protocol,
                            port=resource_port,
                            display_url=display_url,
                            basepath=basepath)
        resource.description = description
        resource.date_crawl_next = datetime.now()
        rm = ResourceMeta()
        if auth_user and auth_pass:
            rm.set_auth(auth_user, auth_pass, auth_type)
        rm.recursive_sizes = recursive_sizes
        rm.web_user_agent = user_agent
        rm.throttle_connections = throttle_connections
        resource.meta = rm

        if isinstance(current_user, int):
            current_user = db.session.query(User).filter(
                User.admin == True).first()
        elif current_user is None:
            current_user = UserController.get_current_user(apply_timeout=False)
        elif isinstance(current_user, User):
            pass
        else:
            raise Exception("bad type for parameter current_user")

        if not current_user:
            raise FindexException("Could not fetch the current user")

        resource.created_by = current_user

        db.session.add(resource)
        db.session.commit()

        resource.group = db.session.query(ResourceGroup).filter(
            ResourceGroup.name == group).first()
        db.session.commit()
        db.session.flush()

        return resource