Implement class join codes back-end#789
Conversation
Test coverage91.29% line coverage reported by SimpleCov. |
2b3e115 to
bb23e12
Compare
508b98b to
aec7f84
Compare
85e8b32 to
efa9fd2
Compare
8ee18e3 to
931a51f
Compare
There was a problem hiding this comment.
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_codetoSchoolClasswith generation/normalization viaJoinCodeGenerator, plus backfill for existing records. - Introduce
/api/join/:join_code(GET/POST) with status-driven responses and enrollment behavior. - Add
regenerate_join_codeendpoint + CanCan ability, and exposejoin_code/auto_join_enabledin 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.
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.
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.
198d882 to
35b5567
Compare
zetter-rpf
left a comment
There was a problem hiding this comment.
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.
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.
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.
043164d to
c055342
Compare
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 ashow.json.builderwith 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 inaction_status.Another feature of
JoinController#showis 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
Schoolto 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
JoinCodeGeneratorwhich produces the codes in the first place.Changes
join_codecolumn with a unique index toschool_classes, plus a backfill migration for existing classes.JoinCodeGeneratorwith.generateand.normalize(canonicalises user input to the hyphenated form for DB lookup).SchoolClasscreate/import with a uniqueness retry, plus aregenerate_join_code!helper.GET /api/join/:join_codereturning the prospective user's status. The full set of statuses is:unauthenticated— no current userjoinable— the user can be enrolled as a studentjoinable_as_teacher— the user already has a teacher role for this school and will be added to the class as a teacherowner— the user owns this school; treated as already a member for redirect purposesalready_member— the user is already a member of this classwrong_school— the user has a role in a different schooldomain_mismatch— the user's email domain is not registered for this schoolnot_a_student— the user has a non-student role elsewherePOST /api/join/:join_codeto enrol the current user as a student (or teacher, ifjoinable_as_teacher) of the school and class.POST /api/schools/:school_id/classes/:id/regenerate_join_code(nested under the existingschool_classesresource).join_codeon the school class JSONSchool#valid_email?(built on Store school email domains #787's domain validation) for thedomain_mismatchcheck.School#auto_join_enabled?to allow the front end to prompt users correctly about the requirements for auto-join.regenerate_join_code.