Exemplo n.º 1
0
def create_secret(service):
    if not is_staff("cs61a"):
        return login()
    email = get_user()["email"]
    if not is_admin(course="cs61a", email=email):
        abort(401)

    if service not in list_services():
        abort(404)

    out = reversed([
        entry["timestamp"] + " " + escape(entry["textPayload"])
        for entry in loads(
            sh(
                "gcloud",
                "logging",
                "read",
                f"projects/cs61a-140900/logs/run.googleapis.com AND resource.labels.service_name={service}",
                "--limit",
                "100",
                "--format",
                "json",
                capture_output=True,
            )) if "textPayload" in entry
    ])

    return "<pre>" + "\n".join(map(str, out)) + "</pre>"
Exemplo n.º 2
0
def load(name, skip_auth=False):
    out = None
    with connect_db() as db:
        data = db(
            "SELECT data FROM pastes WHERE name=%s AND private=FALSE",
            [name],
        ).fetchone()
        if data:
            out = data[0]
    if out is None:
        if not skip_auth and not is_staff("cs61a"):
            return login()
        with connect_db() as db:
            data = db(
                "SELECT data FROM pastes WHERE name=%s",
                [name],
            ).fetchone()
            if data:
                out = data[0]
    if out is None:
        abort(404)
    elif isinstance(out, bytes):
        return out.decode("utf-8")
    else:
        return out
Exemplo n.º 3
0
def index():
    if not is_logged_in():
        return login()
    return html("""
    Select course: 
    <form method="post" action="/view_course">
        <input placeholder="cs61a" name="course"> <input type="submit" value="Login">
    </form>""")
Exemplo n.º 4
0
def preview(path):
    url, creator, secure = lookup(path)
    if url is None:
        return html("No such link exists.")
    if not is_authorized(secure):
        return login()
    return html('Points to <a href="{0}">{0}</a> by {1}'.format(
        add_url_params(url, request.query_string.decode("utf-8")), creator))
Exemplo n.º 5
0
def index():
    if not is_staff("cs61a"):
        return login()

    service_list = "\n".join(
        f"<p /><a href={url_for('create_secret', service=service)}>{service}</a>"
        for service in list_services())

    return f"""
Exemplo n.º 6
0
def deploy_prod_app():
    if not is_staff("cs61a"):
        return login()
    email = get_user()["email"]
    if not is_admin(course="cs61a", email=email):
        abort(401)
    app = request.args["app"]
    deploy_prod_app_sync(target_app=app, noreply=True)
    return html(f"Deploying <code>{app}</code> from master!")
Exemplo n.º 7
0
def index():
    if not is_staff("cs61a"):
        return login()
    email = get_user()["email"]
    if not is_admin(course="cs61a", email=email):
        abort(401)

    service_list = "\n".join(
        f"<p /><a href={url_for('create_secret', service=service)}>{service}</a>"
        for service in list_services())

    return f"""
Exemplo n.º 8
0
def index():
    if not is_staff("cs61a"):
        return login()
    return html(f"""
    Paste text here: 
    <br/><p>
    <form action="{url_for("submit")}" method="POST">
    <textarea name="data" rows="30" cols="50" name="comment" ></textarea>
    </p>
    <input type="submit"></input>
    </form>
    """)
Exemplo n.º 9
0
def index(path):
    if ".pr." in get_host() and not is_staff("cs61a"):
        return login()

    bucket = get_bucket(
        {
            "cs61a": "website-base",
            "website": "website-base",
            "website-server": "website-base",
        },
        "website-base",
    )
    return serve_path(bucket, "/released/", path, path_404="404/index.html")
Exemplo n.º 10
0
 def wrapped(*args, access_token=None, course="cs61a", **kwargs):
     token_good = access_token and is_admin_token(access_token=access_token,
                                                  course=course)
     cookie_good = is_staff(course=course) and is_admin(
         email=get_user()["email"], course=course)
     if token_good or cookie_good:
         try:
             return func(*args, **kwargs, course=course)
         except PermissionError:
             pass
     if access_token:
         raise PermissionError
     else:
         return login()
Exemplo n.º 11
0
def remove_source():
    if not is_staff(get_course()):
        return login()

    url = request.form["url"]
    sheet = request.form["sheet"]

    with connect_db() as db:
        db(
            "DELETE FROM sources WHERE url=%s AND sheet=%s AND course=%s",
            [url, sheet, get_course()],
        )

    return redirect(url_for("index"))
Exemplo n.º 12
0
def add_source():
    if not is_staff(get_course()):
        return login()

    url = request.form["url"]
    sheet = request.form["sheet"]
    secure = True if request.form.get("secure", False) else False

    with connect_db() as db:
        db(
            "INSERT INTO sources VALUES (%s, %s, %s, %s)",
            [url, sheet, secure, get_course()],
        )

    return redirect(url_for("index"))
Exemplo n.º 13
0
def create_secret():
    if not is_staff("cs61a"):
        return login()
    app = request.form["app"]
    name = request.form["name"]
    public = request.form["public"]
    staging = request.form["staging"]
    with connect_db() as db:
        existing = db("SELECT * FROM secrets WHERE app=%s AND name=%s",
                      [app, name]).fetchall()
        if existing:
            abort(409)
        db(
            "INSERT INTO secrets (app, name, public_value, staging_value) VALUES (%s, %s, %s, %s)",
            [app, name, public, staging],
        )
    return redirect(url_for("index"))
Exemplo n.º 14
0
def index(path="index.html"):
    if not is_staff("cs61a"):
        return login()
    username = get_host_username()
    base_directory = get_working_directory(username)

    if "." not in path:
        return index(path + "/index.html")

    original_path = path
    target = path_to_target(path)
    path = safe_join(base_directory, "published", path)
    if not is_up_to_date(username, target):
        build(username, target)

    if path.endswith(".html") or path.endswith(".pdf"):
        logs = get_logs(username, target)
        if logs is not None:
            name, data = logs
            out = f"""
                <pre>{data}</pre>
                <a href={get_paste_url(name)}>{get_paste_url(name)}</a>
                """
        elif os.path.exists(path):
            if path.endswith(".pdf"):
                out = PDF_INLINE_SCRIPT.replace("SRC_PATH",
                                                "/raw/" + original_path)
            else:
                with open(path, "r") as f:
                    out = f.read()
        else:
            out = ""
        out += HOT_RELOAD_INLINE_SCRIPT.replace(
            "MANUAL_VERSION", str(get_manual_version(username))).replace(
                "VERSION",
                str(get_version(username, target)),
            )
        return out
    else:
        try:
            return send_file(path, cache_timeout=-1)
        except FileNotFoundError:
            return "", 404
Exemplo n.º 15
0
def view_course(course=None):
    if not course:
        course = request.form["course"]
        return redirect(url_for("canonical_view_course", course=course))
    if not is_logged_in():
        return login()
    email = get_user()["email"]
    if not is_admin(email, course):
        abort(403)

    with connect_db() as db:
        apps = db(
            "SELECT domain, app, status FROM hosted_apps WHERE course=(%s)",
            [course]).fetchall()

    return html(f"""
        <h2>Hosted Apps for {format_coursecode(course)}</h2>
        {"<p>".join(f"<code>{domain}</code> ({app}) - {status}" for domain, app, status in apps)}
    """)
Exemplo n.º 16
0
def index():
    if not is_staff(get_course()):
        return login()
    with connect_db() as db:
        sources = db(
            "SELECT url, sheet, secure FROM sources WHERE course=%s", [get_course()]
        ).fetchall()

    insert_fields = """<input placeholder="Spreadsheet URL" name="url"></input>
        <input placeholder="Sheet Name" name="sheet"></input>
        <label>
            <input type="checkbox" name="secure"></input>
            Require Authentication
        </label>"""

    sources = "<br/>".join(
        make_row(
            f'<a href="{url}">{url}</a> {sheet} (Secure: {secure})'
            f'<input name="url" type="hidden" value="{url}"></input>'
            f'<input name="sheet" type="hidden" value="{sheet}"></input>',
            url_for("remove_source"),
        )
        for url, sheet, secure in sources
    )

    return html(
        f"""
    <h2>Course: <code>{get_course()}</code></h2>
    Each spreadsheet should be shared with the 61A service account
    <a href="mailto:[email protected]">
        [email protected]</a>.
    They should have three columns with the headers: "URL", "Shortlink", and "Creator".
    <p>
    Visit <a href="{url_for("refresh")}">{url_for("refresh")}</a> (no auth required) 
    after adding a link to synchronize with the spreadsheets.

    <h3>Sources</h3>
    {sources}
    <h3>Add Sources</h3>
    {make_row(insert_fields, url_for("add_source"), "Add")}
    """
    )
Exemplo n.º 17
0
def index(path):
    try:
        info = get_user()
        for p in info["participations"]:
            if p["course"]["offering"] == get_endpoint(
                    "cs61a") and p["role"] == "student":
                return redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
    except:
        pass  # don't let the rickroll crash anything else

    if not is_staff("cs61a"):
        return login()
    bucket = get_bucket(
        {
            "cs61a": "website-base",
            "solutions2": "website-base",
            "solutions": "website-base",
        },
        "website-base",
    )
    return serve_path(bucket, "/unreleased/", path)
Exemplo n.º 18
0
def index():
    if not is_staff("cs61a"):
        return login()
    with connect_db() as db:
        secrets: List[Tuple[str, str, str, str]] = db(
            "SELECT app, name, public_value, staging_value FROM secrets"
        ).fetchall()
    return """
    <h1>Secrets Tool</h1>
    <p>
        Add a secret: 
        <form action="/create_secret" method="POST">
            <input name="app" placeholder="App name" /> 
            <input name="name" placeholder="Secret name" /> 
            <input name="public" placeholder="Public value" /> 
            <input name="staging" placeholder="Staging value" />
            <button type="submit">Submit</button>
        </form>
    </p>
    <p>
        You should assume that the staging value is visible to any member of 61A staff.
        For instance, for Auth keys, provide a 61A-specific key for the staging value,
        and a super key only for the public value, to avoid leaking information. That said,
        staging values are not directly exposed and access will be logged in deploy logs,
        so don't worry about it too much, just be careful.
    </p>
    """ + "".join(
        f"""<p>
            <form 
                style="display: inline" 
                action="{url_for("delete_secret", app_name=app, secret_name=name)}" 
                method="post"
            >
                {app}/{name} - {display_hash(public_value)} (staging: {display_hash(staging_value)})
                <input type="submit" value="Remove">
        </form>"""
        for app, name, public_value, staging_value in secrets
    )
Exemplo n.º 19
0
def trigger_build():
    if not is_staff("cs61a"):
        return login()
    email = get_user()["email"]
    if not is_admin(course="cs61a", email=email):
        abort(401)
    if "app" in request.args:
        target = request.args["app"]
    else:
        target = None

    pr_number = int(request.args["pr_number"])

    g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
    repo = g.get_repo(GITHUB_REPO)
    pr = repo.get_pull(pr_number)

    if DO_NOT_BUILD in [l.name for l in pr.labels]:
        return html(
            f"PR <code>{pr_number}</code> has a DO NOT BUILD label on it, so it cannot be built. Remove this label to build the PR."
        )

    trigger_build_sync(pr_number=pr_number, target_app=target, noreply=True)
    return html(f"Building PR <code>{pr_number}</code>!")
Exemplo n.º 20
0
 def wrapped(*args, **kwargs):
     if not is_staff("cs61a") or not is_berkeley():
         return login()
     return func(*args, **kwargs)
Exemplo n.º 21
0
def submit():
    if not is_staff("cs61a"):
        return login()
    data = request.form["data"]
    return redirect(url_for("load_formatted", name=paste_worker(data)))
Exemplo n.º 22
0
 def wrapped(*args, **kwargs):
     if not (is_staff("cs61a") and is_admin(email=get_user()["email"])):
         return login()
     return func(*args, **kwargs)
Exemplo n.º 23
0
def delete_secret(app_name, secret_name):
    if not is_admin(get_user()["email"], "cs61a"):
        return login()
    with connect_db() as db:
        db("DELETE FROM secrets WHERE app=%s AND name=%s", [app_name, secret_name])
    return redirect(url_for("index"))
Exemplo n.º 24
0
 def wrapped(*args, **kwargs):
     if not list(get_staff_endpoints()):
         return login()
     return route(*args, **kwargs)