Exemplo n.º 1
0
def utility_processor():
    """
    This defines the set of properties and functions that will be added
    to the default context for processing templates. All these items
    can be used in all templates
    """

    if authentication.is_authenticated(flask.session):
        user_name = flask.session['openid']['fullname']
    else:
        user_name = None

    return {
        # Variables
        'LOGIN_URL': LOGIN_URL,
        'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN,
        'COMMIT_ID': COMMIT_ID,
        'ENVIRONMENT': ENVIRONMENT,
        'path': flask.request.path,
        'user_name': user_name,

        # Functions
        'contains': template_functions.contains,
        'join': template_functions.join,
        'static_url': template_functions.static_url,
        'format_number': template_functions.format_number,
    }
Exemplo n.º 2
0
def login_handler():
    if authentication.is_authenticated(flask.session):
        return flask.redirect(open_id.get_next_url())

    try:
        root = authentication.request_macaroon()
    except ApiResponseError as api_response_error:
        if api_response_error.status_code == 401:
            return flask.redirect(flask.url_for(".logout"))
        else:
            return flask.abort(502, str(api_response_error))
    except ApiError as api_error:
        return flask.abort(502, str(api_error))

    openid_macaroon = MacaroonRequest(
        caveat_id=authentication.get_caveat_id(root))
    flask.session["macaroon_root"] = root

    lp_teams = TeamsRequest(query_membership=[LP_CANONICAL_TEAM])

    return open_id.try_login(
        LOGIN_URL,
        ask_for=["email", "nickname", "image"],
        ask_for_optional=["fullname"],
        extensions=[openid_macaroon, lp_teams],
    )
Exemplo n.º 3
0
    def utility_processor():
        """
        This defines the set of properties and functions that will be added
        to the default context for processing templates. All these items
        can be used in all templates
        """

        if authentication.is_authenticated(flask.session):
            user_name = flask.session["openid"]["fullname"]
        else:
            user_name = None

        page_slug = template_utils.generate_slug(flask.request.path)

        return {
            # Variables
            "LOGIN_URL": app.config["LOGIN_URL"],
            "SENTRY_PUBLIC_DSN": app.config["SENTRY_PUBLIC_DSN"],
            "COMMIT_ID": app.config["COMMIT_ID"],
            "ENVIRONMENT": app.config["ENVIRONMENT"],
            "path": flask.request.path,
            "page_slug": page_slug,
            "user_name": user_name,
            "VERIFIED_PUBLISHER": "verified",
            "webapp_config": app.config["WEBAPP_CONFIG"],
            "BSI_URL": app.config["BSI_URL"],
            # Functions
            "contains": template_utils.contains,
            "join": template_utils.join,
            "static_url": template_utils.static_url,
            "format_number": template_utils.format_number,
            "display_name": template_utils.display_name,
        }
Exemplo n.º 4
0
    def utility_processor():
        """
        This defines the set of properties and functions that will be added
        to the default context for processing templates. All these items
        can be used in all templates
        """

        if authentication.is_authenticated(flask.session):
            user_name = flask.session["openid"]["fullname"]
        else:
            user_name = None

        page_slug = template_utils.generate_slug(flask.request.path)

        return {
            # Variables
            "LOGIN_URL": app.config["LOGIN_URL"],
            "SENTRY_PUBLIC_DSN": app.config["SENTRY_PUBLIC_DSN"],
            "COMMIT_ID": app.config["COMMIT_ID"],
            "ENVIRONMENT": app.config["ENVIRONMENT"],
            "path": flask.request.path,
            "page_slug": page_slug,
            "user_name": user_name,
            "VERIFIED_PUBLISHER": "verified",
            "webapp_config": app.config["WEBAPP_CONFIG"],
            "BSI_URL": app.config["BSI_URL"],
            # Functions
            "contains": template_utils.contains,
            "join": template_utils.join,
            "static_url": template_utils.static_url,
            "format_number": template_utils.format_number,
            "display_name": template_utils.display_name,
        }
Exemplo n.º 5
0
    def snap_details_badge_trending(snap_name):
        is_preview = flask.request.args.get("preview", default=0, type=int)
        context = _get_context_snap_details(snap_name)

        # default to empty SVG
        svg = ('<svg height="20" width="1" xmlns="http://www.w3.org/2000/svg" '
               'xmlns:xlink="http://www.w3.org/1999/xlink"></svg>')

        # publishers can see preview of trending badge of their own snaps
        # on Publicise page
        show_as_preview = False
        if is_preview and authentication.is_authenticated(flask.session):
            if (flask.session.get("openid").get("nickname")
                    == context["username"]
                ) or ("user_shared_snaps" in flask.session
                      and snap_name in flask.session.get("user_shared_snaps")):
                show_as_preview = True

        if context["trending"] or show_as_preview:
            svg = get_badge_svg(
                snap_name=snap_name,
                left_text=context["snap_title"],
                right_text="Trending this week",
                color="#FA7041",
            )

        return svg, 200, {"Content-Type": "image/svg+xml"}
Exemplo n.º 6
0
def login_candid():
    if authentication.is_authenticated(flask.session):
        return flask.redirect(
            flask.url_for("publisher_snaps.get_account_snaps"))

    # Get a bakery v2 macaroon from the publisher API to be discharged
    # and save it in the session
    flask.session["publisher-macaroon"] = publisher_api.get_macaroon(
        authentication.PERMISSIONS)

    login_url = candid.get_login_url(
        macaroon=flask.session["publisher-macaroon"],
        callback_url=flask.url_for("login.login_callback", _external=True),
        state=generate_csrf(),
    )

    # Next URL to redirect the user after the login
    next_url = flask.request.args.get("next")

    if next_url:
        if not next_url.startswith("/") and not next_url.startswith(
                flask.request.url_root):
            return flask.abort(400)
        flask.session["next_url"] = next_url

    return flask.redirect(login_url, 302)
Exemplo n.º 7
0
    def utility_processor():
        """
        This defines the set of properties and functions that will be added
        to the default context for processing templates. All these items
        can be used in all templates
        """

        if authentication.is_authenticated(flask.session):
            user_name = flask.session['openid']['fullname']
        else:
            user_name = None

        page_slug = template_utils.generate_slug(flask.request.path)

        return {
            # Variables
            'LOGIN_URL': app.config['LOGIN_URL'],
            'SENTRY_PUBLIC_DSN': app.config['SENTRY_PUBLIC_DSN'],
            'COMMIT_ID': app.config['COMMIT_ID'],
            'ENVIRONMENT': app.config['ENVIRONMENT'],
            'path': flask.request.path,
            'page_slug': page_slug,
            'user_name': user_name,
            'VERIFIED_PUBLISHER': 'verified',
            'webapp_config': app.config['WEBAPP_CONFIG'],
            'BSI_URL': app.config['BSI_URL'],

            # Functions
            'contains': template_utils.contains,
            'join': template_utils.join,
            'static_url': template_utils.static_url,
            'format_number': template_utils.format_number,
        }
Exemplo n.º 8
0
def login_handler():
    if authentication.is_authenticated(flask.session):
        return flask.redirect(open_id.get_next_url())

    try:
        root = authentication.request_macaroon()
    except ApiResponseError as api_response_error:
        if api_response_error.status_code == 401:
            return flask.redirect(flask.url_for(".logout"))
        else:
            return flask.abort(502, str(api_response_error))
    except ApiCircuitBreaker:
        flask.abort(503)
    except ApiError as api_error:
        return flask.abort(502, str(api_error))

    openid_macaroon = MacaroonRequest(
        caveat_id=authentication.get_caveat_id(root)
    )
    flask.session["macaroon_root"] = root

    return open_id.try_login(
        LOGIN_URL,
        ask_for=["email", "nickname", "image"],
        ask_for_optional=["fullname"],
        extensions=[openid_macaroon],
    )
Exemplo n.º 9
0
    def is_user_logged_in(*args, **kwargs):
        last_login_method = flask.request.cookies.get("last_login_method")
        login_path = "login-beta" if last_login_method == "candid" else "login"

        if not authentication.is_authenticated(flask.session):
            return flask.redirect(f"/{login_path}?next={flask.request.path}")

        return func(*args, **kwargs)
Exemplo n.º 10
0
def logout():
    no_redirect = flask.request.args.get("no_redirect", default="false")

    if authentication.is_authenticated(flask.session):
        authentication.empty_session(flask.session)

    if no_redirect == "true":
        return flask.redirect("/")
    else:
        return flask.redirect(BSI_URL + "/auth/logout")
Exemplo n.º 11
0
def logout():
    no_redirect = flask.request.args.get("no_redirect", default="false")

    if authentication.is_authenticated(flask.session):
        authentication.empty_session(flask.session)

    if no_redirect == "true":
        return flask.redirect("/")
    else:
        return flask.redirect(BSI_URL + "/auth/logout")
Exemplo n.º 12
0
def logout():
    no_redirect = flask.request.args.get('no_redirect', default="false")

    if authentication.is_authenticated(flask.session):
        authentication.empty_session(flask.session)

    if no_redirect == 'true':
        return flask.redirect('/')
    else:
        return flask.redirect(BSI_URL + '/auth/logout')
Exemplo n.º 13
0
    def utility_processor():
        """
        This defines the set of properties and functions that will be added
        to the default context for processing templates. All these items
        can be used in all templates
        """

        if authentication.is_authenticated(flask.session):
            user_name = flask.session["publisher"]["fullname"]
            user_is_canonical = flask.session["publisher"].get(
                "is_canonical", False
            )
            stores = flask.session["publisher"].get("stores")
        else:
            user_name = None
            user_is_canonical = False
            stores = []

        page_slug = template_utils.generate_slug(flask.request.path)

        is_brand_store = False

        if "STORE_QUERY" in app.config["WEBAPP_CONFIG"]:
            is_brand_store = True

        return {
            # Variables
            "LOGIN_URL": app.config["LOGIN_URL"],
            "SENTRY_DSN": app.config["SENTRY_DSN"],
            "COMMIT_ID": app.config["COMMIT_ID"],
            "ENVIRONMENT": app.config["ENVIRONMENT"],
            "host_url": flask.request.host_url,
            "path": flask.request.path,
            "page_slug": page_slug,
            "user_name": user_name,
            "VERIFIED_PUBLISHER": "verified",
            "webapp_config": app.config["WEBAPP_CONFIG"],
            "BSI_URL": app.config["BSI_URL"],
            "IS_BRAND_STORE": is_brand_store,
            "now": datetime.now(),
            "user_is_canonical": user_is_canonical,
            # Functions
            "contains": template_utils.contains,
            "join": template_utils.join,
            "static_url": template_utils.static_url,
            "format_number": template_utils.format_number,
            "display_name": template_utils.display_name,
            "install_snippet": template_utils.install_snippet,
            "format_date": template_utils.format_date,
            "format_member_role": template_utils.format_member_role,
            "image": image_template,
            "stores": stores,
        }
Exemplo n.º 14
0
def logout():
    no_redirect = flask.request.args.get("no_redirect", default="false")

    if authentication.is_authenticated(flask.session):
        authentication.empty_session(flask.session)

    if no_redirect == "true":
        return flask.redirect("/")
    else:
        redirect_url = quote(flask.request.url_root, safe="")
        return flask.redirect(
            f"{LOGIN_URL}/+logout?return_to={redirect_url}&return_now=True")
Exemplo n.º 15
0
def login_handler():
    if authentication.is_authenticated(flask.session):
        return flask.redirect(open_id.get_next_url())

    root = authentication.request_macaroon()
    openid_macaroon = MacaroonRequest(
        caveat_id=authentication.get_caveat_id(root))
    flask.session['macaroon_root'] = root

    return open_id.try_login(LOGIN_URL,
                             ask_for=['email', 'nickname', 'image'],
                             ask_for_optional=['fullname'],
                             extensions=[openid_macaroon])
Exemplo n.º 16
0
    def utility_processor():
        """
        This defines the set of properties and functions that will be added
        to the default context for processing templates. All these items
        can be used in all templates
        """

        if authentication.is_authenticated(session):
            publisher = session["publisher"]
        else:
            publisher = None

        return {
            "add_filter": helpers.add_filter,
            "active_filter": helpers.active_filter,
            "remove_filter": helpers.remove_filter,
            "publisher": publisher,
            "image": image_template,
        }
Exemplo n.º 17
0
    def is_user_logged_in(*args, **kwargs):
        if not authentication.is_authenticated(flask.session):
            return flask.redirect("login?next=" + flask.request.path)

        return func(*args, **kwargs)
Exemplo n.º 18
0
    def _get_context_snap_details(snap_name):
        try:
            details = api.get_item_details(snap_name, api_version=2)
        except StoreApiTimeoutError as api_timeout_error:
            flask.abort(504, str(api_timeout_error))
        except StoreApiResponseDecodeError as api_response_decode_error:
            flask.abort(502, str(api_response_decode_error))
        except StoreApiResponseErrorList as api_response_error_list:
            if api_response_error_list.status_code == 404:
                flask.abort(404, "No snap named {}".format(snap_name))
            else:
                if api_response_error_list.errors:
                    error_messages = ", ".join(
                        api_response_error_list.errors.key())
                else:
                    error_messages = "An error occurred."
                flask.abort(502, error_messages)
        except StoreApiResponseError as api_response_error:
            flask.abort(502, str(api_response_error))
        except StoreApiCircuitBreaker:
            flask.abort(503)
        except (StoreApiError, ApiError) as api_error:
            flask.abort(502, str(api_error))

        # When removing all the channel maps of an existing snap the API,
        # responds that the snaps still exists with data.
        # Return a 404 if not channel maps, to avoid having a error.
        # For example: mir-kiosk-browser
        if not details.get("channel-map"):
            flask.abort(404, "No snap named {}".format(snap_name))

        clean_description = bleach.clean(details["snap"]["description"],
                                         tags=[])
        formatted_description = parse_markdown_description(clean_description)

        channel_maps_list = logic.convert_channel_maps(
            details.get("channel-map"))

        latest_channel = logic.get_last_updated_version(
            details.get("channel-map"))

        last_updated = latest_channel["created-at"]
        last_version = latest_channel["version"]
        binary_filesize = latest_channel["download"]["size"]

        # filter out banner and banner-icon images from screenshots
        screenshots = logic.filter_screenshots(details["snap"]["media"])

        icons = logic.get_icon(details["snap"]["media"])

        publisher_info = helpers.get_yaml(
            "{}{}.yaml".format(
                flask.current_app.config["CONTENT_DIRECTORY"]
                ["PUBLISHER_PAGES"],
                details["snap"]["publisher"]["username"],
            ),
            typ="safe",
        )

        publisher_snaps = helpers.get_yaml(
            "{}{}-snaps.yaml".format(
                flask.current_app.config["CONTENT_DIRECTORY"]
                ["PUBLISHER_PAGES"],
                details["snap"]["publisher"]["username"],
            ),
            typ="safe",
        )

        publisher_featured_snaps = None

        if publisher_info:
            publisher_featured_snaps = publisher_info.get("featured_snaps")
            publisher_snaps = logic.get_n_random_snaps(
                publisher_snaps["snaps"], 4)

        videos = logic.get_videos(details["snap"]["media"])

        # until default tracks are supported by the API we special case node
        # to use 10, rather then latest
        default_track = helpers.get_default_track(details["name"])
        if not default_track:
            default_track = (details.get("default-track")
                             if details.get("default-track") else "latest")

        lowest_risk_available = logic.get_lowest_available_risk(
            channel_maps_list, default_track)

        confinement = logic.get_confinement(channel_maps_list, default_track,
                                            lowest_risk_available)

        last_version = logic.get_version(channel_maps_list, default_track,
                                         lowest_risk_available)

        is_users_snap = False
        if authentication.is_authenticated(flask.session):
            if (flask.session.get("openid").get("nickname")
                    == details["snap"]["publisher"]["username"]
                ) or ("user_shared_snaps" in flask.session
                      and snap_name in flask.session.get("user_shared_snaps")):
                is_users_snap = True

        # build list of categories of a snap
        categories = logic.get_snap_categories(details["snap"]["categories"])

        developer = logic.get_snap_developer(details["name"])

        context = {
            "snap-id": details.get("snap-id"),
            # Data direct from details API
            "snap_title": details["snap"]["title"],
            "package_name": details["name"],
            "categories": categories,
            "icon_url": icons[0] if icons else None,
            "version": last_version,
            "license": details["snap"]["license"],
            "publisher": details["snap"]["publisher"]["display-name"],
            "username": details["snap"]["publisher"]["username"],
            "screenshots": screenshots,
            "videos": videos,
            "publisher_snaps": publisher_snaps,
            "publisher_featured_snaps": publisher_featured_snaps,
            "has_publisher_page": publisher_info is not None,
            "prices": details["snap"]["prices"],
            "contact": details["snap"].get("contact"),
            "website": details["snap"].get("website"),
            "summary": details["snap"]["summary"],
            "description": formatted_description,
            "channel_map": channel_maps_list,
            "has_stable": logic.has_stable(channel_maps_list),
            "developer_validation": details["snap"]["publisher"]["validation"],
            "default_track": default_track,
            "lowest_risk_available": lowest_risk_available,
            "confinement": confinement,
            "trending": details["snap"]["trending"],
            # Transformed API data
            "filesize": humanize.naturalsize(binary_filesize),
            "last_updated": logic.convert_date(last_updated),
            "last_updated_raw": last_updated,
            "is_users_snap": is_users_snap,
            "unlisted": details["snap"]["unlisted"],
            "developer": developer,
            # TODO: This is horrible and hacky
            "appliances": {
                "adguard-home": "adguard",
                "mosquitto": "mosquitto",
                "nextcloud": "nextcloud",
                "plexmediaserver": "plex",
                "openhab": "openhab",
            },
        }

        return context
Exemplo n.º 19
0
def logout():
    if authentication.is_authenticated(flask.session):
        authentication.empty_session(flask.session)
    return flask.redirect('/')
Exemplo n.º 20
0
    def is_user_logged_in(*args, **kwargs):
        if not authentication.is_authenticated(flask.session):
            return flask.redirect("/login?next=" + flask.request.path)

        return func(*args, **kwargs)