-
Notifications
You must be signed in to change notification settings - Fork 0
Phase B: session resolves and carries the active organization #49
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
dea0978
step B1: org module skeleton (resolveActiveOrg, listOrgMemberships)
Bonobo791 c171f57
step B2: session resolves and carries the active organization
Bonobo791 d9f892e
step B3: session tenancy tests (org resolution, fallback, repair, zer…
Bonobo791 fede1c1
step B4: (app) layout exposes the user's org list
Bonobo791 9f565ce
fix: phase B review — deterministic org ordering, honest fellBack
Bonobo791 a43eda6
fix: phase B review — signup personal org, deduped membership query, …
Bonobo791 1f7582b
fix: phase A/B review — erase tenancy (org, memberships, invites) on …
Bonobo791 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| // Moderaty — YouTube Comment Auto-Moderation Tool | ||
| // Copyright (C) 2026 Andrew Philip Weilbacher | ||
| // | ||
| // This program is free software: you can redistribute it and/or modify | ||
| // it under the terms of the GNU Affero General Public License as published | ||
| // by the Free Software Foundation, either version 3 of the License, or | ||
| // (at your option) any later version. | ||
| // | ||
| // This program is distributed in the hope that it will be useful, | ||
| // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| // GNU Affero General Public License for more details. | ||
| // | ||
| // You should have received a copy of the GNU Affero General Public License | ||
| // along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
| // | ||
| // Commercial licensing: contact@marketingprowess.simplelogin.com — see COMMERCIAL.md | ||
|
|
||
| import { expect, test } from 'vitest'; | ||
|
|
||
| import { setupTestDb, testDb } from './testdb'; | ||
| import { memberships, organizations, users } from './db/schema'; | ||
| import { listOrgMemberships, resolveActiveOrg } from './org'; | ||
|
|
||
| // Phase D adds the team-management behavior tests to this file; these cover | ||
| // the session-resolution core shipped in Phase B. | ||
| setupTestDb(['memberships', 'organizations', 'users']); | ||
|
|
||
| async function seedUserWithOrgs(userId: string, orgIds: string[], createdAt: string) { | ||
| await testDb() | ||
| .db.insert(users) | ||
| .values({ id: userId, googleSub: `sub-${userId}`, email: `${userId}@example.com`, displayName: userId }); | ||
| for (const orgId of orgIds) { | ||
| await testDb().db.insert(organizations).values({ id: orgId, name: orgId }); | ||
| await testDb().db.insert(memberships).values({ userId, orgId, role: 'member', createdAt }); | ||
| } | ||
| } | ||
|
|
||
| test('memberships tying on created_at resolve deterministically, consistently with the org list', async () => { | ||
| // PR #49 review (Qodo/Codacy): "oldest membership" must be a total order — | ||
| // a timestamp tie (batched inserts) must not let the active org flip with | ||
| // undefined DB row order. Tie-break is org id, and the nav list must agree. | ||
| // Inserted b-first on purpose: insertion order must NOT decide the winner. | ||
| await seedUserWithOrgs('user-1', ['org-b', 'org-a'], '2026-01-01T00:00:00.000Z'); | ||
|
|
||
| const resolved = await resolveActiveOrg('user-1', null); | ||
| expect(resolved?.org.orgId).toBe('org-a'); | ||
|
|
||
| const list = await listOrgMemberships('user-1'); | ||
| expect(list.map((o) => o.orgId)).toEqual(['org-a', 'org-b']); | ||
| }); | ||
|
|
||
| test('fellBack is false when the session had no explicit active org', async () => { | ||
| // PR #49 review (Qodo): fellBack means "an explicit org choice became | ||
| // invalid" — a null active_org_id is the ordinary fresh-login case, not a | ||
| // fallback. | ||
| await seedUserWithOrgs('user-1', ['org-a'], '2026-01-01T00:00:00.000Z'); | ||
|
|
||
| const fresh = await resolveActiveOrg('user-1', null); | ||
| expect(fresh?.fellBack).toBe(false); | ||
|
|
||
| const vanished = await resolveActiveOrg('user-1', 'org-gone'); | ||
| expect(vanished?.fellBack).toBe(true); | ||
| expect(vanished?.org.orgId).toBe('org-a'); | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| // Moderaty — YouTube Comment Auto-Moderation Tool | ||
| // Copyright (C) 2026 Andrew Philip Weilbacher | ||
| // | ||
| // This program is free software: you can redistribute it and/or modify | ||
| // it under the terms of the GNU Affero General Public License as published | ||
| // by the Free Software Foundation, either version 3 of the License, or | ||
| // (at your option) any later version. | ||
| // | ||
| // This program is distributed in the hope that it will be useful, | ||
| // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| // GNU Affero General Public License for more details. | ||
| // | ||
| // You should have received a copy of the GNU Affero General Public License | ||
| // along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
| // | ||
| // Commercial licensing: contact@marketingprowess.simplelogin.com — see COMMERCIAL.md | ||
|
|
||
| // DIY organization tenancy — no auth library, per the project's dependency policy. | ||
|
|
||
| import { randomBytes } from 'node:crypto'; | ||
|
|
||
| import { eq } from 'drizzle-orm'; | ||
|
|
||
| import { db } from '$lib/server/db'; | ||
| import { memberships, organizations } from '$lib/server/db/schema'; | ||
|
|
||
| export type OrgRole = 'owner' | 'admin' | 'member'; | ||
|
|
||
| export interface OrgContext { | ||
| orgId: string; | ||
| orgName: string; | ||
| orgRole: OrgRole; | ||
| plan: string; | ||
| } | ||
|
|
||
| /** Narrows a raw memberships.role string to OrgRole, failing loudly on data bugs. */ | ||
| export function asOrgRole(role: string): OrgRole { | ||
| if (role === 'owner' || role === 'admin' || role === 'member') return role; | ||
| throw new Error(`unknown membership role: ${role}`); | ||
| } | ||
|
|
||
| /** All of a user's memberships joined to their orgs, oldest membership first (ties by org id), in SQL. */ | ||
| async function fetchMembershipRows(userId: string) { | ||
| return db | ||
| .select({ | ||
| orgId: organizations.id, | ||
| orgName: organizations.name, | ||
| plan: organizations.plan, | ||
| role: memberships.role, | ||
| membershipCreatedAt: memberships.createdAt | ||
| }) | ||
| .from(memberships) | ||
| .innerJoin(organizations, eq(memberships.orgId, organizations.id)) | ||
| .where(eq(memberships.userId, userId)) | ||
| .orderBy(memberships.createdAt, memberships.orgId) | ||
| .all(); | ||
| } | ||
|
|
||
| /** | ||
| * Resolves a user's active organization: the session's active_org_id when a | ||
| * membership for it still exists, otherwise the user's OLDEST membership | ||
| * (deterministic fallback — timestamp ties break by org id, in SQL). Returns | ||
| * null only when the user has zero memberships — a data bug the caller must | ||
| * treat as fatal, never as signed-out. `fellBack` is true only when an | ||
| * explicit activeOrgId was supplied and no longer has a membership. | ||
| */ | ||
| export async function resolveActiveOrg( | ||
| userId: string, | ||
| activeOrgId: string | null | ||
| ): Promise<{ org: OrgContext; fellBack: boolean } | null> { | ||
| const rows = await fetchMembershipRows(userId); | ||
| if (rows.length === 0) return null; | ||
| const chosen = rows.find((r) => r.orgId === activeOrgId) ?? rows[0]; | ||
| return { | ||
| org: { orgId: chosen.orgId, orgName: chosen.orgName, orgRole: asOrgRole(chosen.role), plan: chosen.plan }, | ||
| fellBack: activeOrgId !== null && chosen.orgId !== activeOrgId | ||
| }; | ||
| } | ||
|
|
||
| /** Every org the user belongs to, oldest membership first (ties by org id) — feeds the nav team switcher. */ | ||
| export async function listOrgMemberships(userId: string) { | ||
| const rows = await fetchMembershipRows(userId); | ||
| return rows.map(({ orgId, orgName, role }) => ({ orgId, name: orgName, role: asOrgRole(role) })); | ||
| } | ||
|
|
||
| /** | ||
| * Returns the id of the user's personal org, creating it (plus the owner | ||
| * membership) when missing. Naming matches the 0012 backfill (the user's | ||
| * display name). Idempotent per I4: a concurrent same-sub signup that lost | ||
| * the user-insert race finds the org the winner already made. Callers that | ||
| * must commit atomically with other writes (account creation) pass their | ||
| * transaction as `handle`. | ||
| */ | ||
| export async function ensurePersonalOrg( | ||
| handle: Pick<typeof db, 'insert' | 'select'>, | ||
| user: { id: string; displayName: string } | ||
| ): Promise<string> { | ||
| const existing = await handle | ||
| .select({ id: organizations.id }) | ||
| .from(organizations) | ||
| .where(eq(organizations.personalFor, user.id)) | ||
| .get(); | ||
| if (existing) return existing.id; | ||
| const orgId = randomBytes(16).toString('hex'); | ||
| await handle.insert(organizations).values({ id: orgId, name: user.displayName, personalFor: user.id }); | ||
| await handle.insert(memberships).values({ userId: user.id, orgId, role: 'owner' }); | ||
| return orgId; | ||
| } | ||
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.