Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
222 changes: 222 additions & 0 deletions CONDITIONAL_AUTH.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
# Conditional Authentication

ObjectUI now supports conditional authentication based on server discovery information. This allows the console application to automatically detect whether the backend has authentication enabled and adapt accordingly.

## Overview

When the ObjectStack server discovery endpoint (`/.well-known/objectstack` or `/api`) indicates that authentication is disabled (`auth.enabled === false`), the console application will bypass the authentication flow and operate in "Guest Mode".

This is useful for:
- **Development environments** where authentication is not configured
- **Demo environments** where users should access the system without credentials
- **Embedded scenarios** where authentication is handled externally

## Implementation

### 1. Discovery Response Structure

The server's discovery endpoint should return a response with the following structure:

```json
{
"name": "ObjectStack API",
"version": "2.0.0",
"services": {
"auth": {
"enabled": false,
"status": "unavailable",
"message": "Authentication service not installed. Install an auth plugin to enable authentication."
},
"data": {
"enabled": true,
"status": "available"
},
"metadata": {
"enabled": true,
"status": "available"
}
}
}
```

### 2. Client-Side Detection

The console application uses the `ConditionalAuthWrapper` component which:

1. Connects to the server and fetches discovery information
2. Checks the `services.auth.enabled` flag
3. If `false`, wraps the application with `<AuthProvider enabled={false}>` (Guest Mode)
4. If `true` or undefined, wraps with normal `<AuthProvider>` (Standard Auth Mode)

### 3. Guest Mode Behavior

When authentication is disabled:

- A virtual "Guest User" is automatically authenticated with:
- ID: `guest`
- Name: `Guest User`
- Email: `guest@local`
- Token: `guest-token`

- All protected routes become accessible without login
- Login/Register pages are still accessible but not required
- The user menu shows the guest user

## Usage

### For Application Developers

Simply wrap your application with `ConditionalAuthWrapper`:

```tsx
import { ConditionalAuthWrapper } from './components/ConditionalAuthWrapper';

function App() {
return (
<ConditionalAuthWrapper authUrl="/api/auth">
<BrowserRouter>
<Routes>
{/* Your routes */}
</Routes>
</BrowserRouter>
</ConditionalAuthWrapper>
);
}
```

### For Backend Developers

Ensure your discovery endpoint returns the correct `services.auth.enabled` flag:

**With Auth Enabled:**
```typescript
{
services: {
auth: {
enabled: true,
status: "available"
}
}
}
```

**With Auth Disabled:**
```typescript
{
services: {
auth: {
enabled: false,
status: "unavailable",
message: "Auth service not configured"
}
}
}
```

### Using the useDiscovery Hook

Components can also directly access discovery information:

```tsx
import { useDiscovery } from '@object-ui/react';

function MyComponent() {
const { discovery, isLoading, isAuthEnabled } = useDiscovery();

if (isLoading) return <LoadingSpinner />;

return (
<div>
{isAuthEnabled
? <LoginPrompt />
: <GuestWelcome />
}
</div>
);
}
```

## Security Considerations

⚠️ **Important Security Note:**

- The default behavior (when discovery fails or auth status is unknown) is to **enable authentication** for security.
- Guest mode should only be used in controlled environments (development, demos).
- In production, always configure proper authentication.

## API Reference

### ConditionalAuthWrapper

**Props:**
- `authUrl` (string): The authentication endpoint URL
- `children` (ReactNode): Application content to wrap

**Behavior:**
- Fetches discovery on mount
- Shows loading screen while checking auth status
- Wraps children with appropriate AuthProvider configuration

### AuthProvider

**New Props:**
- `enabled` (boolean, default: `true`): Whether authentication is enabled
- When `false`: Automatically authenticates as guest user
- When `true`: Normal authentication flow

### useDiscovery Hook

**Returns:**
- `discovery` (DiscoveryInfo | null): Raw discovery data from server
- `isLoading` (boolean): Whether discovery is being fetched
- `error` (Error | null): Any error that occurred during fetch
- `isAuthEnabled` (boolean): Convenience flag for `discovery?.services?.auth?.enabled ?? true`

## Examples

### Example 1: Development Server Without Auth

**Discovery Response:**
```json
{
"name": "Dev Server",
"services": {
"auth": { "enabled": false }
}
}
```

**Result:** Console loads without requiring login

### Example 2: Production Server With Auth

**Discovery Response:**
```json
{
"name": "Production Server",
"services": {
"auth": { "enabled": true }
}
}
```

**Result:** Console requires user authentication

### Example 3: Legacy Server (No Discovery)

**Discovery Response:** 404 or connection error

**Result:** Defaults to authentication enabled (secure by default)

## Testing

Tests are included in:
- `packages/auth/src/__tests__/AuthProvider.disabled.test.tsx`
- Tests verify guest mode behavior
- Tests verify normal auth mode behavior
- Tests verify session token creation in guest mode

Run tests with:
```bash
pnpm test packages/auth/src/__tests__/AuthProvider.disabled.test.tsx
```
7 changes: 4 additions & 3 deletions apps/console/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { SchemaRendererProvider } from '@object-ui/react';
import { ObjectStackAdapter } from './dataSource';
import type { ConnectionState } from './dataSource';
import appConfig from '../objectstack.shared';
import { AuthProvider, AuthGuard, useAuth } from '@object-ui/auth';
import { AuthGuard, useAuth } from '@object-ui/auth';

// Components
import { ConsoleLayout } from './components/ConsoleLayout';
Expand All @@ -19,6 +19,7 @@ import { DashboardView } from './components/DashboardView';
import { PageView } from './components/PageView';
import { ReportView } from './components/ReportView';
import { ExpressionProvider } from './context/ExpressionProvider';
import { ConditionalAuthWrapper } from './components/ConditionalAuthWrapper';

// Auth Pages
import { LoginPage } from './pages/LoginPage';
Expand Down Expand Up @@ -291,7 +292,7 @@ function RootRedirect() {
export function App() {
return (
<ThemeProvider defaultTheme="system" storageKey="object-ui-theme">
<AuthProvider authUrl="/api/auth">
<ConditionalAuthWrapper authUrl="/api/auth">
<BrowserRouter basename="/">
<Routes>
<Route path="/login" element={<LoginPage />} />
Expand All @@ -305,7 +306,7 @@ export function App() {
<Route path="/" element={<RootRedirect />} />
</Routes>
</BrowserRouter>
</AuthProvider>
</ConditionalAuthWrapper>
</ThemeProvider>
);
}
94 changes: 94 additions & 0 deletions apps/console/src/components/ConditionalAuthWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* ObjectUI Console - Conditional Auth Wrapper
*
* This component fetches discovery information from the server and conditionally
* enables/disables authentication based on the server's auth service status.
*/

import { useState, useEffect, ReactNode } from 'react';
import { ObjectStackAdapter } from './dataSource';
import { AuthProvider } from '@object-ui/auth';
import { LoadingScreen } from './components/LoadingScreen';
Comment on lines +9 to +11
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The relative imports are incorrect for a file located in src/components: ./dataSource and ./components/LoadingScreen do not exist from this directory and will break compilation. Import the adapter from ../dataSource and LoadingScreen from ./LoadingScreen (or the correct local path).

Suggested change
import { ObjectStackAdapter } from './dataSource';
import { AuthProvider } from '@object-ui/auth';
import { LoadingScreen } from './components/LoadingScreen';
import { ObjectStackAdapter } from '../dataSource';
import { AuthProvider } from '@object-ui/auth';
import { LoadingScreen } from './LoadingScreen';

Copilot uses AI. Check for mistakes.
import type { DiscoveryInfo } from '@object-ui/react';

interface ConditionalAuthWrapperProps {
children: ReactNode;
authUrl: string;
}

/**
* Wrapper component that conditionally enables authentication based on server discovery.
*
* This component:
* 1. Creates a temporary data source connection
* 2. Fetches discovery information from the server
* 3. Checks if auth.enabled is true in the discovery response
* 4. Conditionally wraps children with AuthProvider if auth is enabled
* 5. Bypasses auth if discovery indicates auth is disabled (development/demo mode)
*/
export function ConditionalAuthWrapper({ children, authUrl }: ConditionalAuthWrapperProps) {
const [authEnabled, setAuthEnabled] = useState<boolean | null>(null);
const [isLoading, setIsLoading] = useState(true);

useEffect(() => {
let cancelled = false;

async function checkAuthStatus() {
try {
// Create a temporary adapter to fetch discovery
// Empty baseUrl allows the adapter to use browser-relative paths
// This works because the console app is served from the same origin as the API
const adapter = new ObjectStackAdapter({
baseUrl: '',
autoReconnect: false,
});

await adapter.connect();
const discovery = await adapter.getDiscovery() as DiscoveryInfo | null;

if (!cancelled) {
// Check if auth is enabled in discovery
// Default to true if discovery doesn't provide this information
const isAuthEnabled = discovery?.services?.auth?.enabled ?? true;
setAuthEnabled(isAuthEnabled);
}
} catch (error) {
if (!cancelled) {
// If discovery fails, default to auth enabled for security
console.warn('[ConditionalAuthWrapper] Failed to fetch discovery, defaulting to auth enabled:', error);
setAuthEnabled(true);
}
} finally {
if (!cancelled) {
setIsLoading(false);
}
}
}

checkAuthStatus();

return () => {
cancelled = true;
};
}, []);

if (isLoading) {
return <LoadingScreen />;
}

// If auth is enabled, wrap with AuthProvider
if (authEnabled) {
return (
<AuthProvider authUrl={authUrl}>
{children}
</AuthProvider>
);
}

// If auth is disabled, wrap with a disabled AuthProvider (guest mode)
return (
<AuthProvider authUrl={authUrl} enabled={false}>
{children}
</AuthProvider>
);
}
Loading
Loading