def gen_index_html(out, username, show_active=False): if not get_server_pid(username): out += "inactive or nonexistent.<br />" out += f"""<form action="{url_for('start')}" method="POST"> <input type="hidden" name="username" value="{username}" /> <input type="submit" value="Start IDE" /> </form>""" return html(out) config = get_config(username) if is_prod_build(): domain = f"{username}.{get_host()}" else: domain = f"{username}-{get_host()}" out += "active.<br />" out += f"""<form action="https://{domain}/login", method="POST"> <input type="hidden" name="base" value="" /><input type="hidden" name="password" value="{config['password']}" /> <input type="submit" value="Open IDE" /> </form><form action="{url_for('kill')}" method="POST"> <input type="hidden" name="username" value="{username}" /> <input type="submit" value="Kill IDE" /> </form>""" active = get_active_servers() if active and show_active: out += "<p>Active servers: " + ", ".join(active) + "</p>" return html(out)
def index(): username = get_username() out = "<h1>61A Sandbox IDE</h1>\n" out += f"Hi {get_user()['name'].split()[0]}! Your IDE is " if not get_server_pid(username): out += "inactive.<br />" out += f"""<form action="{url_for('start')}" method="POST"> <input type="hidden" name="username" value="{username}" /> <input type="submit" value="Start IDE" /> </form>""" return html(out) config = get_config(username) out += "active.<br />" out += f"""<form action="https://{username}.{get_host()}/login", method="POST" target="_blank"> <input type="hidden" name="base" value="" /><input type="hidden" name="password" value="{config['password']}" /> <input type="submit" value="Open in New Tab" /> </form><form action="{url_for('kill')}" method="POST"> <input type="hidden" name="username" value="{username}" /> <input type="submit" value="Kill IDE" /> </form>""" return html(out)
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))
def piazza_config(course): return html(f""" Enter account details for Piazza service accounts. Leave fields blank to avoid updating them. Ensure that these accounts are enrolled in the appropriate Piazzas! <form action="/piazza/{course}/set_config" method="post"> <label> Piazza course ID <br /> <input name="course_id" type="text"> <br /> </label> <label> Test Piazza course ID <br /> <input name="test_course_id" type="text"> <br /> </label> <br /> <label> Student Username <br /> <input name="student_user" type="text"> <br /> </label> <label> Student Password <br /> <input name="student_pw" type="password"> <br /> </label> <br /> <label> Staff Username <br /> <input name="staff_user" type="text"> <br /> </label> <label> Staff Password <br /> <input name="staff_pw" type="password"> <br /> </label> <label> <input type="submit"> </form> """)
def refresh(): with connect_db() as db: db("DELETE FROM shortlinks WHERE course=%s", [get_course()]) sheets = db( "SELECT url, sheet, secure FROM sources WHERE course=(%s)", [get_course()] ).fetchall() data = [] for url, sheet, secure in sheets: try: csvr = read_spreadsheet(url=url, sheet_name=sheet) except: return error(f"Failed to read spreadsheet {url} (Sheet: {sheet})") headers = [x.lower() for x in csvr[0]] for row in csvr[1:]: row = row + [""] * 5 shortlink = row[headers.index("shortlink")] url = row[headers.index("url")] creator = row[headers.index("creator")] data.append([shortlink, url, creator, secure, get_course()]) with connect_db() as db: db( "INSERT INTO shortlinks (shortlink, url, creator, secure, course) VALUES (%s, %s, %s, %s, %s)", data, ) return html("Links updated")
def index(): if not is_staff("cs61a"): return login() email = get_user()["email"] if not is_admin(course="cs61a", email=email): abort(401) with connect_db() as db: apps = db("SELECT app FROM services WHERE pr_number=0", []).fetchall() pr_apps = db( "SELECT app, pr_number FROM services WHERE pr_number>0 ORDER BY pr_number DESC", [], ).fetchall() return html( f""" This service manages the deployment of the 61A website and various apps. {"".join(f''' <form action="/deploy_prod_app"> <input type="submit" name="app" value="{app}" /> </form> ''' for [app] in apps)} {"".join(f''' <form action="/trigger_build"> <input type="hidden" name="app" value="{app}" /> <input type="hidden" name="pr_number" value="{pr_number}" /> <input type="submit" value="{app + "-pr" + str(pr_number)}" /> </form> ''' for [app, pr_number] in pr_apps)} <form action="/delete_unused_services" method="post"> <input type="submit" value="Delete unused services" /> </form> """ )
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>""")
def index(): out = [app.general_info.render()] with connect_db() as db: for course, endpoint in db( "SELECT course, endpoint FROM courses").fetchall(): if is_staff(course): out.append(app.help_info.render(course)) return html("".join(out))
def google_config(course): return html(f""" Upload Google service worker JSON. This may break existing Google integrations! <form action="/google/{course}/set_auth_json" method="post" enctype="multipart/form-data"> <input name="data" type="file"> <input type="submit"> </form> """)
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!")
def config(): auth_result = authenticate(app) if not (isinstance(auth_result, str) and auth_result == "Authorized!"): return auth_result with connect_db() as db: gscope: List[Tuple[str, str]] = db( "SELECT name, gs_code FROM gscope", [], ).fetchall() adjustments: List[Tuple[str, str, str]] = db( "SELECT hashed, url, sheet FROM adjustments", [], ).fetchall() return html( """ <h1>Grade Display Config</h1> <p> Add a Gradescope assignment: """ + make_row( """<input name="name" placeholder="Shortname (no spaces!)" /> <input name="gs_code" placeholder="Gradescope code" /> """, url_for("create_assign"), "Submit", ) + """ </p> <p> Add an adjustments sheet: """ + make_row( """<input name="url" placeholder="Full URL" /> <input name="sheet" placeholder="Sheet Name" /> """, url_for("add_adjustments"), "Submit", ) + """ </p> """ + "".join( "<p>" + make_row(f"{name} ({gs_code})", url_for("delete_assign", name=name)) for name, gs_code in gscope ) + "".join( "<p>" + make_row( f"Adjustments: {url} ({sheet})", url_for("delete_adjustments", hashed=hashed), ) for hashed, url, sheet in adjustments ) )
def load_formatted(name): out = load(name) if isinstance(out, str): return html(f"""<div style="margin-left: -50%; margin-right: -50%"> <h1>61A Paste</h1> <pre>{out}</pre> <a href=\"{url_for('load_raw', name=name)}\">(raw)</a> </div>""") else: return out
def load_formatted(name): out = load(name) if isinstance(out, str): return html(f"""<body style="max-width: calc(100% - 10em)"> <h1>61A Paste</h1> <pre>{escape(out)}</pre> <a href=\"{url_for('load_raw', name=name)}\">(raw)</a> </body>""") else: return out
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> """)
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>!")
def create_key(course): name = request.form["client_name"] key = gen_key() with connect_db() as db: ret = db("SELECT * FROM auth_keys WHERE client_name = (%s)", [name]).fetchone() if ret: return "client_name already in use", 409 ret = db("SELECT * FROM super_auth_keys WHERE client_name = (%s)", [name]).fetchone() if ret: return "client_name already in use", 409 db( "INSERT INTO auth_keys VALUES (%s, %s, %s, %s, %s, %s)", [name, key, get_name(), course, "all", True], ) return html(f"<pre>{key}</pre>")
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)} """)
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")} """ )
def revoke_all_unused_keys(course): with connect_db() as db: db("DELETE FROM auth_keys WHERE unused = TRUE and course = (%s)", [course]) return html("All unused keys revoked.")
def index(): auth_result = authenticate(app) if auth_result == "Authorized!": auth_result = html(auth_result) return auth_result
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Blueprint, render_template, session, redirect, request from datetime import datetime, timedelta import time from time import mktime from common.xparcer import BankParcer from common.html import html h = html() p = BankParcer() banks = Blueprint('banks', __name__) @banks.route("/bank", methods=['GET','POST']) def banks_page(): if 'username' not in session: return redirect('/login') if 'theme' not in session: session['theme']='a' if request.method == 'POST': if request.form['date']: date = request.form['date'] if 'prev' in request.form: if 'date' not in session: date = str(datetime.now().date() - timedelta(days = 1)) session['date'] = date else: d=datetime.fromtimestamp(mktime(time.strptime(session['date'],'%Y-%m-%d'))) d = d - timedelta(days = 1) date = d.strftime('%Y-%m-%d')
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Blueprint, render_template, session, redirect, request from datetime import datetime, timedelta import time from time import mktime from common.xparcer import MonitorParcer from common.html import html h = html() p = MonitorParcer() monitor = Blueprint('monitor', __name__) @monitor.route("/monitor", methods=['GET', 'POST']) def monitor_page(): date = str(datetime.now().date()) if 'username' not in session: return redirect('/login') if 'theme' not in session: session['theme'] = 'a' if request.method == 'POST': if request.form['date']: date = request.form['date'] if 'prev' in request.form: if 'date' not in session: date = str(datetime.now().date() - timedelta(days=1)) session['date'] = date else: d = datetime.fromtimestamp(