Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,6 @@ SECRET_KEY=
# Required outside development; in development the app uses app.db (SQLite).
DATABASE_URL=

# The course this deployment serves: the key stored with each row, and its
# bCourses course. Required outside development; in development, cs61a and the
# UC Berkeley sandbox's test course.
COURSE_KEY=
CANVAS_COURSE_ID=

# Canvas developer key. Locally, use the UC Berkeley sandbox key:
# https://ucberkeleysandbox.instructure.com/
CANVAS_SERVER_URL=https://ucberkeleysandbox.instructure.com/
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ Provides a web-based interface for requesting help during office hours.

Students request help on an assignment and question number from a location.

Students and staff sign in with bCourses, and a person's staff role comes from their bCourses enrollment.
Students and staff sign in with bCourses, and a person's staff role in each course comes from their bCourses enrollment.

For now each deployment serves one course, set by `COURSE_KEY` and `CANVAS_COURSE_ID` (see `.env.example`).
One site serves every course, with seating's and sections' routes: after signing in, `/offerings` lists your courses, and each course's queue is at `/offerings/<bCourses course id>/`. Course staff set up a queue for one of their bCourses courses with **Import courses from Canvas**. A course moved from one of the old per-course sites keeps its data under its old key (such as `cs61a`): a maintainer links it to its bCourses course with `python manage.py link-offering <bCourses course id> <key> "<name>"`.

## Installation

Expand All @@ -25,7 +25,7 @@ python manage.py seed_data
python manage.py run_server
```

Then open http://localhost:3000 and sign in at `/testing-login/`. The database is SQLite (`app.db`) unless `.env` sets `DATABASE_URL`. To sign in with bCourses instead, set `CANVAS_CLIENT_ID` and `CANVAS_CLIENT_SECRET` in `.env` to the UC Berkeley sandbox's developer key.
Then open http://localhost:3000/offerings/157/ (the course `seed_data` sets up) and sign in. Without `CANVAS_CLIENT_ID`, signing in goes to a development login, where you can be anyone, as a TA or a student in every course. The database is SQLite (`app.db`) unless `.env` sets `DATABASE_URL`. To sign in with bCourses instead, set `CANVAS_CLIENT_ID` and `CANVAS_CLIENT_SECRET` in `.env` to the UC Berkeley sandbox's developer key.

`seed_data` adds sample assignments, locations, students and tickets. `python manage.py resetdb` starts the database over.

Expand Down
5 changes: 0 additions & 5 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,6 @@ def required(name, dev_default=None):

LOCAL_TIMEZONE = os.getenv("TIMEZONE", "US/Pacific")

# The course this deployment serves. In development, the UC Berkeley sandbox's
# test course.
COURSE_KEY = required("COURSE_KEY", dev_default="cs61a")
CANVAS_COURSE_ID = int(required("CANVAS_COURSE_ID", dev_default="157"))

CANVAS_SERVER_URL = os.getenv(
"CANVAS_SERVER_URL", "https://ucberkeleysandbox.instructure.com/"
)
Expand Down
27 changes: 19 additions & 8 deletions manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@
import alembic.command
from alembic.config import Config
from dotenv import load_dotenv
from flask import render_template
from flask import render_template, url_for
from flask_migrate import Migrate
from werkzeug.serving import run_simple

# Before importing the app: config.py reads the environment when it's imported.
load_dotenv()

from oh_queue import app # noqa: E402
from oh_queue.course import get_course # noqa: E402
from oh_queue.models import ( # noqa: E402
Assignment,
Location,
Offering,
Ticket,
TicketStatus,
User,
Expand All @@ -32,6 +32,8 @@
os.environ["FLASK_APP"] = "manage.py"

migrate = Migrate(app, db)
# The UC Berkeley sandbox's test course, which seed_data sets up.
DEV_CANVAS_COURSE_ID = 157
alembic_cfg = Config("migrations/alembic.ini")


Expand All @@ -53,12 +55,19 @@ def seed_data():

print("Seeding...")

# The UC Berkeley sandbox's test course, under the key the per-course sites used.
offering = Offering.query.filter_by(canvas_id=DEV_CANVAS_COURSE_ID).one_or_none()
if offering is None:
offering = Offering(canvas_id=DEV_CANVAS_COURSE_ID, key="cs61a", name="CS 61A (sandbox)", code="CS 61A")
db.session.add(offering)
course = offering.key

assignments = [
Assignment(name=name, course=get_course(), visible=True)
Assignment(name=name, course=course, visible=True)
for name in ["Hog", "Maps", "Ants", "Scheme"]
]
locations = [
Location(name=name, course=get_course(), visible=True, online=False, link="")
Location(name=name, course=course, visible=True, online=False, link="")
for name in ["109 Morgan", "241 Cory", "247 Cory"]
]
questions = list(range(1, 16)) + ["Other", "EC", "Checkoff"]
Expand All @@ -79,9 +88,9 @@ def seed_data():
random.choice([last_name, last_name[0]]),
random.choice(["berkeley.edu", "gmail.com"]),
)
student = User.query.filter_by(email=email).one_or_none()
student = User.query.filter_by(email=email, course=course).one_or_none()
if not student:
student = User(name=real_name, email=email, course=get_course())
student = User(name=real_name, email=email, course=course)
db.session.add(student)
db.session.commit()

Expand All @@ -94,11 +103,13 @@ def seed_data():
location=random.choice(locations),
question=random.choice(questions),
description=random.choice(descriptions),
course=get_course(),
course=course,
)
db.session.add(ticket)

db.session.commit()
with app.test_request_context():
print(f"Seeded {offering.display_name}: open {url_for('offering.index', canvas_course_id=offering.canvas_id)}")


@app.cli.command("resetdb")
Expand All @@ -125,7 +136,7 @@ def create_tables():
@not_in_production
def build():
with app.test_request_context():
render_template("index.html", course_name="test")
render_template("index.html", course_name="test", base_path="/offerings/0")


@app.cli.command("run_server")
Expand Down
78 changes: 78 additions & 0 deletions migrations/versions/d3a7e5f1c0b2_add_offerings_and_accounts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""Add offerings and accounts, so one site serves every course

Also removes the only_registered_students setting: a course's queue is now
only open to people enrolled in it on bCourses.

Revision ID: d3a7e5f1c0b2
Revises: 4370289bdaeb
Create Date: 2026-11-20 00:00:00.000000

"""

from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "d3a7e5f1c0b2"
down_revision = "4370289bdaeb"
branch_labels = None
depends_on = None

config_entries = sa.table(
"config_entries",
sa.column("key", sa.String),
sa.column("value", sa.Text),
sa.column("public", sa.Boolean),
sa.column("course", sa.String),
)


def upgrade():
# New tables: existing rows keep their course keys, and an offering
# moved from a per-course site is linked to its key with `flask link-offering`.
op.create_table(
"offerings",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("canvas_id", sa.Integer(), nullable=False),
sa.Column("key", sa.String(length=255), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("code", sa.String(length=255), nullable=True),
sa.Column("start_at", sa.String(length=255), nullable=True),
sa.Column("hidden", sa.Boolean(), server_default=sa.false(), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("key"),
)
op.create_index("ix_offerings_canvas_id", "offerings", ["canvas_id"], unique=True)

op.create_table(
"account",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("canvas_id", sa.String(length=255), nullable=False),
sa.Column("email", sa.String(length=255), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("is_global_admin", sa.Boolean(), nullable=False),
sa.Column("canvas_courses", sa.JSON(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_account_canvas_id", "account", ["canvas_id"], unique=True)
op.create_index("ix_account_email", "account", ["email"], unique=False)

op.execute(config_entries.delete().where(config_entries.c.key == "only_registered_students"))


def downgrade():
# Back with its default, off, in every course.
courses = [
course
for (course,) in op.get_bind().execute(sa.select(config_entries.c.course).distinct())
]
op.bulk_insert(
config_entries,
[{"key": "only_registered_students", "value": "false", "public": True, "course": course}
for course in courses],
)
op.drop_index("ix_account_email", table_name="account")
op.drop_index("ix_account_canvas_id", table_name="account")
op.drop_table("account")
op.drop_index("ix_offerings_canvas_id", table_name="offerings")
op.drop_table("offerings")
6 changes: 5 additions & 1 deletion oh_queue/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

from flask_session import Session
from datetime import timedelta
from oh_queue.errors import register_error_handlers
from oh_queue.login import create_login_client
from oh_queue.offerings import create_offering_pages

# Flask-related stuff

Expand Down Expand Up @@ -37,8 +39,10 @@

db.init_app(app)

# Initialize Canvas login
# Initialize Canvas login and the pages for choosing a course
create_login_client(app)
create_offering_pages(app)
register_error_handlers(app)

# Configure server-side sessions
app.config['SESSION_TYPE'] = 'sqlalchemy'
Expand Down
63 changes: 38 additions & 25 deletions oh_queue/canvas_service.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
"""The Canvas API calls made when someone signs in."""

from canvasapi import Canvas
from canvasapi.course import Course
from flask import current_app

from oh_queue.models import can_be_offering

# What the app asks Canvas for at sign-in.
SCOPES = [
"url:GET|/api/v1/users/:id",
"url:GET|/api/v1/courses/:id",
"url:GET|/api/v1/users/:user_id/courses",
"url:GET|/api/v1/users/:user_id/profile",
"url:GET|/api/v1/courses/:course_id/enrollments",
]

# Enrollment types as the user courses endpoint reports them.
STAFF_ENROLLMENT_TYPES = {"ta", "teacher"}


def _client(access_token: str) -> Canvas:
return Canvas(current_app.config["CANVAS_SERVER_URL"], access_token)
Expand All @@ -22,25 +24,36 @@ def get_profile(user_id, access_token: str) -> dict:
return _client(access_token).get_user(user_id).get_profile()


def get_course(course_id: int, access_token: str) -> Course:
return _client(access_token).get_course(course_id)


def in_admin_override_course(user_id, access_token: str) -> bool:
"""Whether the user is in ADMIN_OVERRIDE_CANVAS_COURSE_ID, which makes
them staff in every course."""
override_id = current_app.config.get("ADMIN_OVERRIDE_CANVAS_COURSE_ID")
if override_id is None:
return False
courses = _client(access_token).get_user(user_id).get_courses(
enrollment_status="active", per_page=100
)
return any(c.id == override_id for c in courses)


def is_staff(course: Course, user_id) -> bool:
"""Whether the user is a TA or teacher in a Canvas course."""
return any(
e.type in ("TaEnrollment", "TeacherEnrollment")
for e in course.get_enrollments(user_id=str(user_id))
)
def _start_at(course):
"""The term's start, else the course's own start, else its creation, like seating."""
term = getattr(course, "term", None) or {}
return term.get("start_at") or getattr(course, "start_at", None) or getattr(course, "created_at", None)


def get_user_courses(user_id, access_token: str) -> dict:
"""The user's active Canvas courses and their role in each, as in sections.

Returns ``{str(course id): {"name", "code", "start_at", "is_staff", "is_admin",
"is_student"}}``. Staff are TAs and Teachers; admins are Teachers and Lead TAs.
"""
courses = {}
for c in _client(access_token).get_user(user_id).get_courses(
enrollment_state="active", include=["term"], per_page=100
):
enrollments = getattr(c, "enrollments", None) or []
if not enrollments or not hasattr(c, "course_code"):
continue # courses the user can't see, or restricted by date
if not can_be_offering(c.id):
current_app.logger.info("Skipped Canvas course %s (%s): its ID is too big", c.id, c.name)
continue
types = {e["type"] for e in enrollments}
roles = {e.get("role") for e in enrollments}
courses[str(c.id)] = {
"name": c.name,
"code": c.course_code,
"start_at": _start_at(c),
"is_staff": bool(types & STAFF_ENROLLMENT_TYPES),
"is_admin": "teacher" in types or "Lead TA" in roles,
"is_student": "student" in types,
}
return courses
29 changes: 0 additions & 29 deletions oh_queue/course.py

This file was deleted.

26 changes: 26 additions & 0 deletions oh_queue/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Error pages that say what went wrong, as in sections, instead of Werkzeug's
bare ones, which leave people with no way back to the site.

Course API calls (paths containing /api/) get JSON with the message; the
course page reloads when its API is refused, to show the page's own error.
"""

import flask
from flask import current_app, jsonify, request
from werkzeug.exceptions import HTTPException


def error_page(title: str, message: str, status: int):
# Rendered without render_template, whose context processors include
# Flask-Login's, which loads the signed-in user: that can be what failed
# (someone not enrolled in the course). error.html doesn't show the user.
template = current_app.jinja_env.get_template("pages/error.html")
return template.render(title=title, message=message), status


def register_error_handlers(app: flask.Flask):
@app.errorhandler(HTTPException)
def http_error(error: HTTPException):
if "/api/" in request.path:
return jsonify({"message": error.description}), error.code
return error_page(f"{error.code} {error.name}", error.description, error.code)
Loading