feat: add organization onboarding flow and auth enforcement

This commit is contained in:
Usman Baig
2026-01-22 00:32:48 +01:00
parent 923aed464a
commit 12dc03b636
6 changed files with 288 additions and 5 deletions

View File

@@ -25,6 +25,8 @@ interface UserPayload {
sub: string
email?: string
totp_enabled?: boolean
org_id?: string
role?: string
}
export async function exchangeAuthCode(code: string, codeVerifier: string, redirectUri: string) {
@@ -83,7 +85,9 @@ export async function exchangeAuthCode(code: string, codeVerifier: string, redir
user: {
id: payload.sub,
email: payload.email || 'user@ciphera.net',
totp_enabled: payload.totp_enabled || false
totp_enabled: payload.totp_enabled || false,
org_id: payload.org_id,
role: payload.role
}
}
@@ -124,7 +128,9 @@ export async function setSessionAction(accessToken: string, refreshToken: string
user: {
id: payload.sub,
email: payload.email || 'user@ciphera.net',
totp_enabled: payload.totp_enabled || false
totp_enabled: payload.totp_enabled || false,
org_id: payload.org_id,
role: payload.role
}
}
} catch (e) {
@@ -161,7 +167,9 @@ export async function getSessionAction() {
return {
id: payload.sub,
email: payload.email || 'user@ciphera.net',
totp_enabled: payload.totp_enabled || false
totp_enabled: payload.totp_enabled || false,
org_id: payload.org_id,
role: payload.role
}
} catch {
return null

107
app/onboarding/page.tsx Normal file
View File

@@ -0,0 +1,107 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { createOrganization } from '@/lib/api/organization'
import { useAuth } from '@/lib/auth/context'
import LoadingOverlay from '@/components/LoadingOverlay'
import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input'
export default function OnboardingPage() {
const [name, setName] = useState('')
const [slug, setSlug] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const router = useRouter()
const { user } = useAuth()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
setError('')
try {
await createOrganization(name, slug)
// * Redirect to home, AuthContext will detect the new org and auto-switch
router.push('/')
} catch (err: any) {
setError(err.message || 'Failed to create organization')
} finally {
setLoading(false)
}
}
// * Auto-generate slug from name
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value
setName(val)
if (!slug || slug === name.toLowerCase().replace(/[^a-z0-9]/g, '-')) {
setSlug(val.toLowerCase().replace(/[^a-z0-9]/g, '-'))
}
}
if (loading) return <LoadingOverlay title="Creating Organization..." />
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-neutral-900 px-4">
<div className="max-w-md w-full space-y-8">
<div className="text-center">
<h2 className="mt-6 text-3xl font-bold text-gray-900 dark:text-white">
Welcome to Pulse
</h2>
<p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
To get started, please create an organization for your team.
</p>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
<div className="rounded-md shadow-sm space-y-4">
<div>
<label htmlFor="org-name" className="sr-only">Organization Name</label>
<Input
id="org-name"
name="name"
type="text"
required
placeholder="Organization Name (e.g. Acme Corp)"
value={name}
onChange={handleNameChange}
/>
</div>
<div>
<label htmlFor="org-slug" className="sr-only">URL Slug</label>
<Input
id="org-slug"
name="slug"
type="text"
required
placeholder="URL Slug (e.g. acme-corp)"
value={slug}
onChange={(e) => setSlug(e.target.value)}
/>
<p className="text-xs text-gray-500 mt-1">
This will be used in your organization's URL.
</p>
</div>
</div>
{error && (
<div className="text-red-500 text-sm text-center">
{error}
</div>
)}
<div>
<Button
type="submit"
className="w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Create Organization
</Button>
</div>
</form>
</div>
</div>
)
}

37
components/ui/Button.tsx Normal file
View File

@@ -0,0 +1,37 @@
import React from 'react';
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'ghost';
isLoading?: boolean;
}
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className = '', variant = 'primary', isLoading, children, disabled, ...props }, ref) => {
const baseStyles = 'inline-flex items-center justify-center rounded-xl text-sm font-medium px-5 py-2.5 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed';
const variants = {
primary: 'bg-blue-600 text-white shadow-sm hover:bg-blue-700 focus:ring-blue-500',
secondary: 'bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 text-neutral-900 dark:text-white hover:bg-neutral-50 dark:hover:bg-neutral-800 shadow-sm focus:ring-neutral-200',
ghost: 'text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800 focus:ring-neutral-200',
};
return (
<button
ref={ref}
className={`${baseStyles} ${variants[variant]} ${className}`}
disabled={disabled || isLoading}
{...props}
>
{isLoading && (
<svg className="w-4 h-4 mr-2 animate-spin" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
)}
{children}
</button>
);
}
);
Button.displayName = 'Button';

37
components/ui/Input.tsx Normal file
View File

@@ -0,0 +1,37 @@
import React from 'react';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
error?: string;
icon?: React.ReactNode;
}
export const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className = '', error, icon, ...props }, ref) => {
return (
<div className="relative">
<input
ref={ref}
className={`
w-full py-3 border rounded-xl bg-neutral-50/50 dark:bg-neutral-900/50 focus:bg-white dark:focus:bg-neutral-900 transition-all duration-200 outline-none disabled:opacity-50 disabled:cursor-not-allowed dark:text-white
${icon ? 'pl-11 pr-4' : 'px-4'}
${error
? 'border-red-300 dark:border-red-800 focus:border-red-500 focus:ring-4 focus:ring-red-500/10'
: 'border-neutral-200 dark:border-neutral-800 hover:border-blue-500/50 focus:border-blue-500 focus:ring-4 focus:ring-blue-500/10'}
${className}
`}
{...props}
/>
{icon && (
<div className={`
absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none transition-colors duration-200
${error ? 'text-red-400' : 'text-neutral-400 dark:text-neutral-500'}
`}>
{icon}
</div>
)}
</div>
);
}
);
Input.displayName = 'Input';

46
lib/api/organization.ts Normal file
View 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 }),
})
}

View File

@@ -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" />}