Exemple #1
0
    def create_file_template(context, path):
        www_root=AppInfo.get_current_config("ui","wwwroot",exception=True)
        loader=jinja2.FileSystemLoader(www_root)

        jenv=JinjaTemplate.__create_environment(context, loader)

        template=jenv.get_template(path)
        return template
Exemple #2
0
    def render_status_template(context, http_status, err_desc):
        www_root=AppInfo.get_current_config("ui","wwwroot",exception=True)

        path=f"templates/error/{http_status}.htm"
        default_template="templates/error/default.htm"

        template=None
        log.create_logger(__name__).info(f"{FileSystemTools.format_path(www_root)}{path}")

        if os.path.isfile(f"{FileSystemTools.format_path(www_root)}{path}"):
            template=JinjaTemplate.create_file_template(context, path).render({"error": http_status, "description": err_desc})
        elif os.path.isfile(f"{FileSystemTools.format_path(www_root)}{default_template}"):
            template=JinjaTemplate.create_file_template(context, default_template).render({"error": http_status, "description": err_desc})
        else:
            template=JinjaTemplate.create_string_template(context,
            """<div>Statuscode_:{{ error }}</div><div>Description:{{ description }}</div>"""
            ).render({"error": http_status, "description": err_desc})

        return template
Exemple #3
0
def before_request():
    g.context=None

    if AppInfo.get_current_config('instance','enable_swagger_doc',0)==0:
        if request.endpoint=='doc':
            abort(404, "Not enabled")

    logger.info(f"Endpoint: {request.endpoint}")

    if request.endpoint!='api.login' and request.endpoint!='ui.login':
        if 'session_id' in session:
            try:
                g.context=AppInfo.create_context(session['session_id'])
            except NameError as err:
                abort(400, f"Session_id found in session context: error raised: {err}")
                pass
        else:
            #do not set session['session_id'] because the
            #guest session will be automaticly deactivated.
            username=""
            password=""
            if 'restapi_username' in request.headers:
                username=request.headers['restapi-username']
                password=request.headers['restapi-password']
            elif 'username' in request.headers:
                username=request.headers['username']
                password=request.headers['password']
            else:
                guest=AppInfo.guest_credentials()
                username=guest['username']
                password=guest['password']

            session_id=AppInfo.login(username,password)
            if session_id==None:
                print(f"try to login with username: {username}")
                abort(400,'Wrong username or password')

            g.context=AppInfo.create_context(session_id, auto_logoff=True)

        for arg in request.args:
            g.context.set_arg(arg, request.args[arg])
Exemple #4
0
    def get(self, path="index.htm", session_id=None, content_name=None):
        try:
            logger.info(f"Path: {path}")
            logger.info(f"content_name: {content_name}")
            logger.info(f"session_id: {session_id}")

            create_parser().parse_args()
            context = g.context

            portal_id = "default"
            #
            # content class
            #
            if not path.endswith("login.htm"):
                pass

            #
            # render the defined jinja template (in case ofahtm file)
            #
            if path.endswith('.htm'):
                next = HTTPRequest.redirect(request)
                logger.info(f"Redirect : {next}")

                fetch = build_fetchxml_by_alias(context,
                                                "api_portal",
                                                portal_id,
                                                type="select")
                fetchparser = FetchXmlParser(fetch, context)
                rs = DatabaseServices.exec(fetchparser, context, fetch_mode=1)
                if rs.get_result() == None:
                    abort(404, "Portal not found => %s" % id)

                # render the content first
                if content_name == None:
                    content_name = HTTPRequest.get_querystring_value(
                        request, "content_name", default="home")

                content = self.__get_content(context, portal_id, content_name)
                if content == None:
                    abort(404, "Content not found => %s" % content_name)

                params = {
                    "context": context,
                    "content_name": content_name,
                    "content_id": content['id']
                }

                template = JinjaTemplate.create_string_template(
                    context,
                    content['content'].encode('utf-8').decode('utf-8'))
                content_str = template.render(params)

                #
                # Render the complete page
                #
                params['content'] = content_str
                template = JinjaTemplate.create_file_template(context, path)
                page_str = template.render(params)

                response = make_response(page_str)
                response.headers['content-type'] = 'text/html'

                return response
            else:
                www_root = FileSystemTools.format_path(
                    AppInfo.get_current_config('ui', 'wwwroot',
                                               exception=True))
                return send_file(f"{www_root}{path}")

        except ConfigNotValid as err:
            logger.exception(f"Config not valid {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)
        except jinja2.exceptions.TemplateNotFound as err:
            logger.exception(f"TemplateNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(
                    context, 404, f"Template not found {err}"), 404)
        except FileNotFoundError as err:
            logger.exception(f"FileNotFound: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 404,
                                                     f"File not found {err}"),
                404)
        except RestApiNotAllowed as err:
            logger.exception(f"RestApiNotAllowed Exception: {err}")
            return redirect(f"/ui/login?redirect=/{path}", code=302)
        except Exception as err:
            logger.exception(f"Exception: {err}")
            return make_response(
                JinjaTemplate.render_status_template(context, 500, err), 500)