Skip to content
Closed
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
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ GOOGLE_SERVICE_ACCOUNT_EMAIL=
# Optional: enables /api/sudo/* and export_attendance_secret. Use a long random value.
API_SECRET=

# Cal 1 Card photo API, for roster photos; the same settings as seating. In
# development the app uses made-up photos unless this is false. C1C only answers
# allowlisted addresses, so requests go through C1C_PROXY_URL (ask a maintainer).
MOCK_C1C=true
C1C_API_DOMAIN=
C1C_API_USERNAME=
C1C_API_PASSWORD=
C1C_PROXY_URL=

# Google Sheets import uses Application Default Credentials. Locally, run:
# gcloud auth application-default login \
# --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/spreadsheets.readonly
Expand Down
55 changes: 55 additions & 0 deletions server/c1c_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Student photos from the Cal 1 Card office's API (C1C), for roster photos (#4).

Works like seating's server/services/c1c/__init__.py, which has used this API
since 2024, and takes the same settings. C1C only answers requests from
allowlisted addresses, so requests go through C1C_PROXY_URL when it's set.
"""

import requests
from flask import current_app

# Seconds to wait for C1C, so a slow response can't hold up the request; the
# roster shows the placeholder instead.
TIMEOUT = 10


# Input: sid, a student's ID number.
# Output: (image bytes, content type), or None if there's no photo.
# Description: Development uses a made-up picture (fake_photo) unless
# MOCK_C1C=false. Without C1C settings (as on staging today), or if C1C fails,
# there's no photo, so the page shows a placeholder instead of an error.
def get_photo(sid: str) -> tuple[bytes, str] | None:
config = current_app.config
if config.get("MOCK_C1C"):
return fake_photo(sid)
if not config.get("C1C_API_DOMAIN"):
return None
proxy_url = config.get("C1C_PROXY_URL")
try:
response = requests.get(
config["C1C_API_DOMAIN"].rstrip("/") + f"/c1c-api/v1/photo/{sid}",
auth=(config["C1C_API_USERNAME"], config["C1C_API_PASSWORD"]),
proxies={"http": proxy_url, "https": proxy_url} if proxy_url else None,
timeout=TIMEOUT,
)
except requests.RequestException:
return None
if response.status_code != 200:
return None
return response.content, "image/jpeg"


# Input: sid, a student's ID number.
# Output: (SVG bytes, "image/svg+xml"), a plain head-and-shoulders drawing.
# Description: Stands in for a real photo in development and tests. The
# background color comes from the SID, so different students look different.
def fake_photo(sid: str) -> tuple[bytes, str]:
hue = sum(map(ord, sid)) * 47 % 360
svg = (
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96">'
f'<rect width="96" height="96" fill="hsl({hue} 45% 70%)"/>'
'<circle cx="48" cy="38" r="18" fill="#fff"/>'
'<ellipse cx="48" cy="92" rx="32" ry="28" fill="#fff"/>'
"</svg>"
)
return svg.encode(), "image/svg+xml"
9 changes: 6 additions & 3 deletions server/canvas_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,14 @@ def get_user_courses(user_id, access_token: str) -> dict:


def get_student_from_email(email: str, access_token: str):
"""``(canvas user id, name)`` of the student in the current course with
login ``email``, or None. The name is their display name, as at login."""
"""``(canvas user id, name, sid)`` of the student in the current course with
login ``email``, or None. The name is their display name, as at login. The
SID is None if Canvas doesn't show it to this staff member."""
course = _client(access_token).get_course(get_canvas_course_id())
for enrollment in course.get_enrollments(type=["StudentEnrollment"]):
user = enrollment.user
if user["login_id"] == email:
return str(user["id"]), user.get("short_name") or user["name"]
# Canvas's docs promise the SID on the enrollment; fall back to the user record.
sid = getattr(enrollment, "sis_user_id", None) or user.get("sis_user_id")
return str(user["id"]), user.get("short_name") or user["name"], sid
return None
7 changes: 7 additions & 0 deletions server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ def load_config(app: flask.Flask):
GOOGLE_SERVICE_ACCOUNT_EMAIL=os.getenv("GOOGLE_SERVICE_ACCOUNT_EMAIL"),
# Shared secret for the /api/sudo/* and export_attendance_secret endpoints.
API_SECRET=os.getenv("API_SECRET"),
# Cal 1 Card photo API (c1c_service.py), with the same settings as
# seating. Development uses made-up photos unless MOCK_C1C=false.
MOCK_C1C=is_dev and os.getenv("MOCK_C1C", "true").lower() == "true",
C1C_API_DOMAIN=os.getenv("C1C_API_DOMAIN"),
C1C_API_USERNAME=os.getenv("C1C_API_USERNAME"),
C1C_API_PASSWORD=os.getenv("C1C_API_PASSWORD"),
C1C_PROXY_URL=os.getenv("C1C_PROXY_URL"),
PERMANENT_SESSION_LIFETIME=7200,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SECURE=not is_dev,
Expand Down
3 changes: 2 additions & 1 deletion server/fake_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ def __init__(self, canvas_id):

def get_profile(self) -> dict:
return {"id": self.id, "name": self.name, "short_name": self.short_name,
"primary_email": self.email, "login_id": self.login_id}
"primary_email": self.email, "login_id": self.login_id,
"sis_user_id": self.sis_user_id}

def get_courses(self, *, enrollment_state="active", include=(), per_page=100) -> list[FakeCourse]:
return [FakeCourse(course_id, course["enrollments"])
Expand Down
3 changes: 3 additions & 0 deletions server/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ def complete_login(token: dict):
user.email = email
user.name = name
user.pronouns = profile.get("pronouns") or None
# Canvas may leave out the SID, depending on what this person may see; keep
# the one we have (e.g. from when staff added them) rather than erase it.
user.sid = profile.get("sis_user_id") or user.sid
user.canvas_courses = courses
user.is_global_admin = override_id is not None and str(override_id) in courses
db.session.commit()
Expand Down
24 changes: 24 additions & 0 deletions server/migrations/versions/0005_sid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Add users.sid, the student ID number from Canvas, for roster photos.

Revision ID: 0005_sid
Revises: 0004_pronouns
Create Date: 2026-11-16
"""
from alembic import op
import sqlalchemy as sa


revision = "0005_sid"
down_revision = "0004_pronouns"
branch_labels = None
depends_on = None


def upgrade():
with op.batch_alter_table("users") as batch:
batch.add_column(sa.Column("sid", sa.String(length=255), nullable=True))


def downgrade():
with op.batch_alter_table("users") as batch:
batch.drop_column("sid")
3 changes: 3 additions & 0 deletions server/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,9 @@ class User(db.Model, UserMixin):
# As shared through CalCentral/UCPath and reported by Canvas at login; None if
# the person hasn't shared any (or hasn't logged in).
pronouns: str = db.Column(db.String(255), nullable=True)
# Student ID number (Canvas's sis_user_id), used to look up their Cal 1 Card
# photo. None until Canvas has shown it to us, at login or when staff add them.
sid: str = db.Column(db.String(255), nullable=True)
# Active Canvas courses at last login, keyed by str(canvas course id):
# {"name", "code", "start_at", "is_staff", "is_admin", "is_student"}.
canvas_courses: dict = db.Column(db.JSON, nullable=False, default=dict)
Expand Down
23 changes: 22 additions & 1 deletion server/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from sqlalchemy import func
from sqlalchemy.orm import joinedload, noload

import c1c_service
import canvas_service
from offering import OFFERING_URL_PREFIX, get_canvas_course_id, get_course, get_course_name, load_offering
from import_sheet import check_capacity, import_sections_from_url, import_enrollment_from_url, parse_capacity
Expand Down Expand Up @@ -707,8 +708,9 @@ def add_students(emails: str, section_id: str):

if not found:
raise Failure("Could not find email that belongs to this class")
canvas_id, canvasname = found
canvas_id, canvasname, sid = found
student = find_or_add_person(email, canvasname, canvas_id=canvas_id)
student.sid = sid or student.sid
student.set_role(get_course(), is_staff=False)
add_student_helper(student, section)
db.session.commit()
Expand Down Expand Up @@ -835,6 +837,25 @@ def fetch_user(user_id: str):
raise Failure(f"No user found with id {user_id}")
return user.simple_json

# Input: user_id, the student whose photo to show.
# Output: their Cal 1 Card photo, or 404 if there isn't one.
# Description: A plain GET, not @api, so an <img> tag can load it. Staff
# only, and only for people in this course. The photo isn't saved, and
# "private" keeps shared caches from storing it.
@bp.route("/api/students/<int:user_id>/photo")
@login_required
def student_photo(user_id: int):
if not current_user.is_staff:
abort(403)
student = offering_member(id=user_id)
photo = c1c_service.get_photo(student.sid) if student is not None and student.sid else None
if photo is None:
abort(404)
image, content_type = photo
response = flask.Response(image, mimetype=content_type)
response.headers["Cache-Control"] = "private, max-age=3600"
return response

@api
@staff_required
def get_userid(email: str):
Expand Down
13 changes: 9 additions & 4 deletions src/HistoryPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import Pronouns from "./Pronouns";
import type { ID, PersonDetails } from "./models";
import { sectionTitle } from "./models";
import StateContext from "./StateContext";
import StudentPhoto from "./StudentPhoto";
import useAPI from "./useAPI";

type Props = {
Expand Down Expand Up @@ -45,10 +46,14 @@ export default function HistoryPage({ userID }: Props): React.ReactNode {
<br />
<Row>
<Col>
<h1 className="h2">
{user.name}
<Pronouns of={user} />
</h1>
<div className="d-flex align-items-center gap-3 mb-2">
{/* userID is set only when staff look at someone else's history. */}
{userID != null && <StudentPhoto studentID={userID} size={120} />}
<h1 className="h2 mb-0">
{user.name}
<Pronouns of={user} />
</h1>
</div>

{userID == null && (
<p>
Expand Down
44 changes: 24 additions & 20 deletions src/SectionRoster.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import AddStudentModal from "./AddStudentModal";
import Pronouns from "./Pronouns";
import type { SectionDetails } from "./models";
import StateContext from "./StateContext";
import StudentPhoto from "./StudentPhoto";
import useAPI from "./useStateAPI";
import useSectionAPI from "./useSectionAPI";

Expand Down Expand Up @@ -80,26 +81,29 @@ export default function SectionRoster({ section }: Props) {
{section.students.map((student) => (
<CardHolder key={student.email}>
<Card>
<Card.Body>
<Card.Title>
<Link to={`/user/${student.id}`}>{student.name}</Link>
<Pronouns of={student} />
</Card.Title>
<Card.Text>
<a href={`mailto:${student.email}`}>{student.email}</a>
</Card.Text>{" "}
<Button
variant="danger"
size="sm"
onClick={() =>
removeStudent({
student: student.email,
section_id: section.id,
}).then(() => refreshState())
}
>
Remove
</Button>
<Card.Body className="d-flex gap-3">
<StudentPhoto studentID={student.id} size={72} />
<div className="text-break">
<Card.Title>
<Link to={`/user/${student.id}`}>{student.name}</Link>
<Pronouns of={student} />
</Card.Title>
<Card.Text>
<a href={`mailto:${student.email}`}>{student.email}</a>
</Card.Text>{" "}
<Button
variant="danger"
size="sm"
onClick={() =>
removeStudent({
student: student.email,
section_id: section.id,
}).then(() => refreshState())
}
>
Remove
</Button>
</div>
</Card.Body>
</Card>
</CardHolder>
Expand Down
10 changes: 8 additions & 2 deletions src/SessionAttendance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import styled from "styled-components";
import AddStudentModal from "./AddStudentModal";
import AttendanceRow from "./AttendanceRow";
import Pronouns from "./Pronouns";
import StudentPhoto from "./StudentPhoto";
import { nextSessionStartTime } from "./models";
import type { AttendanceStatusType, Person, SectionDetails, Session } from "./models";
import useSectionAPI from "./useSectionAPI";
Expand Down Expand Up @@ -110,8 +111,13 @@ export default function SessionAttendance({ section, session }: Props) {
{students.map((student) => (
<tr key={student.email} className="text-center">
<td className="align-middle">
<Link to={`/user/${student.id}`}>{student.name}</Link>
<Pronouns of={student} />
<div className="d-inline-flex align-items-center gap-2">
<StudentPhoto studentID={student.id} size={32} />
<span>
<Link to={`/user/${student.id}`}>{student.name}</Link>
<Pronouns of={student} />
</span>
</div>
</td>
<td>
<AttendanceRow
Expand Down
43 changes: 43 additions & 0 deletions src/StudentPhoto.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useState } from "react";
import { PersonFill } from "react-bootstrap-icons";
import COURSE_BASE from "./coursePath";
import type { ID } from "./models";

type Props = {
studentID: ID;
// Width and height in pixels.
size: number;
};

// Input: studentID, whose Cal 1 Card photo to show, and its size in pixels.
// Output: the photo, or a gray placeholder if there isn't one.
// Description: Only for staff pages: the server refuses everyone else. The
// server answers 404 with no photo, so onError switches to the placeholder.
// alt is empty because the student's name is always shown right beside it.
export default function StudentPhoto({ studentID, size }: Props) {
// Remember which student failed, so moving to another student tries again.
const [missingPhotoID, setMissingPhotoID] = useState<ID | null>(null);

if (missingPhotoID === studentID) {
return (
<div
className="rounded bg-secondary-subtle text-secondary d-flex align-items-center justify-content-center flex-shrink-0"
style={{ width: size, height: size }}
aria-hidden="true"
>
<PersonFill size={size / 2} />
</div>
);
}
return (
<img
src={`${COURSE_BASE}/api/students/${studentID}/photo`}
alt=""
width={size}
height={size}
className="rounded flex-shrink-0"
style={{ objectFit: "cover" }}
onError={() => setMissingPhotoID(studentID)}
/>
);
}
1 change: 1 addition & 0 deletions tests/a11y/test_a11y_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class Page:
"/<path:filename>": "not a page (the React build's files)",
"/health": "not a page",
"/offerings/<int:canvas_course_id>/debug": "not a page",
"/offerings/<int:canvas_course_id>/api/students/<int:user_id>/photo": "not a page (a student's photo)",
"/login/": "redirects to the login page",
"/authorized/": "redirects after login",
"/logout/": "redirects after logout",
Expand Down
Loading