Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

fix: fix a bug

ThieryMichele0998f433010
diff --git a/.claude/scripts/e2e-smoke.sh b/.claude/scripts/e2e-smoke.sh
index 98e42c4c..836f4f64 100755
--- a/.claude/scripts/e2e-smoke.sh
+++ b/.claude/scripts/e2e-smoke.sh
@@ -86,6 +86,9 @@ done
for f in seed.sql signing_keys.json; do
[ -f "$SRC/supabase/$f" ] && cp "$SRC/supabase/$f" "$workdir/supabase/$f"
done
+# Edge functions validate the JWT issuer, which is this slot's API port.
+[ -f "$SRC/supabase/functions/.env" ] && sed "s|^SB_JWT_ISSUER=.*|SB_JWT_ISSUER=http://127.0.0.1:$api_port/auth/v1|" \
+ "$SRC/supabase/functions/.env" > "$workdir/supabase/functions/.env"
if [ "$DRY" = "1" ]; then
echo "DRY-RUN slot=$slot offset=$offset project=$project api_port=$api_port app_port=$app_port workdir=$workdir"
diff --git a/doc/src/content/docs/developers/atomic-crm-api.mdx b/doc/src/content/docs/developers/atomic-crm-api.mdx
index 1cbd5782..1a359ad4 100644
--- a/doc/src/content/docs/developers/atomic-crm-api.mdx
+++ b/doc/src/content/docs/developers/atomic-crm-api.mdx
@@ -65,13 +65,21 @@ You can customize the OpenAPI specification via comments on tables. See the [Pos
Here is a list of the main supabase auth endpoints you are most likely to use for authentication:
-- `POST /auth/v1/signup`: to create a new user and get a JWT token.
+- `POST /auth/v1/signup`: to create the first user of a new instance and get a JWT token. Once a user exists, sign-up is closed: administrators create users from the Users page (see [User Management](../../users/user-management/)).
- `POST /auth/v1/token`: to authenticate a user and get a JWT token. (multiple grant types are supported, check the documentation for more details)
- `POST /auth/v1/logout`: to log out the authenticated user.
- `GET /auth/v1/user`: to get the authenticated user information.
See the [Supabase project's API documentation](https://supabase.com/dashboard/project/_/integrations/data_api/docs?page=users-management) for all the possible endpoints.
+To create a user from a script, first insert the new user's id into the `user_invitations` table with the service role key, then create the user with that same id. Without the invitation, user creation fails with a "Database error saving new user" error:
+
+```ts
+const id = crypto.randomUUID();
+await supabaseAdmin.from("user_invitations").insert({ user_id: id });
+await supabaseAdmin.auth.admin.createUser({ id, email, password });
+```
+
## Data API Endpoints
Here is the list of all the atomic crm specific endpoints:
diff --git a/doc/src/content/docs/users/user-management.mdx b/doc/src/content/docs/users/user-management.mdx
index dca107a6..1de9f4ee 100644
--- a/doc/src/content/docs/users/user-management.mdx
+++ b/doc/src/content/docs/users/user-management.mdx
@@ -17,3 +17,5 @@ Note: If the application is connected to the production database, the first user
Any user with the administrator role can create new users. To do this, click on the avatar in the top right corner and select 'Users'. From this page, you can add new users, edit existing users, and delete users.
![Adding users](../../images/adding-users.png "Adding users")
+
+Once the first user exists, public sign-up is closed. The Users page is the only way to add users, except for [SAML SSO](../../developers/sso/) users, who are created on their first login. Users added from the Supabase dashboard (_Authentication > Users > Add user_ or _Invite user_), or by a script calling `auth.admin.createUser`, are rejected with a "Database error saving new user" error. To create users from a script, see [Auth API Endpoints](../../developers/atomic-crm-api/#auth-api-endpoints).
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index 421ad277..b67fdad1 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -41,7 +41,17 @@ async function createUser({
email: string;
password: string;
}) {
+ const id = crypto.randomUUID();
+ const { error: invitationError } = await adminSupabase
+ .from("user_invitations")
+ .insert({ user_id: id });
+
+ if (invitationError) {
+ throw new Error(`Failed to create user: ${invitationError.message}`);
+ }
+
const { data, error } = await adminSupabase.auth.admin.createUser({
+ id,
email,
password,
email_confirm: true,
@@ -67,21 +77,12 @@ async function createSales({
password: string;
administrator?: boolean;
}) {
- const { data: userData, error: userError } =
- await adminSupabase.auth.admin.createUser({
- email,
- password,
- email_confirm: true,
- });
-
- if (userError) {
- throw new Error(`Failed to create sales: ${userError.message}`);
- }
+ const user = await createUser({ email, password });
const { data, error } = await adminSupabase
.from("sales")
.update({ first_name, last_name, administrator })
- .eq("user_id", userData.user?.id)
+ .eq("user_id", user.id)
.select()
.single();
diff --git a/e2e/signup.spec.ts b/e2e/signup.spec.ts
new file mode 100644
index 00000000..93b461a6
--- /dev/null
+++ b/e2e/signup.spec.ts
@@ -0,0 +1,52 @@
+import { createClient } from "@supabase/supabase-js";
+import { test, expect } from "./fixtures";
+
+test("only the first user can sign up", async ({ createUser }) => {
+ await createUser({ email: "[email protected]", password: "password" });
+
+ const supabase = createClient(
+ process.env.VITE_SUPABASE_URL ?? "http://127.0.0.1:54341",
+ process.env.VITE_SB_PUBLISHABLE_KEY!,
+ { auth: { persistSession: false } },
+ );
+ const { error } = await supabase.auth.signUp({
+ email: "[email protected]",
+ password: "password",
+ });
+
+ expect(error).not.toBeNull();
+});
+
+test("an administrator can still create users", async ({
+ page,
+ isMobile,
+ createSales,
+}) => {
+ test.skip(isMobile, "User management is only available on desktop");
+
+ await createSales({
+ administrator: true,
+ email: "[email protected]",
+ first_name: "John",
+ last_name: "Doe",
+ password: "password",
+ });
+
+ await page.goto("/");
+ await page.getByLabel("Email").fill("[email protected]");
+ await page.getByLabel("Password").fill("password");
+ await page.getByRole("button", { name: "Sign in" }).click();
+ await expect(page.getByRole("link", { name: "Dashboard" })).toBeVisible();
+
+ await page.goto("/sales");
+ await page.getByRole("link", { name: "New user" }).click();
+ await page.getByLabel("First name").fill("Marie");
+ await page.getByLabel("Last name").fill("Curie");
+ await page.getByLabel("Email").fill("[email protected]");
+ await page.getByRole("button", { name: "Save" }).click();
+
+ await expect(page.getByText(/^User created/)).toBeVisible();
+ await expect(
+ page.getByRole("cell", { name: "[email protected]" }),
+ ).toBeVisible();
+});
diff --git a/makefile b/makefile
index a47b2ce2..39c08691 100644
--- a/makefile
+++ b/makefile
@@ -68,6 +68,8 @@ start-supabase-e2e: ## start a separate supabase instance for e2e (fresh DB ever
cp -r supabase/migrations .supabase-e2e/supabase/migrations
cp -r supabase/schemas .supabase-e2e/supabase/schemas
cp -r supabase/functions .supabase-e2e/supabase/functions
+ # edge functions validate the JWT issuer, which is the e2e API port here
+ sed 's|^SB_JWT_ISSUER=.*|SB_JWT_ISSUER=http://127.0.0.1:54341/auth/v1|' supabase/functions/.env > .supabase-e2e/supabase/functions/.env
cp -r supabase/templates .supabase-e2e/supabase/templates
cp supabase/seed.sql .supabase-e2e/supabase/seed.sql
cp supabase/signing_keys.json .supabase-e2e/supabase/signing_keys.json
diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.ts
index 76491d77..8759d1a6 100644
--- a/supabase/functions/users/index.ts
+++ b/supabase/functions/users/index.ts
@@ -145,7 +145,18 @@ async function inviteUser(req: Request, currentUserSale: any) {
);
}
+ const id = crypto.randomUUID();
+ const { error: invitationError } = await supabaseAdmin
+ .from("user_invitations")
+ .insert({ user_id: id });
+
+ if (invitationError) {
+ console.error(`Error inviting user: invitation_error=${invitationError}`);
+ return createErrorResponse(500, "Internal Server Error");
+ }
+
const { data, error: userError } = await supabaseAdmin.auth.admin.createUser({
+ id,
email,
password,
user_metadata: { first_name, last_name },
diff --git a/supabase/migrations/20261030125021_user_invitations.sql b/supabase/migrations/20261030125021_user_invitations.sql
new file mode 100644
index 00000000..6f2e0b59
--- /dev/null
+++ b/supabase/migrations/20261030125021_user_invitations.sql
@@ -0,0 +1,45 @@
+create table "public"."user_invitations" (
+ "user_id" uuid not null
+);
+
+alter table "public"."user_invitations" enable row level security;
+
+CREATE UNIQUE INDEX user_invitations_pkey ON public.user_invitations USING btree (user_id);
+
+alter table "public"."user_invitations" add constraint "user_invitations_pkey" PRIMARY KEY using index "user_invitations_pkey";
+
+revoke all on table "public"."user_invitations" from "anon", "authenticated";
+
+grant all on table "public"."user_invitations" to "service_role";
+
+set check_function_bodies = off;
+
+CREATE OR REPLACE FUNCTION public.handle_new_user()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+declare
+ sales_count int;
+begin
+ select count(id) into sales_count
+ from public.sales;
+
+ delete from public.user_invitations where user_id = new.id;
+ if sales_count > 0 and not found and not new.is_sso_user then
+ raise exception 'Sign up is not allowed';
+ end if;
+
+ insert into public.sales (first_name, last_name, email, user_id, administrator)
+ values (
+ coalesce(new.raw_user_meta_data ->> 'first_name', new.raw_user_meta_data -> 'custom_claims' ->> 'first_name', 'Pending'),
+ coalesce(new.raw_user_meta_data ->> 'last_name', new.raw_user_meta_data -> 'custom_claims' ->> 'last_name', 'Pending'),
+ new.email,
+ new.id,
+ case when sales_count > 0 then FALSE else TRUE end
+ );
+ return new;
+end;
+$function$
+;
diff --git a/supabase/schemas/01_tables.sql b/supabase/schemas/01_tables.sql
index 8b64819f..1ec17b7f 100644
--- a/supabase/schemas/01_tables.sql
+++ b/supabase/schemas/01_tables.sql
@@ -132,6 +132,10 @@ create table public.favicons_excluded_domains (
domain text not null
);
+create table public.user_invitations (
+ user_id uuid primary key
+);
+
--
-- Foreign keys
--
diff --git a/supabase/schemas/02_functions.sql b/supabase/schemas/02_functions.sql
index 0d9fc0a0..646a55a9 100644
--- a/supabase/schemas/02_functions.sql
+++ b/supabase/schemas/02_functions.sql
@@ -238,6 +238,11 @@ begin
select count(id) into sales_count
from public.sales;
+ delete from public.user_invitations where user_id = new.id;
+ if sales_count > 0 and not found and not new.is_sso_user then
+ raise exception 'Sign up is not allowed';
+ end if;
+
insert into public.sales (first_name, last_name, email, user_id, administrator)
values (
coalesce(new.raw_user_meta_data ->> 'first_name', new.raw_user_meta_data -> 'custom_claims' ->> 'first_name', 'Pending'),
diff --git a/supabase/schemas/05_policies.sql b/supabase/schemas/05_policies.sql
index 9be5ab2c..cb2a41a2 100644
--- a/supabase/schemas/05_policies.sql
+++ b/supabase/schemas/05_policies.sql
@@ -14,6 +14,7 @@ alter table public.tags enable row level security;
alter table public.tasks enable row level security;
alter table public.configuration enable row level security;
alter table public.favicons_excluded_domains enable row level security;
+alter table public.user_invitations enable row level security;
-- Companies
create policy "Enable read access for authenticated users" on public.companies for select to authenticated using (true);
diff --git a/supabase/schemas/06_grants.sql b/supabase/schemas/06_grants.sql
index 02945a58..a4c2b523 100644
--- a/supabase/schemas/06_grants.sql
+++ b/supabase/schemas/06_grants.sql
@@ -106,6 +106,9 @@ grant all on table public.favicons_excluded_domains to anon;
grant all on table public.favicons_excluded_domains to authenticated;
grant all on table public.favicons_excluded_domains to service_role;
+revoke all on table public.user_invitations from anon, authenticated;
+grant all on table public.user_invitations to service_role;
+
-- View grants
grant all on table public.activity_log to anon;
grant all on table public.activity_log to authenticated;