13 KiB
created_date, last_modified_date, last_modified_summary
| created_date | last_modified_date | last_modified_summary |
|---|---|---|
| 2025-06-05 | 2025-08-25 | Document password reset (recovery) flow and production redirect configuration |
🔐 Authentication System Detailed Guide
This document provides a comprehensive overview of the authentication and user profile management system in this application. It leverages Supabase for backend services and Zustand for client-side state management.
1. Core Technologies
- Supabase Auth: Provides secure user authentication (email/password, social logins if configured), JWT-based session management, and user identity storage in the
auth.userstable. - Supabase Database (PostgreSQL): Hosts the
public.profilestable, which stores additional user information beyond whatauth.usersprovides. - Next.js Middleware: Used for protecting routes at the edge, redirecting unauthenticated users.
- Zustand: For managing global client-side authentication state (user, session, profile, loading status).
- TypeScript: Ensures type safety throughout the authentication flow and data handling.
2. Authentication Flow
2.1. User Sign-Up
- User provides email and password.
- The
signUpmethod insrc/store/auth.tsis called. supabase.auth.signUp()is invoked:- Creates a new user in the
auth.userstable. - Sends a confirmation email (if email confirmations are enabled in Supabase).
- Creates a new user in the
- Profile Creation: Immediately after successful sign-up in
auth.users, thesignUpmethod insrc/store/auth.tsalso:- Constructs a new profile object.
- Populates initial fields:
id: Matches theauth.users.id.username: Derived from the email prefix.display_name: Also derived from the email prefix.avatar_url:nullby default.bio:nullby default.bitcoin_address:nullby default.created_at&updated_at: Current timestamp.
- Inserts this new record into the
public.profilestable.
- The
onAuthStateChangelistener insrc/store/auth.tswill eventually fire with aSIGNED_INevent (orUSER_ADDEDdepending on Supabase config), triggering a profile fetch and state update.
2.2. User Log-In
- User provides email and password.
- The
signInmethod insrc/store/auth.tsis called. supabase.auth.signInWithPassword()is invoked.- Supabase validates credentials and, if successful, establishes a session and issues a JWT.
- The
onAuthStateChangelistener insrc/store/auth.tsfires with aSIGNED_INevent. - The listener updates the Zustand store with the
userandsessionobjects. - It then asynchronously fetches the user's corresponding profile from the
public.profilestable using theuser.id. - The fetched
profiledata is also updated in the Zustand store. - Client-side UI reacts to the updated state (e.g., redirecting to a dashboard, showing user-specific content).
2.3. User Log-Out
- User initiates logout (e.g., clicks a logout button).
- The
signOutmethod insrc/store/auth.tsis called. supabase.auth.signOut()is invoked.- Supabase invalidates the current session and clears relevant auth cookies/storage.
- The
onAuthStateChangelistener insrc/store/auth.tsfires with aSIGNED_OUTevent. - The listener clears
user,session, andprofiledata in the Zustand store. - UI reacts, typically redirecting to a public page (e.g., homepage or login page).
2.4. Session Management & Route Protection
- Next.js Middleware (
src/middleware.ts):- Intercepts requests to protected routes.
- Uses
@supabase/ssr'screateServerClientto check for a valid session from cookies. - If no session, redirects to
/auth. - Handles sign-out URL (
/auth/signout).
- Client-Side Hooks (
src/hooks/useAuth.ts):useRequireAuth(): For client-side components/pages. If no authenticated user (after hydration), redirects to/auth.useRedirectIfAuthenticated(): If an authenticated user visits a page like/auth, redirects them to/dashboard.
- Zustand Store Hydration:
- The store is persisted to
localStorage. - On app load, the
onAuthStateChangelistener (withINITIAL_SESSIONevent) and persisted state help rehydrate the auth status quickly. hydratedandisLoadingflags in the store are crucial for UI to prevent flicker and show appropriate loading states.
- The store is persisted to
2.5. Password Reset (Recovery) Flow
- Initiation:
resetPassword({ email })insrc/services/supabase/auth/index.tscallssupabase.auth.resetPasswordForEmail(email, { redirectTo }).redirectTomust be a fully-qualified URL to the reset page, e.g.,https://www.orangecat.ch/auth/reset-password.- In production,
NEXT_PUBLIC_SITE_URLmust be set to the canonical domain used in Supabase (see configuration below). The service constructsredirectToas${NEXT_PUBLIC_SITE_URL}/auth/reset-password.
- Email: Supabase generates
{{ .ConfirmationURL }}which includes the tokens (often in the URL hash fragment) and sends it using our templatesupabase/templates/recovery.html. - Redirect handling:
- For valid links, Supabase should redirect directly to
/auth/reset-passwordon the same domain asredirectTo. - For expired/invalid links, Supabase may fall back to the configured
site_urlroot and append error query parameters (e.g.,?error=access_denied&error_code=otp_expired). - Middleware at
src/middleware.tsnow preserves such error parameters and redirects from/to/auth/reset-password, keeping both query and any client-side hash intact (when available in the browser).
- For valid links, Supabase should redirect directly to
- Reset page:
src/app/auth/reset-password/page.tsxmerges tokens from both query string and hash fragment, then callssupabase.auth.setSession({ access_token, refresh_token })before allowing the password update.
Configuration requirements (Production):
- Supabase Project Settings → Authentication → URL Configuration:
- Set
site_urlto the canonical domain (choose one):https://www.orangecat.chorhttps://orangecat.ch. - Add ALL of the following to Additional Redirect URLs (exact match required):
https://www.orangecat.ch/auth/reset-passwordhttps://orangecat.ch/auth/reset-password- (Optional for dev):
http://localhost:3000/auth/reset-password
- Set
- Vercel (or hosting) Environment Variables:
- Set
NEXT_PUBLIC_SITE_URLto the SAME canonical domain used forsite_urlabove (e.g.,https://www.orangecat.ch). - This ensures the
redirectTogenerated server-side matches the allow-list in Supabase exactly.
- Set
- Notes:
- If
redirectTois not exactly on the allow-list, Supabase will reject it and fall back tosite_urlwith error parameters, causing a redirect to the homepage. - Browsers do not send URL hash fragments to the server. Our client page reads both query and hash; middleware can only act on query params.
- If
3. State Management (src/store/auth.ts)
useAuthStore(Zustand): Single source of truth for client-side authentication state.user: User | null: The SupabaseUserobject.session: Session | null: The SupabaseSessionobject.profile: Profile | null: The user's custom profile data from theprofilestable (typed byProfilefromsrc/types/database.ts).isLoading: boolean: Indicates if an auth operation or profile fetch is in progress.hydrated: boolean: Indicates if the store has been rehydrated fromlocalStorageand initial session check is complete.isAdmin: boolean: Derived fromuser?.app_metadata?.role.error: string | null: Stores any error messages from auth operations.
onAuthStateChangeListener:- Listens to Supabase auth events (
SIGNED_IN,SIGNED_OUT,USER_UPDATED,INITIAL_SESSION, etc.). - Updates the store accordingly, including fetching/clearing the user profile.
- This is the primary mechanism for keeping the client-side state in sync with Supabase's auth state.
- Listens to Supabase auth events (
4. User Profiles
4.1. Profile Data Structure
The structure of user profiles is defined by the Profile interface in src/types/database.ts. This should mirror the schema of the public.profiles table in Supabase.
// From: src/types/database.ts
export interface Profile {
id: string; // Primary key, matches auth.users.id
username?: string | null;
display_name: string | null;
avatar_url?: string | null;
bio: string | null;
bitcoin_address: string | null;
created_at: string; // ISO timestamp
updated_at: string; // ISO timestamp
}
4.2. Link to auth.users
- The
profiles.idcolumn is the primary key and is a foreign key referencingauth.users.id. This establishes a one-to-one relationship.
4.3. Profile Creation and Updates
- Creation: As detailed in the "User Sign-Up" flow, a profile is automatically created in
public.profileswhen a new user signs up viasrc/store/auth.ts. - Updates:
- Users can update their profile information through UI elements.
- The
updateProfilemethod insrc/store/auth.tsis called. - This method, in turn, may call
ProfileService.updateProfile(or directly use the Supabase client as it currently does). - The service/store updates the relevant row in the
public.profilestable using the user's ID. - After a successful update, the local
profilestate in the Zustand store is also updated.
5. Database Interaction (public.profiles Table)
- Schema Consistency: It is critical that the columns and data types in your
public.profilestable in Supabase exactly match theProfileinterface insrc/types/database.ts. Mismatches will lead to runtime errors. - Row Level Security (RLS):
- RLS should be enabled on the
public.profilestable. - Recommended Policies:
- Users can only select their own profile:
CREATE POLICY "Enable read access for own user" ON public.profiles FOR SELECT USING (auth.uid() = id); - Users can only update their own profile:
CREATE POLICY "Enable update access for own user" ON public.profiles FOR UPDATE USING (auth.uid() = id) WITH CHECK (auth.uid() = id); - Profile creation is handled by the application logic after user sign-up (often using service_role key implicitly via
supabase.auth.signUpcontext or explicit service client if profile creation is separate and secured). For client-side initiated profile inserts linked to new users, ensure the RLS policy for INSERT allows it only ifidmatchesauth.uid().CREATE POLICY "Enable insert for own user" ON public.profiles FOR INSERT WITH CHECK (auth.uid() = id);
- Users can only select their own profile:
- RLS should be enabled on the
5.1. Cascading Deletes (Important Setup)
By default, deleting a user from auth.users (e.g., via Supabase dashboard or admin SDK) will not automatically delete their corresponding row in public.profiles. This leaves orphaned profile data.
To enable automatic cascading deletes:
-
Create a Database Function: Execute this in the Supabase SQL Editor:
CREATE OR REPLACE FUNCTION public.handle_user_delete() RETURNS TRIGGER AS $$ BEGIN DELETE FROM public.profiles WHERE id = OLD.id; -- OLD.id refers to the id of the user being deleted RETURN OLD; END; $$ LANGUAGE plpgsql SECURITY DEFINER;(Note:
SECURITY DEFINERallows the function to run with the permissions of the user who defined it, which is necessary to delete frompublic.profilesif restrictive RLS is in place for the calling user.) -
Create a Trigger on
auth.users: Execute this in the Supabase SQL Editor:CREATE TRIGGER on_auth_user_deleted AFTER DELETE ON auth.users FOR EACH ROW EXECUTE FUNCTION public.handle_user_delete();This ensures that whenever a user is deleted from
auth.users, their associated profile inpublic.profilesis also deleted.
6. Key Files & Responsibilities
src/store/auth.ts: Central Zustand store for auth state, sign-in/up/out methods,onAuthStateChangelistener.src/types/database.ts: Defines theProfileinterface (andProfileFormData). Single source of truth for profile structure.src/hooks/useAuth.ts: Provides convenient hooks (useAuth,useRequireAuth,useRedirectIfAuthenticated) for accessing auth state and managing route protection on the client side.src/middleware.ts: Next.js middleware for edge-based route protection.src/services/profileService.ts: Class-based service for profile-related database operations (though some operations are currently direct in the store).src/services/supabase/client.ts: Exports the Supabase browser client instance and some helper functions.src/services/supabase/profiles.ts: Contains additional direct Supabase query functions for profiles.docs/auth_system.md(this file): Detailed documentation.
7. Maintainability & Best Practices
- Type Safety: The unified
Profiletype is crucial. Ensure it always reflects the database schema. - RLS: Keep Row Level Security policies on Supabase tables strict and well-tested.
- Error Handling: Ensure robust error handling in async operations within the store and services.
- Single Responsibility: Consider refining services so that
ProfileService.tsbecomes the sole handler of all directprofilestable interactions, which the store would then use. - Keep Documentation Updated: As the authentication system evolves, update this document.
This detailed guide should help current and future developers understand the intricacies of the authentication system.