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
17 changes: 11 additions & 6 deletions backend/classroom/test_wave_e_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,22 +95,27 @@ class EffortAndHeatmapTest(ReportsBase):
"""Items 43/44: the analytics derivations."""

def test_effort_board_ranks_grinders(self):
# st attempts 3 times (2 active days); lz a single AC.
# The two "old day" submissions are pinned to fixed clock times on
# explicit dates (10:00 and 10:30 two days ago, 10:00 yesterday):
# minutes_ago offsets straddle midnight depending on the wall clock
# at run time, which made active_days flake (3 dates at night runs).
# st attempts 4 times (2 active days); lz a single AC. Every
# submission sits on a pinned instant (10:00/10:30 two days ago,
# 10:00/10:30 yesterday) and the window is widened to 3 days so
# the pins always fall inside — fully wall-clock independent.
Assignment.objects.filter(pk=self.assignment.pk).update(
available_from=timezone.now() - timedelta(days=3),
due_at=timezone.now() + timedelta(days=3),
)

def pinned(days_ago: int, minute: int = 0):
moment = timezone.now() - timedelta(days=days_ago)
return moment.replace(hour=10, minute=minute, second=0, microsecond=0)

self._submit_at(self.student, WA, 10, pinned(2, 0))
self._submit_at(self.student, WA, 20, pinned(2, 30))
self._submit_at(self.student, WA, 30, pinned(1, 0))
self._submit_at(self.student, WA, 40, pinned(1, 30))
self._submit(self.lazy, AC, 100)
board = effort_board(self.classroom)
rows = {r["username"]: r for r in board["results"]}
self.assertEqual(rows["st"]["attempts"], 3)
self.assertEqual(rows["st"]["attempts"], 4)
self.assertEqual(rows["st"]["active_days"], 2)
self.assertEqual(rows["st"]["problems_solved"], 0)
self.assertEqual(rows["lz"]["problems_solved"], 1)
Expand Down
8 changes: 8 additions & 0 deletions backend/users/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,11 @@ class UserAdmin(BaseUserAdmin):
class OwnerWeeklySnapshotAdmin(admin.ModelAdmin):
list_display = ("week", "captured_at")
readonly_fields = ("week", "captured_at", "payload")


from .models import SetterProfile # noqa: E402


@admin.register(SetterProfile)
class SetterProfileAdmin(admin.ModelAdmin):
list_display = ("user", "updated_at")
55 changes: 55 additions & 0 deletions backend/users/migrations/0010_setterprofile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Generated by Django 5.2.17 on 2026-11-18 09:15

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("users", "0009_user_bio"),
]

operations = [
migrations.CreateModel(
name="SetterProfile",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"blurb",
models.TextField(blank=True, max_length=600, verbose_name="blurb"),
),
(
"links",
models.JSONField(
blank=True,
default=list,
help_text="Up to 5 external links (strings).",
verbose_name="links",
),
),
("updated_at", models.DateTimeField(auto_now=True)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="setter_profile",
to=settings.AUTH_USER_MODEL,
verbose_name="user",
),
),
],
options={
"verbose_name": "setter profile",
"verbose_name_plural": "setter profiles",
},
),
]
29 changes: 29 additions & 0 deletions backend/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,32 @@ class Meta:

def __str__(self):
return f"{self.follower_id} -> {self.target_id}"


class SetterProfile(models.Model):
"""Item 70 — the author-editable side of the setter CV: a short blurb
and up to five links (personal site, GitHub, editorial portfolio…)."""

MAX_LINKS = 5

user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="setter_profile",
verbose_name=_("user"),
)
blurb = models.TextField(_("blurb"), max_length=600, blank=True)
links = models.JSONField(
_("links"),
default=list,
blank=True,
help_text=_("Up to 5 external links (strings)."),
)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
verbose_name = _("setter profile")
verbose_name_plural = _("setter profiles")

def __str__(self):
return f"setter-cv: {self.user_id}"
162 changes: 162 additions & 0 deletions backend/users/profile_widgets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
"""Setter CVs, solve cards and embeddable widgets (wave F items 70-72).

Endpoints (all public where noted):

- ``GET /users/{username}/setter-cv/`` the derived portfolio + profile
- ``PUT /users/{username}/setter-cv/`` owner edits blurb/links
- ``GET /cards/solve/{username}/{problem_id}/`` the solve-card payload
- ``GET /cards/solve/{username}/{problem_id}/svg`` the shareable SVG card
- ``GET /embed/problems/{problem_id}/`` the embeddable widget payload
"""

from __future__ import annotations

import html

from django.contrib.auth import get_user_model
from django.utils import timezone
from django.shortcuts import get_object_or_404
from rest_framework import permissions, serializers, status
from rest_framework.response import Response
from rest_framework.views import APIView

from problems.models import Problem
from submissions.models import Submission

from .setter import setter_cv, solve_card

User = get_user_model()


class SetterProfileSerializer(serializers.Serializer):
blurb = serializers.CharField(max_length=600, required=False, allow_blank=True)
links = serializers.ListField(
child=serializers.URLField(), required=False, max_length=5
)


class SetterCVView(APIView):
"""Item 70 — the public setter CV; owners PUT their blurb/links."""

def get(self, request, username):
user = User.objects.filter(username=username).first()
if user is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(setter_cv(user))

def put(self, request, username):
user = User.objects.filter(username=username).first()
if user is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
if user.id != request.user.id:
return Response(
{"detail": "Only the setter edits their CV."},
status=status.HTTP_403_FORBIDDEN,
)
payload = SetterProfileSerializer(data=request.data)
payload.is_valid(raise_exception=True)
from .models import SetterProfile

profile, _ = SetterProfile.objects.get_or_create(user=user)
if "blurb" in payload.validated_data:
profile.blurb = payload.validated_data["blurb"]
if "links" in payload.validated_data:
profile.links = payload.validated_data["links"]
profile.save()
return Response(setter_cv(user))


class SolveCardView(APIView):
"""Item 71 — the deterministic solve-card payload."""

permission_classes = [permissions.AllowAny]

def get(self, request, username, problem_id):
user = User.objects.filter(username=username).first()
problem = Problem.objects.filter(pk=problem_id).first()
if user is None or problem is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(solve_card(user, problem))
Comment on lines +74 to +79

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: SolveCardView and SolveCardSvgView do not enforce problem status or contest visibility checks, leaking metadata for non-public or contest problems to unauthenticated callers.
Severity: MEDIUM

Suggested Fix

Filter problem queries to only allow APPROVED status (or owner-accessible problems for authenticated users) and ensure problems locked in active contests return a 404 response.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: backend/users/profile_widgets.py#L74-L79

Potential issue: `SolveCardView` and `SolveCardSvgView` permit anonymous access and
retrieve problems using `Problem.objects.filter(pk=problem_id).first()` without checking
visibility constraints such as `status=APPROVED` or active contest restrictions. This
allows anonymous users to iterate through sequential problem IDs to read metadata
including title, difficulty, and solver counts for draft, pending, private, or active
contest problems.

Also affects:

  • backend/users/profile_widgets.py:87~92



class SolveCardSvgView(APIView):
"""Item 71 — the shareable SVG render of the solve card."""

permission_classes = [permissions.AllowAny]

def get(self, request, username, problem_id):
user = User.objects.filter(username=username).first()
problem = Problem.objects.filter(pk=problem_id).first()
if user is None or problem is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
card = solve_card(user, problem)
# The viewer's own solve stays private: the SVG only renders for
# public facts (solved-on date + ordinal) — never code or feedback.
solved_date = (
card["solved_at"].strftime("%Y-%m-%d") if card["solved_at"] else ""
)
Comment on lines +95 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require an accepted submission before rendering a solved SVG

For an existing user who has never solved the requested problem, this public endpoint still returns an SVG labeled SOLVED under that user's handle. solve_card() returns solved_at=None in that case, but the renderer merely leaves the date blank and includes the problem's current solver count. Anyone can therefore obtain an official-looking solve card for an arbitrary user/problem pair without an accepted submission. Reject unsolved pairs before rendering, or render an explicitly unsolved state instead.

Useful? React with 👍 / 👎.

title = html.escape(card["problem_title"][:60])
handle = html.escape(card["username"][:30])
svg = f"""<svg xmlns="http://www.w3.org/2000/svg" width="600" height="200" viewBox="0 0 600 200">
<rect width="600" height="200" rx="16" fill="#0f172a"/>
<rect x="8" y="8" width="584" height="184" rx="12" fill="#1e293b"/>
<text x="32" y="58" fill="#38bdf8" font-family="sans-serif" font-size="22" font-weight="bold">SOLVED</text>
<text x="32" y="96" fill="#f8fafc" font-family="sans-serif" font-size="24" font-weight="bold">{handle}</text>
<text x="32" y="128" fill="#cbd5e1" font-family="sans-serif" font-size="18">{title}</text>
<text x="32" y="162" fill="#94a3b8" font-family="sans-serif" font-size="14">solver #{card["ordinal"]} · {solved_date} · webcoder</text>
</svg>"""
Comment on lines +97 to +107

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: SolveCardSvgView renders a "SOLVED" badge and solve card for users who have not solved the given problem.
Severity: MEDIUM

Suggested Fix

In SolveCardSvgView and SolveCardView, check if an accepted submission exists for (user, problem) or if card["solved_at"] is None, and return an HTTP 404 response.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: backend/users/profile_widgets.py#L87-L107

Potential issue: `SolveCardSvgView.get` renders a card image with a hardcoded "SOLVED"
label for any requested user and problem combination without verifying whether the user
actually achieved an accepted submission. If a user has not solved the problem,
`solved_at` resolves to `None`, but the endpoint still returns HTTP 200 with an SVG
claiming the problem is solved.

Did we get this right? 👍 / 👎 to inform future reviews.

from django.http import HttpResponse

return HttpResponse(svg, content_type="image/svg+xml")


class EmbedProblemView(APIView):
"""Item 72 — the embeddable problem-widget payload (statement summary
+ sample I/O + a CTA link; never hidden tests or full statements of
contest-fresh problems)."""

permission_classes = [permissions.AllowAny]

def get(self, request, problem_id):
problem = get_object_or_404(Problem, pk=problem_id)
Comment on lines +120 to +121

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict public widgets to publicly visible problems

For a draft or pending-approval problem that is not attached to an upcoming/running contest, this anonymous endpoint returns its title and sample inputs/outputs to anyone who supplies its ID. The existing visibility boundary in ProblemViewSet.get_queryset() (backend/problems/views.py:201–227) restricts anonymous readers to APPROVED problems, but this lookup bypasses it. The two new solve-card views likewise query unrestricted problems and expose their metadata. Apply the public-problem visibility filter across these new public endpoints so unpublished author content cannot be retrieved by enumerating IDs.

Useful? React with 👍 / 👎.

from contests.models import ContestProblem

live_contest = ContestProblem.objects.filter(
problem=problem,
contest__end_at__gt=timezone.now(),
).exists()
if live_contest:
return Response(
{"detail": "This problem is not embeddable right now."},
Comment on lines +120 to +130

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: EmbedProblemView retrieves problems without validating status == APPROVED, leaking draft and private problem details to anonymous users.
Severity: HIGH

Suggested Fix

Enforce problem visibility checks matching ProblemViewSet.get_queryset or use the _visible_problem helper before returning the embed payload, returning a 404 for unapproved problems.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: backend/users/profile_widgets.py#L120-L130

Potential issue: `EmbedProblemView.get` uses `get_object_or_404(Problem, pk=problem_id)`
without checking the problem's `status`. Because the view allows any unauthenticated
caller, anonymous clients can query sequential IDs to inspect unpublished, draft, and
private problems—retrieving titles, limits, sample test cases, and solve counts that are
otherwise protected across the application.

Also affects:

  • backend/users/profile_widgets.py:74-79

Did we get this right? 👍 / 👎 to inform future reviews.

status=status.HTTP_403_FORBIDDEN,
)
title = (
problem.title_i18n.get("en", f"Problem {problem.id}")
if isinstance(problem.title_i18n, dict)
else f"Problem {problem.id}"
)
samples = list(
problem.test_cases.filter(is_sample=True)
.order_by("order")
.values("input_data", "expected_output_data")[:3]
)
solved = (
Submission.objects.filter(
problem=problem, verdict=Submission.VerdictStatus.ACCEPTED
)
.values_list("user_id")
.distinct()
.count()
)
return Response(
{
"problem_id": problem.id,
"title": title,
"difficulty": problem.difficulty,
"time_limit_ms": problem.default_time_limit_ms,
"memory_limit_kb": problem.default_memory_limit_kb,
"samples": samples,
"solved_by": solved,
"solve_url": f"/problems/{problem.id}",
}
)
92 changes: 92 additions & 0 deletions backend/users/setter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Setter CVs + shareable solve cards (wave F items 70-71).

- ``setter_cv`` — the derived authoring portfolio (approved problems by
difficulty, editorial/article credits, contest-setting credits) plus the
author-editable ``SetterProfile`` blurb and links.
- ``solve_card`` — the deterministic solve-card payload rendered as an SVG
by the view (username, problem, solve ordinal, date).
"""

from __future__ import annotations

from contests.models import ContestProblem
from problems.models import Article, CommunityEditorial, Problem


def setter_cv(user) -> dict:
"""The public setter portfolio (item 70)."""
approved = Problem.objects.filter(
author=user, status=Problem.ProblemStatus.APPROVED
)
by_difficulty = {"EASY": 0, "MEDIUM": 0, "HARD": 0}
for problem in approved:
if problem.difficulty in by_difficulty:
by_difficulty[problem.difficulty] += 1
Comment on lines +21 to +24

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include VERY_EASY problems in the difficulty breakdown

For setters who author beginner problems, the CV silently excludes all VERY_EASY problems from its difficulty breakdown even though they contribute to problems_approved. Problem.DifficultyLevel explicitly defines this supported difficulty, and the problem authoring form offers it, so a setter whose approved portfolio consists entirely of beginner problems gets a positive total alongside zero in every displayed difficulty bucket. Initialize the breakdown from the model's supported difficulty choices, including VERY_EASY, so those contributions are represented.

Useful? React with 👍 / 👎.

Comment on lines +21 to +24

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: by_difficulty omits "VERY_EASY", causing approved problems of that difficulty to be excluded from the setter CV's difficulty breakdown.
Severity: MEDIUM

Suggested Fix

Include "VERY_EASY" in by_difficulty by dynamically initializing keys from Problem.DifficultyLevel.values (or Problem.DifficultyLevel.choices), or use collections.Counter to track counts.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: backend/users/setter.py#L21-L24

Potential issue: In `backend/users/setter.py`, `by_difficulty` is initialized with keys
only for `"EASY"`, `"MEDIUM"`, and `"HARD"`, omitting `"VERY_EASY"`. When aggregating
problems for the setter CV breakdown, problems with difficulty `VERY_EASY` fail the
membership check and are omitted from `by_difficulty`. Consequently, the breakdown sums
to less than `problems_approved`, and the frontend displays missing or inconsistent
difficulty metrics for setters with approved `VERY_EASY` problems.

editorials = CommunityEditorial.objects.filter(
author=user, status=CommunityEditorial.Status.APPROVED
).count()
articles = Article.objects.filter(
author=user, status=Article.Status.APPROVED
).count()
contest_ids = set(
ContestProblem.objects.filter(
problem__in=approved.values_list("id", flat=True)
).values_list("contest_id", flat=True)
)
profile = getattr(user, "setter_profile", None)
return {
"username": user.username,
"blurb": profile.blurb if profile else "",
"links": profile.links if profile else [],
"problems_approved": approved.count(),
"problems_by_difficulty": by_difficulty,
"community_editorials": editorials,
"articles": articles,
"contests_contributed": len(contest_ids),
"member_since": user.date_joined,
}


def solve_ordinal(problem_id: int) -> int:
"""1-based solve ordinal of a problem (the Nth solver overall)."""
from submissions.models import Submission

return (
Submission.objects.filter(
problem_id=problem_id, verdict=Submission.VerdictStatus.ACCEPTED
)
.values_list("user_id")
.distinct()
.count()
)
Comment on lines +51 to +61

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: solve_ordinal calculates the total distinct solver count instead of the user's specific solve rank.
Severity: MEDIUM

Suggested Fix

Update solve_ordinal to accept the user or their earliest accepted submission timestamp, counting only distinct users who solved the problem at or before that timestamp.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: backend/users/setter.py#L50-L61

Potential issue: `solve_ordinal` computes the total count of distinct users with an
accepted submission on the problem rather than the solving user's specific rank or order
of solve. As a result, every solver displays the exact same ordinal on their card, and
the displayed number changes dynamically over time as subsequent users solve the
problem.

Did we get this right? 👍 / 👎 to inform future reviews.



def solve_card(user, problem) -> dict:
"""The deterministic share-card payload (item 71)."""
solved_at = None
from submissions.models import Submission

first = (
Submission.objects.filter(
user=user,
problem=problem,
verdict=Submission.VerdictStatus.ACCEPTED,
)
.order_by("submission_time")
.first()
)
if first is not None:
solved_at = first.submission_time
title = (
problem.title_i18n.get("en", f"Problem {problem.id}")
if isinstance(problem.title_i18n, dict)
else f"Problem {problem.id}"
)
return {
"username": user.username,
"problem_id": problem.id,
"problem_title": title,
"difficulty": problem.difficulty,
"ordinal": solve_ordinal(problem.id),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Calculate the ordinal at the user's first accepted submission

Once two users have solved a problem, both cards display solver #2, including the first solver's previously shared card. solve_ordinal() counts all current distinct solvers without considering this user or their first accepted submission, so the displayed ordinal is a changing solve count rather than the claimed deterministic solver position. Calculate the user's position using their first accepted submission and distinct solvers up to that point, so later solves do not change earlier users' ordinals.

Useful? React with 👍 / 👎.

"solved_at": solved_at,
}
Loading
Loading