Skip to content

Implement class join codes back-end#789

Merged
fspeirs merged 23 commits into
mainfrom
fs-implement-class-join-codes
May 21, 2026
Merged

Implement class join codes back-end#789
fspeirs merged 23 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.29% line coverage reported by SimpleCov.
Run: https://github.com/RaspberryPiFoundation/editor-api/actions/runs/26231228186

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 Outdated
@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 11 commits May 20, 2026 13:07
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
Comment thread app/controllers/api/join_controller.rb Outdated
Comment thread app/controllers/api/join_controller.rb
Comment thread app/models/school.rb Outdated
Comment thread lib/join_code_generator.rb
Copy link
Copy Markdown
Contributor

@zetter-rpf zetter-rpf left a comment

Choose a reason for hiding this comment

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

This is great work and I can't see anything that won't work.

I've added a few suggestions for improvements but none are required - up to you if they are worth doing.

fspeirs added a commit that referenced this pull request May 21, 2026
Add explicit `when :joinable` and have `else` raise on unknown statuses,
so a future status that isn't routed fails loudly instead of silently
falling through to the student-enrollment path.

Addresses PR #789 review comment from @zetter-rpf.
fspeirs added a commit that referenced this pull request May 21, 2026
The previous name was too generic — it sounded like format/RFC validation
but only checks whether the email's domain is registered against this
school's `SchoolEmailDomain` records.

Addresses PR #789 review comment from @zetter-rpf.
fspeirs added a commit that referenced this pull request May 21, 2026
Move the action_status computation and its supporting predicates out of
JoinController into a dedicated service object. The controller becomes a
thin transport layer that asks the service for a status and routes the
response.

Adds a unit spec covering every returned status (already_member, owner,
joinable_as_teacher, joinable for existing student, not_a_student,
wrong_school, domain_mismatch, joinable for new student with matching
domain), addressing the reviewer's coverage-visibility concern.

Addresses PR #789 review comment from @zetter-rpf.
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-hupiti May 21, 2026 13:55 Inactive
fspeirs added 3 commits May 21, 2026 15:06
Add explicit `when :joinable` and have `else` raise on unknown statuses,
so a future status that isn't routed fails loudly instead of silently
falling through to the student-enrollment path.

Addresses PR #789 review comment from @zetter-rpf.
The previous name was too generic — it sounded like format/RFC validation
but only checks whether the email's domain is registered against this
school's `SchoolEmailDomain` records.

Addresses PR #789 review comment from @zetter-rpf.
Move the action_status computation and its supporting predicates out of
JoinController into a dedicated service object. The controller becomes a
thin transport layer that asks the service for a status and routes the
response.

Adds a unit spec covering every returned status (already_member, owner,
joinable_as_teacher, joinable for existing student, not_a_student,
wrong_school, domain_mismatch, joinable for new student with matching
domain), addressing the reviewer's coverage-visibility concern.

Addresses PR #789 review comment from @zetter-rpf.
@fspeirs fspeirs force-pushed the fs-implement-class-join-codes branch from 043164d to c055342 Compare May 21, 2026 14:08
@fspeirs fspeirs temporarily deployed to editor-api-p-fs-impleme-hupiti May 21, 2026 14:08 Inactive
@fspeirs fspeirs enabled auto-merge (squash) May 21, 2026 14:08
@fspeirs fspeirs merged commit fe67e5c into main May 21, 2026
5 checks passed
@fspeirs fspeirs deleted the fs-implement-class-join-codes branch May 21, 2026 14:11
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.

3 participants