feat: add organization onboarding flow and auth enforcement
This commit is contained in:
46
lib/api/organization.ts
Normal file
46
lib/api/organization.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import apiRequest from './client'
|
||||
|
||||
export interface Organization {
|
||||
id: string
|
||||
name: string
|
||||
slug: string
|
||||
role: 'owner' | 'admin' | 'member'
|
||||
joined_at: string
|
||||
}
|
||||
|
||||
export interface OrganizationMember {
|
||||
organization_id: string
|
||||
user_id: string
|
||||
role: string
|
||||
joined_at: string
|
||||
organization_name: string
|
||||
organization_slug: string
|
||||
}
|
||||
|
||||
// * Fetch user's organizations
|
||||
export async function getUserOrganizations(): Promise<{ organizations: OrganizationMember[] }> {
|
||||
// * Route to Auth Service
|
||||
// * Note: The client.ts prepends /api/v1, but the auth service routes are /api/v1/auth/organizations
|
||||
// * We need to be careful with the prefix.
|
||||
// * client.ts: if endpoint starts with /auth, it uses AUTH_API_URL + /api/v1 + endpoint
|
||||
// * So if we pass /auth/organizations, it becomes AUTH_API_URL/api/v1/auth/organizations
|
||||
// * This matches the router group in main.go: v1.Group("/auth").Group("/organizations")
|
||||
return apiRequest<{ organizations: OrganizationMember[] }>('/auth/organizations')
|
||||
}
|
||||
|
||||
// * Create a new organization
|
||||
export async function createOrganization(name: string, slug: string): Promise<Organization> {
|
||||
return apiRequest<Organization>('/auth/organizations', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, slug }),
|
||||
})
|
||||
}
|
||||
|
||||
// * Switch context to organization (returns new token)
|
||||
export async function switchContext(organizationId: string): Promise<{ token: string, refresh_token: string }> {
|
||||
// * Route in main.go is /api/v1/auth/switch-context
|
||||
return apiRequest<{ token: string, refresh_token: string }>('/auth/switch-context', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ organization_id: organizationId }),
|
||||
})
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
'use client'
|
||||
|
||||
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useRouter, usePathname } from 'next/navigation'
|
||||
import apiRequest from '@/lib/api/client'
|
||||
import LoadingOverlay from '@/components/LoadingOverlay'
|
||||
import { logoutAction, getSessionAction } from '@/app/actions/auth'
|
||||
import { logoutAction, getSessionAction, setSessionAction } from '@/app/actions/auth'
|
||||
import { getUserOrganizations, switchContext } from '@/lib/api/organization'
|
||||
|
||||
interface User {
|
||||
id: string
|
||||
email: string
|
||||
totp_enabled: boolean
|
||||
org_id?: string
|
||||
role?: string
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
@@ -35,6 +38,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [isLoggingOut, setIsLoggingOut] = useState(false)
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
|
||||
const login = (userData: User) => {
|
||||
// * We still store user profile in localStorage for optimistic UI, but NOT the token
|
||||
@@ -97,6 +101,50 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
init()
|
||||
}, [])
|
||||
|
||||
// * Organization Wall & Auto-Switch
|
||||
useEffect(() => {
|
||||
const checkOrg = async () => {
|
||||
if (!loading && user) {
|
||||
// * If we are on onboarding, skip check
|
||||
if (pathname?.startsWith('/onboarding')) return
|
||||
|
||||
try {
|
||||
const { organizations } = await getUserOrganizations()
|
||||
|
||||
if (organizations.length === 0) {
|
||||
// * No organizations -> Redirect to Onboarding
|
||||
router.push('/onboarding')
|
||||
return
|
||||
}
|
||||
|
||||
// * If user has organizations but no context (org_id), switch to the first one
|
||||
if (!user.org_id && organizations.length > 0) {
|
||||
const firstOrg = organizations[0]
|
||||
console.log('Auto-switching to organization:', firstOrg.organization_name)
|
||||
|
||||
try {
|
||||
const { token, refresh_token } = await switchContext(firstOrg.organization_id)
|
||||
|
||||
// * Update session cookie
|
||||
const result = await setSessionAction(token, refresh_token)
|
||||
if (result.success && result.user) {
|
||||
setUser(result.user)
|
||||
localStorage.setItem('user', JSON.stringify(result.user))
|
||||
router.refresh()
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to auto-switch context', e)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch organizations", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
checkOrg()
|
||||
}, [loading, user, pathname, router])
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, refresh, refreshSession }}>
|
||||
{isLoggingOut && <LoadingOverlay logoSrc="/ciphera_icon_no_margins.png" title="Pulse" />}
|
||||
|
||||
Reference in New Issue
Block a user