BetterAuth Integration Summary
Overview
The authentication system uses BetterAuth for centralized identity management. This provides better ownership of user data, consistent session management across web and mobile, and more flexible authentication flows.What Was Implemented
1. Auth Client (frontend/astro/apps/platform/src/lib/auth.ts)
- Initialization: Configured
better-auth/clientwithbaseURL: "/api/auth". - Plugins: Enabled
anonymousClient,adminClient, andorganizationClient. - Enhanced Utilities:
- Auth Methods:
signUp,signIn,signOut,getSessionwrapped intry-catch. - Admin Management: Added
adminCreateUser,adminSetRole, andadminRemoveUserfor platform administration. - Organization Management: Added
createOrganization,inviteMember,updateMemberRole, andremoveMemberutilities. - Error Mapping: Centralized
mapAuthErrorfunction converts BetterAuth/Network errors into user-friendly messages. - Logging: Server-side error logging enabled using
import.meta.env.SSR. - Network Resilience: Handles fetch failures and timeouts gracefully.
- Auth Methods:
2. Role Structure
- Platform Roles:
user,admin,superadmin(stored in the mainusertable). - Organization Roles:
owner,admin,staff,member,viewer(stored in the multi-tenantmembertable). - Middleware: Correctly exposes both
hasRole(platformRole)andhasOrgRole(orgRole)helpers viaAstro.locals.auth.
3. Authenticated API Client (frontend/astro/apps/platform/src/lib/api.ts)
- 401 Retry Logic: Automatic session refresh when a
401 Unauthorizedis encountered. - Global Helper: Centralized headers management supporting both client-side and SSR contexts.
- Domain Methods: Restored all leave management methods (
getLeaveBalances,createLeaveRequest, etc.) using the authenticated wrapper.
3. Middleware & SSR Auth (frontend/astro/apps/platform/src/middleware.ts)
- Session Validation: Uses
BETTER_AUTH_SECRETto validate thebetter-auth.session_tokencookie. - Local Context: Populates
Astro.locals.authwith user metadata if a valid session exists. - Protected Routes: Logic implemented to redirect unauthenticated users from
/dashboard/*to/sign-in.
4. UI Components Integration
- Auth Forms:
SignUpForm.tsx,SignInForm.tsx, andSignInAnonymous.tsxupdated to use the newauthClient. - Session Sync: Implemented client-side sync in
AppLayout.astroto ensure the session token is available inwindow.__BETTER_AUTH_TOKEN__for SPA requests.
How It Works (401 Retry Flow)
Environment Variables Required
| Variable | Description | Location |
|---|---|---|
PUBLIC_API_URL | Root URL for the backend API | .env |
BETTER_AUTH_SECRET | Secret key for JWT signing | .env.local |
BETTER_AUTH_URL | The public URL of the frontend | .env.local |