示例#1
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>
    """)
示例#2
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"""
示例#3
0
def set_acadh():
    if not is_staff("cs61a"):
        return redirect(url_for("config"))

    url = request.form["url"]
    sheet = request.form["sheet"]
    with connect_db() as db:
        db("DELETE FROM acadh")
        db(
            "INSERT INTO acadh (url, sheet) VALUES (%s, %s)",
            [url, sheet],
        )
    return redirect(url_for("config"))
示例#4
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")
示例#5
0
def add_adjustments():
    if not is_staff("cs61a"):
        return redirect(url_for("config"))

    url = request.form["url"]
    sheet = request.form["sheet"]
    hashed = hashlib.sha512(url.encode("utf-8") + sheet.encode("utf-8")).hexdigest()
    with connect_db() as db:
        db(
            "INSERT INTO adjustments (hashed, url, sheet) VALUES (%s, %s, %s)",
            [hashed, url, sheet],
        )
    return redirect(url_for("config"))
示例#6
0
 def set_config():
     if not is_staff(get_course()):
         return jsonify({"success": False})
     if not DEV and not can_user(
             course=get_course(),
             email=get_user()["email"],
             action="configure_howamidoing",
     ):
         return jsonify({"success": False})
     data = request.form.get("data")
     with connect_db() as db:
         db("DELETE FROM configs WHERE courseCode=%s", [get_course()])
         db("INSERT INTO configs VALUES (%s, %s)", [get_course(), data])
     return jsonify({"success": True})
示例#7
0
    def set_grades_route():
        if not is_staff(get_course()):
            return jsonify({"success": False})
        if not DEV and not can_user(
                course=get_course(),
                email=get_user()["email"],
                action="configure_howamidoing",
        ):
            return jsonify({"success": False})
        data = request.form.get("data")
        with transaction_db() as db:
            set_grades(data, get_course(), db)

        return jsonify({"success": True})
示例#8
0
 def all_scores():
     if not is_staff(get_course()):
         return jsonify({"success": False})
     with connect_db() as db:
         [header] = db("SELECT header FROM headers WHERE courseCode=%s",
                       [get_course()]).fetchone()
         header = json.loads(header)
         data = db("SELECT data FROM students WHERE courseCode=%s",
                   get_course()).fetchall()
         scores = []
         for [score] in data:
             score = json.loads(score)
             scores.append(score)
         return jsonify({"header": header, "scores": scores})
示例#9
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"))
示例#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()
示例#11
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"))
示例#12
0
def create_assign():
    if not is_staff("cs61a"):
        return redirect(url_for("config"))

    name = request.form["name"]
    gs_code = request.form["gs_code"]
    with connect_db() as db:
        existing = db("SELECT * FROM gscope WHERE name=%s", [name]).fetchall()
        if existing:
            abort(409)
        db(
            "INSERT INTO gscope (name, gs_code) VALUES (%s, %s)",
            [name, gs_code],
        )
    return redirect(url_for("config"))
示例#13
0
def authenticate(app):
    """Returns an OAuth token that can be passed to the server for
    identification. If FORCE is False, it will attempt to use a cached token
    or refresh the OAuth token. If NOINTERACT is true, it will return None
    rather than prompting the user.
    """
    try:
        access_token = refresh_local_token()
    except Exception:
        print("Performing authentication.")

    if not is_staff("cs61a"):
        return redirect(url_for("login"))

    return "Authorized!"
示例#14
0
def is_authorized(secure: AccessRestriction):
    """Returns authorization status based on the given access restriction.

    :param secure: access restriction
    :type secure: AccessRestriction
    :return: authorization status (``True`` or ``False``)
    """
    if secure == AccessRestriction.ALL:
        return True
    elif secure == AccessRestriction.STAFF:
        return is_staff(get_course())
    elif secure == AccessRestriction.STUDENT:
        return is_enrolled(get_course())
    else:
        raise Exception(f"{secure} is not a valid AccessRestriction")
示例#15
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"))
示例#16
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
示例#17
0
    def login():
        user_data = get_user()
        user = User.query.filter_by(email=user_data["email"]).one_or_none()
        if user is None:
            user = User(email=user_data["email"],
                        name=user_data["name"],
                        is_staff=False)
            db.session.add(user)
        user.name = user_data["name"] or user_data["email"]
        for participation in user_data["participations"]:
            if participation["course"]["offering"] == get_endpoint():
                break
        else:
            if getenv("ENV") == "prod":
                return

        user.is_staff = is_staff("cs61a" if dev else get_course())
        db.session.commit()
        login_user(user)
示例#18
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")}
    """
    )
示例#19
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)
示例#20
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
    )
示例#21
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>!")
示例#22
0
def create_secret(service):
    if not is_staff("cs61a"):
        return login()

    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>"
示例#23
0
def submit():
    if not is_staff("cs61a"):
        return login()
    data = request.form["data"]
    return redirect(url_for("load_formatted", name=paste_worker(data)))
示例#24
0
 def wrapped(*args, **kwargs):
     if not (is_staff("cs61a") and is_admin(email=get_user()["email"])):
         return login()
     return func(*args, **kwargs)
示例#25
0
def hot_reloader():
    if not is_staff("cs61a"):
        abort(403)

    return send_file(HOT_RELOAD_SCRIPT_PATH)
示例#26
0
def rebuild_path():
    if not is_staff("cs61a"):
        abort(403)
    path = request.json["path"]
    build(get_host_username(), path_to_target(path))
    return ""
示例#27
0
    def query():
        try:
            if is_logged_in():
                user = get_user()

                email = user["email"]
                target = request.args.get("target", None)
                admin = True if DEV else is_admin(course=get_course(),
                                                  email=email)

                if is_staff(get_course()):
                    if target:
                        email = target
                    else:
                        show_all_students = has_access_to_all_grades()
                        students = []
                        with connect_db() as db:
                            lookup = db(
                                "SELECT shortData FROM students WHERE courseCode=%s",
                                [get_course()],
                            ).fetchall()
                            for row in lookup:
                                parsed = json.loads(row[0])
                                if show_all_students or parsed.get("TA",
                                                                   "") in (
                                                                       "",
                                                                       email,
                                                                   ):
                                    students.append(parsed)
                        return jsonify({
                            "success": True,
                            "isStaff": True,
                            "isAdmin": admin,
                            "canExportGrades": show_all_students,
                            "allStudents": students,
                            "email": user["email"],
                            "name": user["name"],
                            "lastUpdated": last_updated(),
                        })

                with connect_db() as db:
                    [short_data, data] = db(
                        "SELECT shortData, data FROM students WHERE courseCode=%s AND email=%s",
                        [get_course(), email],
                    ).fetchone()
                    [header
                     ] = db("SELECT header FROM headers WHERE courseCode=%s",
                            [get_course()]).fetchone()
                    short_data = json.loads(short_data)
                    if not (email == user["email"] or admin or short_data.get(
                            "TA", "") in ("", user["email"])):
                        return jsonify({"success": False, "retry": False})
                    data = json.loads(data)
                    header = json.loads(header)
                    return jsonify({
                        "success": True,
                        "header": header,
                        "data": data,
                        "email": short_data["Email"],
                        "name": short_data["Name"],
                        "SID": short_data["SID"],
                        "ta": short_data.get("TA", ""),
                        "lastUpdated": last_updated(),
                    })
            else:
                return jsonify({"success": False, "retry": True})

        except Exception:
            pass
        return jsonify({"success": False, "retry": False})
示例#28
0
def delete_assign(name):
    if not is_staff("cs61a"):
        return redirect(url_for("config"))
    with connect_db() as db:
        db("DELETE FROM gscope WHERE name=%s", [name])
    return redirect(url_for("config"))
示例#29
0
 def wrapped(*args, **kwargs):
     if not is_staff("cs61a") or not is_berkeley():
         return login()
     return func(*args, **kwargs)
示例#30
0
def delete_adjustments(hashed):
    if not is_staff("cs61a"):
        return redirect(url_for("config"))
    with connect_db() as db:
        db("DELETE FROM adjustments WHERE hashed=%s", [hashed])
    return redirect(url_for("config"))