Exemplo n.º 1
0
def index(req: Request):
    uuid = uuid4().hex
    env[uuid] = {'session_id': uuid}
    response = HTMLResponse(
        templates.TemplateResponse('index.html', {'endpoints': endpoints}))
    response.set_cookie('sessionId', uuid)
    return response
Exemplo n.º 2
0
        async def handle_401_403(request, call_next):
            response = await call_next(request)
            request_dict = dict(request)
            if response.status_code in [401, 404]:
                if 'text/html' in request.headers['accept']:
                    if response.status_code == 404:
                        return HTMLResponse(self.admin.not_found_page(),
                                            status_code=404)
                    response = HTMLResponse(self.admin.login_page(
                        welcome_message='Login Required'),
                                            status_code=401)
                    response.set_cookie('token', 'INVALID')
                    response.set_cookie('ref',
                                        request.__dict__['scope']['path'])

            if response.status_code == 500:
                log.error(
                    f"Internal error - 500 - with request: {request.__dict__}")
            return response
Exemplo n.º 3
0
        async def handle_401_403(request, call_next):
            response = await call_next(request)
            request_dict = dict(request)

            if response.status_code in [401, 404]:
                if "text/html" in request.headers["accept"]:
                    if response.status_code == 404:
                        return self.html_not_found_page()

                    response = HTMLResponse(
                        await self.get_login_page(message="Login Required",
                                                  request=request),
                        status_code=401,
                    )
                    response.set_cookie("token", "INVALID",
                                        **self.cookie_security)
                    response.set_cookie("ref",
                                        request.__dict__["scope"]["path"],
                                        **self.cookie_security)

            if response.status_code == 500:
                self.log.error(
                    f"Internal error - 500 - with request: {request.__dict__}")
            return response
Exemplo n.º 4
0
            async def mock_function(*args, **kwargs):
                request = kwargs["request"]
                token = kwargs["token"]
                if token in {"NO_TOKEN", "INVALID"}:
                    if (response_class is HTMLResponse
                            or "text/html" in request.headers["accept"]):
                        response = HTMLResponse(
                            await self.get_login_page(message="Login Required",
                                                      request=request),
                            status_code=401,
                        )
                        response.set_cookie("token", "INVALID",
                                            **self.cookie_security)
                        response.set_cookie(
                            "ref",
                            request.__dict__["scope"]["path"],
                            **self.cookie_security,
                        )
                        return response
                try:
                    token = self.decode_token(token)[1]
                except Exception as e:
                    if isinstance(e, InvalidJWSSignature):
                        self.log.error(
                            f"EasyAuthClient failed to decode token - keys may have rotated - login wil be required"
                        )
                    else:
                        self.log.exception(f"error decoding token")
                    if (response_class is HTMLResponse
                            or "text/html" in request.headers["accept"]):
                        response = HTMLResponse(
                            await self.get_login_page(message="Login Required",
                                                      request=request),
                            status_code=401,
                        )
                        response.set_cookie("token", "INVALID",
                                            **self.cookie_security)
                        response.set_cookie(
                            "ref",
                            request.__dict__["scope"]["path"],
                            **self.cookie_security,
                        )
                        # response.headers["ref"] = request.__dict__["scope"]["path"]
                        return response
                    raise HTTPException(
                        status_code=401,
                        detail=f"not authorized, invalid or expired")

                allowed = False
                for auth_type, values in permissions.items():
                    if not auth_type in token["permissions"]:
                        self.log.warning(f"{auth_type} is required")
                        continue
                    for value in values:
                        if value in token["permissions"][auth_type]:
                            allowed = True
                            break

                if not token["token_id"] in self.store["tokens"]:
                    self.log.error(
                        f"token for user {token['permissions']['users'][0]} - {token['token_id']} is unknown / revoked {self.store['tokens']}"
                    )
                    if (response_class is HTMLResponse
                            or "text/html" in request.headers["accept"]):
                        response = HTMLResponse(
                            await self.get_login_page(message="Login Required",
                                                      request=request),
                            status_code=401,
                        )
                        response.set_cookie("token", "INVALID",
                                            **self.cookie_security)
                        response.set_cookie(
                            "ref",
                            request.__dict__["scope"]["path"],
                            **self.cookie_security,
                        )
                        # response.headers["ref"] = request.__dict__["scope"]["path"]
                        return response
                    raise HTTPException(
                        status_code=401,
                        detail=f"not authorized, invalid or expired")

                if not allowed:
                    if (response_class is HTMLResponse
                            or "text/html" in request.headers["accept"]):
                        response = HTMLResponse(
                            await self.get_403_page(
                            ),  # self.admin.forbidden_page(),
                            status_code=403,
                        )
                        return response
                    raise HTTPException(
                        status_code=403,
                        detail=
                        f"not authorized, permissions required: {permissions}",
                    )

                if "access_token" in kwargs:
                    kwargs["access_token"] = token

                if not send_token:
                    del kwargs["token"]
                if not send_request:
                    del kwargs["request"]

                result = func(*args, **kwargs)
                if asyncio.iscoroutine(result):
                    return await result
                return result
Exemplo n.º 5
0
async def home(request: Request):
    """
     Primary landing section for the app

    :param request: request object sent in the post body when accessing this API
    :return: Will return a rendered HTML page
    """
    # Handle the rendering of the login url
    login_url = ""
    user = ""
    flow = request.cookies.get("flow")
    if not request.cookies.get("user"):
        if keyVaultName:
            flow = auth.build_auth_code_flow(
                client_id=secret_client.get_secret("login-app-clientid").value,
                secret=secret_client.get_secret("login-app-pwd").value,
                scopes=auth.SCOPE)
        else:
            flow = auth.build_auth_code_flow(scopes=auth.SCOPE)
        login_url = flow["auth_uri"]
    else:
        user = json.loads(request.cookies.get("user"))

    # Modal Templates
    tenant_input_html = "Please enter the Tenant ID for the Azure Instance you are using.  This is needed to set up" \
                        "authentication.  You can find this by typing \"Tenant\" into the Azure Portal for where you" \
                        " intend to deploy your infrastructure." + \
                        br().render() + \
                        div(
                            input_("Tenant ID", id="tenantId", cls="form-control", aria_label="Small",
                                   aria_describedby="inputGroup-sizing-sm"),
                            div(
                                button("Save Id", type="button", id="saveTenant",
                                       cls="btn btn-outline-secondary"),
                                cls="input-group-append"),
                            cls="input-group input-group-sm mb-3").render(pretty=False)

    login_input_html = "Click the below button to initiate AAD authentication" + br(
    ).render() + div(
        a("Login", href=login_url),
        cls="input-group input-group-sm mb-3").render(pretty=False)

    try:
        config = json.load(open("form_config.json"))
    except FileNotFoundError:
        config = None

    # Initiate the HTML Document
    doc = dominate.document(title="Mission LZ")

    # Set initial style sheet in HTML doc head
    with doc.head:
        link(rel='stylesheet', href=static_location + 'bootstrap.min.css')
        link(rel='stylesheet', href=static_location + 'custom.css')

    # Fill in the single page app template with forms and sections
    with doc:
        # Case for each variable type in JSON definition
        with div(cls="navbar navbar-expand-lg fixed-top navbar-dark bg-primary"
                 ):
            with div(cls="container"):
                a("Mission LZ", cls="navbar-brand", href="#")
                with div(cls='text-right'):
                    if user:
                        a("Logout " + user["name"],
                          href="/logout",
                          cls="btn btn-outline-secondary")

        with div(cls="container"):
            with div(cls="page-header"):
                if config:
                    pass
                    # Parse each config element in a switch to generate a section of forms for it
                else:
                    build_form(find_config())

        # Modal
        with div(cls="modal fade",
                 data_backdrop="static",
                 id="promptModal",
                 tabindex="-1",
                 role="dialog",
                 aria_hidden="true"):
            with div(cls="modal-dialog modal-dialog-centered modal-lg",
                     role="document"):
                with div(cls="modal-content"):
                    with div(cls="modal-header"):
                        h5("Modal Title", cls="modal-title")
                    div("Modal Content", cls="modal-body")
                    with div(cls="modal-footer"):
                        button("Close",
                               id="modBtn",
                               type="button",
                               cls="btn btn-secondary",
                               data_dismiss="modal")

        # Include the Javascript Files in the output HTML
        script(src=static_location + 'jquery-3.5.1.min.js')
        script(src=static_location + 'bootstrap.bundle.min.js')
        script(src=static_location + 'custom.js')

        script().add_raw_string("""
        function promptLogin() {
            $('#promptModal').on('show.bs.modal', function (event) {
              var modal = $(this)
              modal.find('.modal-title').text('Login')
              modal.find('.modal-body').html('""" + login_input_html + """')
              modal.find('#modBtn').hide()
            })
            $('#promptModal').modal('show')
        }

        var interval = null
        function retrieve_results() {
          $.ajax({
           type: "GET",
           url: "/poll",
           success: function(msg){
             $("#terminal").text(msg);
             $("#terminal").scrollTop($("#terminal")[0].scrollHeight);
           }
         });
        }

        function submitForm(){
            interval = setInterval(retrieve_results, 2000);
        }

        $(document).ready(function(){
            $('#showTenant').click(function(){
                promptTenant()
            })

            logged_in = readCookie("user")

            if(!logged_in || $.trim(logged_in) == ""){
              promptLogin()
            }
        })

        $(document).on('submit', '#terraform_config', function(e) {
            $('#promptModal').on('show.bs.modal', function (event) {
              var modal = $(this)
              modal.find('.modal-title').text('Polling execution results: (Box May Stay Blank for an extended amount of time)')
              modal.find('.modal-body').html('<pre id="terminal"></pre>')
              modal.find('#modBtn').show()
              modal.find('#modBtn').click(function(){
                clearInterval(interval)
              })
            })
            $('#promptModal').modal('show')
             $.ajax({
                url: $(this).attr('action'),
                type: $(this).attr('method'),
                data: $(this).serialize(),
                success: function(html) {
                    submitForm()
                }
            });
            e.preventDefault();
        });

        $("input").change(function(){
            $("input[name="+ this.name +"]").val(this.value)
        })
        """)

    response = HTMLResponse(content=str(doc), status_code=200)
    response.set_cookie("flow", json.dumps(flow), expires=3600)
    return response
Exemplo n.º 6
0
            async def mock_function(*args, **kwargs):
                request = kwargs['request']
                token = kwargs['token']
                if token == 'NO_TOKEN':
                    if response_class is HTMLResponse or 'text/html' in request.headers[
                            'accept']:
                        response = HTMLResponse(self.admin.login_page(
                            welcome_message='Login Required'),
                                                status_code=401)
                        response.set_cookie('token', 'INVALID')
                        response.set_cookie('ref',
                                            request.__dict__['scope']['path'])
                        return response

                try:
                    token = self.decode_token(token)[1]
                    self.log.debug(f"decoded token: {token}")
                except Exception:
                    self.log.exception(f"error decoding token")
                    if response_class is HTMLResponse:
                        response = HTMLResponse(self.admin.login_page(
                            welcome_message='Login Required'),
                                                status_code=401)
                        response.set_cookie('token', 'INVALID')
                        response.set_cookie('ref',
                                            request.__dict__['scope']['path'])
                        return response
                    raise HTTPException(
                        status_code=401,
                        detail=f"not authorized, invalid or expired")

                allowed = False
                for auth_type, values in permissions.items():
                    if not auth_type in token['permissions']:
                        self.log.warning(f"{auth_type} is required")
                        continue
                    for value in values:
                        if value in token['permissions'][auth_type]:
                            allowed = True
                            break
                if not allowed:
                    if response_class is HTMLResponse:
                        response = HTMLResponse(self.admin.forbidden_page(),
                                                status_code=403)
                        response.set_cookie('token', 'INVALID')
                        return response
                    raise HTTPException(
                        status_code=403,
                        detail=
                        f"not authorized, permissions required: {permissions}")

                if 'access_token' in kwargs:
                    kwargs['access_token'] = token

                if not send_token:
                    del kwargs['token']
                if not send_request:
                    del kwargs['request']

                result = func(*args, **kwargs)
                if asyncio.iscoroutine(result):
                    return await result
                return result