Skip to content

Implement class join codes back-end#789

Open
fspeirs wants to merge 20 commits into
mainfrom
fs-implement-class-join-codes
Open

Implement class join codes back-end#789
fspeirs wants to merge 20 commits into
mainfrom
fs-implement-class-join-codes

Conversation

@fspeirs
Copy link
Copy Markdown
Contributor

@fspeirs fspeirs commented Apr 22, 2026

This PR implements the back-end for class join codes — students join a class by entering an 8-character code in the format CDDD-CDDD (consonant + three digits, twice, separated by a hyphen).

Core Logic

The core logic for this work lives in JoinController#create, which determines what response the front-end gets based on the user who is trying to join. This method returns a show.json.builder with values that allow the front-end to determine what to show the user, or where to redirect them to based on their status. The status value is computed in action_status.

Another feature of JoinController#show is that it may be called by unauthenticated users, so that we can destructure the join code into a school and class in order to show the user a school and class name before they're redirected to log in.

There are modifications to School to allow that model to carry a join code and regenerate it. Conceptually, a join code is a globally unique code that represents both a class code and a school code.

The other component of interest is the JoinCodeGenerator which produces the codes in the first place.

Changes

  • Add join_code column with a unique index to school_classes, plus a backfill migration for existing classes.
  • Add JoinCodeGenerator with .generate and .normalize (canonicalises user input to the hyphenated form for DB lookup).
  • Auto-assign join codes on SchoolClass create/import with a uniqueness retry, plus a regenerate_join_code! helper.
  • Add GET /api/join/:join_code returning the prospective user's status. The full set of statuses is:
    • unauthenticated — no current user
    • joinable — the user can be enrolled as a student
    • joinable_as_teacher — the user already has a teacher role for this school and will be added to the class as a teacher
    • owner — the user owns this school; treated as already a member for redirect purposes
    • already_member — the user is already a member of this class
    • wrong_school — the user has a role in a different school
    • domain_mismatch — the user's email domain is not registered for this school
    • not_a_student — the user has a non-student role elsewhere
  • Add POST /api/join/:join_code to enrol the current user as a student (or teacher, if joinable_as_teacher) of the school and class.
  • Add POST /api/schools/:school_id/classes/:id/regenerate_join_code (nested under the existing school_classes resource).
  • Expose join_code on the school class JSON
  • Add School#valid_email? (built on Store school email domains #787's domain validation) for the domain_mismatch check.
  • Add School#auto_join_enabled? to allow the front end to prompt users correctly about the requirements for auto-join.
  • Update CanCan abilities so school owners and class teachers can regenerate_join_code.
  • Add specs covering the model, generator, controllers, and abilities.

@cla-bot cla-bot Bot added the cla-signed label Apr 22, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 22, 2026

Test coverage

91.27% line coverage reported by SimpleCov.
Run: https://github.com/RaspberryPiFoundation/editor-api/actions/runs/26161488973

Comment thread spec/models/school_class_spec.rb Fixed
@fspeirs fspeirs force-pushed the fs-implement-class-join-codes branch from 2b3e115 to bb23e12 Compare April 22, 2026 12:43
@fspeirs fspeirs force-pushed the fs-implement-class-join-codes branch 2 times, most recently from 508b98b to aec7f84 Compare May 7, 2026 12:42
@fspeirs fspeirs changed the title Implement class join codes Implement class join codes back-end May 18, 2026
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-xjbsht May 18, 2026 10:23 Inactive
@fspeirs fspeirs force-pushed the fs-implement-class-join-codes branch from 85e8b32 to efa9fd2 Compare May 19, 2026 08:43
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-o7nlku May 19, 2026 08:43 Inactive
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-wn9exx May 19, 2026 14:44 Inactive
@fspeirs fspeirs force-pushed the fs-implement-class-join-codes branch from 8ee18e3 to 931a51f Compare May 20, 2026 09:35
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-l8upzy May 20, 2026 09:35 Inactive
@fspeirs fspeirs marked this pull request as ready for review May 20, 2026 09:44
Copilot AI review requested due to automatic review settings May 20, 2026 09:44
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Implements the API and supporting model changes for “class join codes”, enabling users to preview a class via join code (unauthenticated) and to enroll into a class (authenticated), plus providing a teacher/owner ability to regenerate a class join code.

Changes:

  • Add join_code to SchoolClass with generation/normalization via JoinCodeGenerator, plus backfill for existing records.
  • Introduce /api/join/:join_code (GET/POST) with status-driven responses and enrollment behavior.
  • Add regenerate_join_code endpoint + CanCan ability, and expose join_code / auto_join_enabled in JSON.

Reviewed changes

Copilot reviewed 20 out of 20 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
spec/requests/join_controller_spec.rb Request specs for join-code show/create behavior and status outcomes.
spec/models/school_spec.rb Specs for School#auto_join_enabled? and School#valid_email?.
spec/models/school_class_spec.rb Specs for join code assignment, regeneration, and validations.
spec/lib/join_code_generator_spec.rb Specs for join code generation and normalization.
spec/features/school_class/regenerating_join_code_spec.rb Request-style spec coverage for join code regeneration endpoint.
spec/features/my_school/showing_my_school_spec.rb Updates expected school JSON to include auto_join_enabled.
spec/factories/school_class.rb Factory now assigns join_code by default.
lib/join_code_generator.rb Adds generator/normalizer and join-code format regex.
db/schema.rb Schema update for school_classes.join_code + unique index.
db/migrate/20260420104939_backfill_join_code_for_school_classes.rb Backfills join codes for existing classes.
db/migrate/20260420104938_add_join_code_to_school_classes.rb Adds join_code column and unique index.
config/routes.rb Adds regenerate_join_code member route and join endpoints.
app/views/api/schools/_school.json.jbuilder Exposes auto_join_enabled on school JSON.
app/views/api/school_classes/_school_class.json.jbuilder Exposes join_code on school class JSON.
app/views/api/join/show.json.jbuilder Adds join “show” response JSON (status + school/class details).
app/models/school.rb Adds auto_join_enabled? and valid_email?.
app/models/school_class.rb Adds join code generation/validation + regeneration method.
app/models/ability.rb Grants regenerate_join_code to owners/teachers.
app/controllers/api/school_classes_controller.rb Adds regenerate_join_code action.
app/controllers/api/join_controller.rb Adds join show/create logic and enrollment behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread app/models/school.rb Outdated
Comment thread app/models/school_class.rb Outdated
Comment thread app/models/school_class.rb
Comment thread app/controllers/api/join_controller.rb Outdated
Comment thread config/routes.rb
Comment thread app/controllers/api/join_controller.rb
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-ogh53i May 20, 2026 10:13 Inactive
@fspeirs fspeirs requested a review from Copilot May 20, 2026 10:19
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 20 out of 20 changed files in this pull request and generated 3 comments.

Comment thread app/controllers/api/join_controller.rb Outdated
Comment thread app/views/api/schools/_school.json.jbuilder
Comment thread spec/features/school_class/regenerating_join_code_spec.rb Outdated
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-jf58r6 May 20, 2026 10:35 Inactive
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-jf58r6 May 20, 2026 10:36 Inactive
@fspeirs fspeirs requested a review from Copilot May 20, 2026 10:42
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 20 out of 20 changed files in this pull request and generated 7 comments.

Comment thread app/models/school_class.rb
Comment thread app/controllers/api/join_controller.rb Outdated
Comment thread app/controllers/api/school_classes_controller.rb Outdated
Comment thread db/migrate/20260420104938_add_join_code_to_school_classes.rb
Comment thread db/migrate/20260420104939_backfill_join_code_for_school_classes.rb Outdated
Comment thread db/migrate/20260420104939_backfill_join_code_for_school_classes.rb
Comment thread spec/features/school_class/regenerating_join_code_spec.rb Outdated
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-fgy9p3 May 20, 2026 10:58 Inactive
fspeirs added 3 commits May 20, 2026 13:07
Generate human-readable globally unique class join codes in the
format CVDDCVDD (e.g. CE18LI80) — consonant, vowel, two digits,
twice. The mixed alpha+numeric layout reads cleanly out loud,
limits visual ambiguity (no I/1 or O/0 collisions in the consonant
set), and is short enough to type from memory.

Removes K, X, and Z from the consonant pool to reduce the chance of
generating offensive substrings, and rejects any code whose
consonant-vowel pairs match a small denylist of common offensive
patterns. Generation retries up to 100 times before giving up.
Add a globally unique, regenerable join code to every class. The
code is generated automatically on creation and backfilled for
existing classes. Distinct from the existing per-school code:
join codes are globally unique (so /join/:code can resolve without
a school identifier), are designed to be regeneratable if a class
needs a fresh code, and are surfaced in the school_class JSON
payload for clients that display them.

Two migrations following the existing pattern for the per-school
code field — one to add the column and unique index, one to
backfill existing rows. The backfill skips validations because
existing rows may not satisfy other newer constraints.
Add POST /api/schools/:school_id/classes/:id/regenerate_join_code
so teachers and school owners can rotate a class's join code if
it has been over-shared. The endpoint authorises through CanCan;
both school_owner and school_teacher abilities gain the
regenerate_join_code permission for classes they have access to.
fspeirs and others added 17 commits May 20, 2026 13:07
Add a public predicate that answers whether an email address
belongs to one of the school's allowed domains. Extracts the
domain from the email (after the last '@', stripped and
lowercased) and delegates to the existing valid_domain? lookup
against school_email_domains. Returns false for blank, malformed,
or domain-less inputs.

Lets callers gate behaviour on email domain without having to
parse the address themselves.
Add the student-facing half of the join-code flow: a JSON API the
frontend can call to look up a class from its join code and enroll
the current user. Mirrors the teacher_invitations pattern — backend
is JSON-only, the frontend owns the public URL the user lands on.

GET /api/join/:join_code is unauthenticated and returns
{ status, school, school_class } where status is one of
unauthenticated, joinable, already_member, wrong_school, or
domain_mismatch. The frontend uses status to decide what to show.

POST /api/join/:join_code requires auth and performs enrollment.
On success or for already_member it returns
{ redirect_url } (a locale-less path so the frontend can prepend
the user's current locale); on a forbidden status it returns 403
with the status as the error. Membership creation is idempotent.

The endpoint normalises join codes by uppercasing and stripping
non-alphanumerics, so hyphenated forms like BAFA-1234 from
copy-and-pasted share links resolve to the canonical BAFA1234.
Adds a boolean sso_enabled? to School (true when at least one
school_email_domain exists) and surfaces it through the school
jbuilder partial so the front end can detect JIT-provisioning
schools.
This will ease any concerns about accidentally generating rude words
while also remaining visually distinct from class codes or school codes,
which are DD-DD-DD.
Renames the predicate and the school JSON "sso_enabled" key to
"auto_join_enabled", which describes that the flag reflects class
auto-join eligibility (presence of registered email domains) rather
than SSO.
Teachers and owners of the class's school can now use the join link:

- A teacher already in the class is treated as already_member and
  redirected into the class.
- A teacher of the school not yet in the class gets joinable_as_teacher;
  POST /api/join adds them as a ClassTeacher, then redirects.
- An owner of the school gets the owner status and is redirected into
  the class without being added to it.

Refactors compute_action_status into existing_user_join_status /
new_user_join_status, split on whether the user already has a role in
the school, and renames add_user_to_school_and_class to
add_student_to_school_and_class.
Avoids loading the school_email_domains association into memory when
the method is invoked per-school during JSON rendering.
assign_join_code now caps retries at 5 and adds a validation error on
exhaustion, mirroring assign_class_code so the model can never spin
forever if the code-space is exhausted or the generator is stubbed.

regenerate_join_code! also rescues ActiveRecord::RecordNotUnique once
and retries, so a TOCTOU race against the unique index between the
in-memory uniqueness check and the DB write does not surface as a 500
to the caller.
Wraps role and class-membership creation in a transaction, switches the
check-then-create pattern to find_or_create_by!, and rescues
ActiveRecord::RecordNotUnique so that two simultaneous POSTs to
/api/join/:join_code for the same user no longer surface a 500 when
the DB unique index catches a race that the in-memory existence
checks missed.
The test doesn't require a school owner, just a member.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Adds frozen_string_literal pragma, scopes the backfill to rows with
NULL join_code, retries on RecordNotUnique and validator exhaustion,
and raises a clear error if it cannot find a unique code after
MAX_ATTEMPTS rather than aborting mid-migration with a generic
constraint violation.
ClassStudent#student_has_the_school_student_role_for_the_school only
runs when the #student attr_accessor is set, so find_or_create_by!
without a block silently skipped the invariant. Pass the user via a
block to keep the check live, matching the teacher path. Also rescue
RecordInvalid (when only student_id-taken) for the race between the
in-memory uniqueness validator and the DB unique index.
find_or_create_by! validates before insert. Under contention, the
in-memory uniqueness validator on teacher_id can fire first and raise
RecordInvalid before the DB unique index can raise RecordNotUnique, so
the endpoint must rescue both to remain idempotent.
…code

Returning e.message leaked the 'Validation failed: …' prefix and
inconsistent shape vs. the other actions in this controller, which
return a clean { error: … } payload. Use the model's full_messages
joined to a sentence to keep the API contract uniform.
The before block already authenticates as :teacher, so the previous
two examples exercised the same path. Keep the descriptive one.
@fspeirs fspeirs force-pushed the fs-implement-class-join-codes branch from 198d882 to 35b5567 Compare May 20, 2026 12:07
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-yxye2x May 20, 2026 12:08 Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants