Esempio n. 1
0
def create_login_client(app: flask.Flask):
    login_manager = LoginManager()
    login_manager.init_app(app)

    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)

    create_oauth_client(app, "sections", success_callback=login)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route("/oauth/logout")
    def logout():
        logout_user()
        return redirect(url_for("index"))
Esempio n. 2
0
@only("logs")
def container_log(name):
    return dict(success=True, logs=dna.docker_logs(name))


def check_auth(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        if not (is_staff("cs61a") and is_admin(email=get_user()["email"])):
            return login()
        return func(*args, **kwargs)

    return wrapped


create_oauth_client(app, "hosted-apps")

dna_api = dna.create_api_client(precheck=check_auth)
app.register_blueprint(dna_api, url_prefix="/dna")

dna_logs = dna.create_logs_client(precheck=check_auth)
app.register_blueprint(dna_logs, url_prefix="/logs")

# PR Proxy Setup
from dna.utils import Certbot
from dna.utils.nginx_utils import Server, Location
from common.rpc.hosted import create_pr_subdomain

proxy_cb = Certbot(CERTBOT_ARGS + ["-i", "nginx"])
pr_confs = f"{os.getcwd()}/data/pr_proxy"
Esempio n. 3
0
class Status(Enum):
    VALIDATING = "VALIDATING"
    DNS_INVALID = "DNS_INVALID"
    PROVISIONING = "PROVISIONING"
    PROVISIONING_FAILED = "PROVISIONING_FAILED"
    UPDATING_OAUTH = "UPDATING_OAUTH"
    INTERNAL_ERROR = "INTERNAL_ERROR"
    SUCCESS = "SUCCESS"


app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
    app.debug = True

create_oauth_client(app, "61a-domains")

with connect_db() as db:
    db("""CREATE TABLE IF NOT EXISTS hosted_apps (
    domain VARCHAR(128),
    course VARCHAR(128),
    app VARCHAR(128),
    status VARCHAR(128)
)
""")


@app.route("/")
def index():
    if not is_logged_in():
        return login()
Esempio n. 4
0
from flask import Flask
from common.oauth_client import create_oauth_client

from models import create_models, db
from admin import create_admin_endpoints
from okpy import create_okpy_endpoints
from worker import create_worker_endpoints
from superadmin import create_superadmin_endpoints

app = Flask(__name__)
if __name__ == "__main__":
    app.debug = True

create_oauth_client(app, "61a-autograder")

create_models(app)

create_admin_endpoints(app)
create_okpy_endpoints(app)
create_worker_endpoints(app)
create_superadmin_endpoints(app)


@app.before_first_request
def init_db():
    db.init_app(app)
    db.create_all(app=app)


@app.route("/")
def index():
Esempio n. 5
0
from common.oauth_client import (
    create_oauth_client,
    get_user,
    is_enrolled,
    login,
)

VALID_ORIGINS = r"https://.*cs61a\.org"

app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
    app.debug = True

CORS(app, origins=VALID_ORIGINS, supports_credentials=True)

create_oauth_client(app, "61a-discussions")
"""
This is normally risky! It is safe here because 
    (a) CORS prevents an attacker from reading reply data, even if their request is authenticated
    (b) The endpoints require a Content-Type of application/json, so browsers will send a pre-flight
        meaning that they will not even send POSTs unless they pass the CORS check, which they don't

To ensure safety, we must ensure that 
    (a) GET requests have no side-effects
    (b) POST requests must have the JSON Content-Type, so a malicious site cannot send requests on
        behalf of a user that can cause issues.
    (c) The CORS policy only allows *.cs61a.org to send POSTs with credentials
"""


@app.after_request
Esempio n. 6
0
from common.oauth_client import create_oauth_client, is_staff, login
from common.url_for import get_host

app = Flask(__name__)
if __name__ == "__main__":
    app.debug = True


@app.route("/", defaults={"path": ""})
@app.route("/<path:path>", methods=["GET"])
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")


Compress(app)
create_oauth_client(app, "cs61a-staging")

if __name__ == "__main__":
    app.run(debug=True)
Esempio n. 7
0
app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
    app.debug = True

with connect_db() as db:
    db("""CREATE TABLE IF NOT EXISTS secrets (
    app varchar(128),
    name varchar(128),
    public_value varchar(512),
    staging_value varchar(512)
)""")
    secret_key = db(
        "SELECT public_value FROM secrets WHERE app='secrets' and name='OKPY_OAUTH_SECRET'"
    ).fetchone()

create_oauth_client(app, "61a-secrets",
                    secret_key[0] if secret_key is not None else "")


@validate_master_secret.bind(app)
def validate_master_secret(master_secret):
    with connect_db() as db:
        public_app = db(
            "SELECT app FROM secrets WHERE public_value=%s AND name='MASTER'",
            [master_secret],
        ).fetchone()
        if public_app is not None:
            return public_app[0], False
        staging_app = db(
            "SELECT app FROM secrets WHERE staging_value=%s AND name='MASTER'",
            [master_secret],
        ).fetchone()
Esempio n. 8
0

def print_to_stderr(print_function):
    """Writes to sys.stderr using the desired print function.

    :param print_function: a print function

    :return: a function that writes the input to sys.stderr using the desired print function
    """
    def print(*s):
        print_function(*s, file=sys.stderr)

    return print


print = print_to_stderr(print)

app = Flask(__name__,
            static_url_path="",
            static_folder="static",
            template_folder="static")

if __name__ == "__main__":
    app.debug = True

create_client(app)
create_oauth_client(app, CONSUMER_KEY)

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000, debug=True)
Esempio n. 9
0
        frameborder="0" 
        scrolling="no"
    >
    </iframe>
</div>
"""

HOT_RELOAD_INLINE_SCRIPT = """
<script>
    const version=VERSION; 
    const manualVersion=MANUAL_VERSION;
</script>
<script src="/hot_reloader.js"></script>
"""

create_oauth_client(app, "61a-sandbox")

with connect_db() as db:
    db("""CREATE TABLE IF NOT EXISTS sandboxes (
    username varchar(128),
    initialized boolean,
    locked boolean,
    version integer, -- updated every time we sync a file
    manual_version integer -- updated after every manual make command
);""")

    db("""CREATE TABLE IF NOT EXISTS builds (
        username varchar(128),
        target varchar(256),
        pending boolean
    );""")
Esempio n. 10
0
from flask import Flask, abort, request, redirect
from typing import List, Tuple

from common.oauth_client import create_oauth_client, is_staff
from common.jobs import job
from common.db import connect_db
from common.url_for import url_for
from common.html import html, make_row

from auth import authenticate, update_storage
from datetime import datetime

from update_job import update

app = Flask(__name__)
create_oauth_client(app, "grade-display-exports", return_response=update_storage)

with connect_db() as db:
    db(
        """CREATE TABLE IF NOT EXISTS gscope (
    name varchar(128),
    gs_code varchar(128)
)"""
    )
    db(
        """CREATE TABLE IF NOT EXISTS adjustments (
    hashed text,
    url text,
    sheet text
)"""
    )
Esempio n. 11
0
from flask import Flask

from admins_client import create_admins_client
from auth_client import create_auth_client
from common.oauth_client import create_oauth_client
from domains_client import create_domains_client
from google_client import create_google_client
from management_client import create_management_client
from piazza_client import create_piazza_client
from ed_client import create_ed_client
from slack_client import create_slack_client

app = Flask(__name__)

if __name__ == "__main__":
    app.debug = True

create_oauth_client(app, "61a-account-auth")
create_management_client(app)
create_auth_client(app)
create_admins_client(app)
create_google_client(app)
create_piazza_client(app)
create_ed_client(app)
create_slack_client(app)
create_domains_client(app)


if __name__ == "__main__":
    app.run(debug=True)
Esempio n. 12
0
from flask import Flask

from api_client import create_api_client
from common.oauth_client import create_oauth_client
from config_client import create_config_client
from slack_client import create_slack_client

app = Flask(__name__)

if __name__ == "__main__":
    app.debug = True

create_config_client(app)
create_slack_client(app)
create_oauth_client(app, "eecs-slackbot")
create_api_client(app)

if __name__ == "__main__":
    app.run(debug=True)
Esempio n. 13
0
)
from common.rpc.hosted import add_domain
from common.rpc.secrets import get_secret
from common.shell_utils import sh
from common.html import html
from common.url_for import get_host, url_for
from common.db import connect_db

NGINX_PORT = os.environ.get("PORT", "8001")
DEFAULT_USER = "******"
SK_RETURN_TO = "start_kill_return_to"

app = Flask(__name__)

create_oauth_client(app,
                    "61a-ide",
                    secret_key=get_secret(secret_name="OKPY_IDE_SECRET"))

with connect_db() as db:
    db("""CREATE TABLE IF NOT EXISTS ide (
    username varchar(128),
    initialized boolean, -- this is unused in the ide context, for now
    locked boolean
);""")

VSCODE_ASSOC = """
{
    "files.associations": {
        "BUILD": "python",
        "WORKSPACE": "python"
    },
Esempio n. 14
0
from string import ascii_lowercase

from flask import Flask, Response, abort, redirect, request, escape

from common.db import connect_db
from common.html import html
from common.oauth_client import create_oauth_client, is_staff, login
from common.rpc.paste import get_paste, paste_text
from common.rpc.secrets import validates_master_secret
from common.url_for import url_for

app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
    app.debug = True

create_oauth_client(app, "61a-paste")

with connect_db() as db:
    db("""CREATE TABLE IF NOT EXISTS pastes (
    name varchar(128),
    data LONGBLOB,
    private boolean
);""")


@app.route("/")
def index():
    if not is_staff("cs61a"):
        return login()
    return html(f"""
    Paste text here: 
Esempio n. 15
0
    )


def add_url_params(url, params_string):
    parse_result = list(urlparse.urlsplit(url))
    parse_result[3] = "&".join(filter(lambda s: s, [parse_result[3], params_string]))
    return urlparse.urlunsplit(tuple(parse_result))


app = Flask(__name__)
app.url_map.strict_slashes = False

if __name__ == "__main__":
    app.debug = True

create_oauth_client(app, "61a-shortlinks")


def lookup(path):
    with connect_db() as db:
        target = db(
            "SELECT url, creator, secure FROM shortlinks WHERE shortlink=%s AND course=%s",
            [path, get_course()],
        ).fetchone()
    return list(target) if target else (None, None, None)


@app.route("/<path>/")
def handler(path):
    url, creator, secure = lookup(path)
    if not url:
Esempio n. 16
0
from common.rpc.secrets import get_secret, only, validates_master_secret
from common.url_for import url_for
from conf import GITHUB_REPO
from service_management import delete_unused_services
from github_utils import BuildStatus, pack, set_pr_comment
from scheduling import report_build_status
from target_determinator import determine_targets
from worker import land_commit

DO_NOT_BUILD = "DO NOT BUILD"

app = Flask(__name__)
if __name__ == "__main__":
    app.debug = True

create_oauth_client(app, "61a-buildserver")

with connect_db() as db:
    db(
        """CREATE TABLE IF NOT EXISTS services (
    app varchar(128),
    pr_number int,
    locked boolean,
    is_web_service boolean
)
"""
    )
    db(
        """CREATE TABLE IF NOT EXISTS apps (
    app varchar(128),
    repo varchar(128),
Esempio n. 17
0
from html import escape
from json import loads

from flask import Flask, abort

from common.oauth_client import create_oauth_client, get_user, is_staff, login
from common.shell_utils import sh
from common.url_for import url_for
from common.rpc.auth import is_admin

app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
    app.debug = True

create_oauth_client(app, "61a-logs")


@app.route("/")
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"""
    <h1>Log Viewer</h1>