Implement class join codes back-end#789
Open
fspeirs wants to merge 20 commits into
Open
Conversation
Test coverage91.27% line coverage reported by SimpleCov. |
2b3e115 to
bb23e12
Compare
508b98b to
aec7f84
Compare
85e8b32 to
efa9fd2
Compare
8ee18e3 to
931a51f
Compare
Contributor
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.
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.
198d882 to
35b5567
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.