Implement complete Bearer Token and API key authentication system
- Create comprehensive authentication backend with JWT and API key support - Add database models for users, API keys, and tokens with proper security - Implement authentication middleware and API endpoints - Build complete frontend authentication UI with: - LoginForm component with JWT authentication - APIKeyManager for creating and managing API keys - AuthDashboard for comprehensive auth management - AuthContext for state management and authenticated requests - Initialize database with default admin user (admin/admin123) - Add proper token refresh, validation, and blacklisting - Implement scope-based API key authorization system 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
455
frontend/src/components/auth/APIKeyManager.tsx
Normal file
455
frontend/src/components/auth/APIKeyManager.tsx
Normal file
@@ -0,0 +1,455 @@
|
||||
/**
|
||||
* API Key Management Component
|
||||
* Provides interface for creating, viewing, and managing API keys
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Key,
|
||||
Plus,
|
||||
Copy,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Trash2,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
Calendar,
|
||||
Shield
|
||||
} from 'lucide-react';
|
||||
import { useAuthenticatedFetch } from '../../contexts/AuthContext';
|
||||
|
||||
interface APIKey {
|
||||
id: number;
|
||||
name: string;
|
||||
key_prefix: string;
|
||||
scopes: string[];
|
||||
is_active: boolean;
|
||||
last_used?: string;
|
||||
created_at: string;
|
||||
expires_at?: string;
|
||||
}
|
||||
|
||||
interface CreateAPIKeyRequest {
|
||||
name: string;
|
||||
scopes: string[];
|
||||
expires_days?: number;
|
||||
}
|
||||
|
||||
interface CreateAPIKeyResponse {
|
||||
api_key: APIKey;
|
||||
plain_key: string;
|
||||
}
|
||||
|
||||
const API_SCOPES = [
|
||||
{ id: 'read', label: 'Read Access', description: 'View data and resources' },
|
||||
{ id: 'write', label: 'Write Access', description: 'Create and modify resources' },
|
||||
{ id: 'admin', label: 'Admin Access', description: 'Full administrative access' },
|
||||
{ id: 'agents', label: 'Agent Management', description: 'Manage AI agents' },
|
||||
{ id: 'workflows', label: 'Workflow Management', description: 'Create and run workflows' },
|
||||
{ id: 'monitoring', label: 'Monitoring', description: 'Access monitoring and metrics' }
|
||||
];
|
||||
|
||||
export const APIKeyManager: React.FC = () => {
|
||||
const [apiKeys, setApiKeys] = useState<APIKey[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
|
||||
const [newKey, setNewKey] = useState<string | null>(null);
|
||||
const [showNewKey, setShowNewKey] = useState(false);
|
||||
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
|
||||
|
||||
// Create form state
|
||||
const [createForm, setCreateForm] = useState({
|
||||
name: '',
|
||||
scopes: [] as string[],
|
||||
expires_days: undefined as number | undefined
|
||||
});
|
||||
|
||||
const authenticatedFetch = useAuthenticatedFetch();
|
||||
|
||||
useEffect(() => {
|
||||
loadAPIKeys();
|
||||
}, []);
|
||||
|
||||
const loadAPIKeys = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await authenticatedFetch('/api/auth/api-keys');
|
||||
|
||||
if (response.ok) {
|
||||
const keys = await response.json();
|
||||
setApiKeys(keys);
|
||||
} else {
|
||||
setError('Failed to load API keys');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to load API keys');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateAPIKey = async () => {
|
||||
try {
|
||||
const requestData: CreateAPIKeyRequest = {
|
||||
name: createForm.name,
|
||||
scopes: createForm.scopes,
|
||||
...(createForm.expires_days && { expires_days: createForm.expires_days })
|
||||
};
|
||||
|
||||
const response = await authenticatedFetch('/api/auth/api-keys', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(requestData)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data: CreateAPIKeyResponse = await response.json();
|
||||
setNewKey(data.plain_key);
|
||||
setApiKeys(prev => [...prev, data.api_key]);
|
||||
|
||||
// Reset form
|
||||
setCreateForm({
|
||||
name: '',
|
||||
scopes: [],
|
||||
expires_days: undefined
|
||||
});
|
||||
|
||||
setError('');
|
||||
} else {
|
||||
const errorData = await response.json();
|
||||
setError(errorData.detail || 'Failed to create API key');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to create API key');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAPIKey = async (keyId: number, keyName: string) => {
|
||||
if (!confirm(`Are you sure you want to delete the API key "${keyName}"? This action cannot be undone.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await authenticatedFetch(`/api/auth/api-keys/${keyId}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
setApiKeys(prev => prev.filter(key => key.id !== keyId));
|
||||
} else {
|
||||
setError('Failed to delete API key');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to delete API key');
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleAPIKey = async (keyId: number, isActive: boolean) => {
|
||||
try {
|
||||
const response = await authenticatedFetch(`/api/auth/api-keys/${keyId}/toggle`, {
|
||||
method: 'PATCH'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const updatedKey = await response.json();
|
||||
setApiKeys(prev => prev.map(key => key.id === keyId ? updatedKey : key));
|
||||
} else {
|
||||
setError('Failed to update API key status');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to update API key status');
|
||||
}
|
||||
};
|
||||
|
||||
const copyToClipboard = (text: string, keyId?: number) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
if (keyId) {
|
||||
setCopiedKeyId(keyId);
|
||||
setTimeout(() => setCopiedKeyId(null), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleScopeChange = (scope: string, checked: boolean) => {
|
||||
setCreateForm(prev => ({
|
||||
...prev,
|
||||
scopes: checked
|
||||
? [...prev.scopes, scope]
|
||||
: prev.scopes.filter(s => s !== scope)
|
||||
}));
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-gray-900">API Keys</h2>
|
||||
<p className="text-gray-600 mt-1">
|
||||
Manage API keys for programmatic access to Hive
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Create API Key
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New API Key</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="key-name">Key Name</Label>
|
||||
<Input
|
||||
id="key-name"
|
||||
value={createForm.name}
|
||||
onChange={(e) => setCreateForm(prev => ({ ...prev, name: e.target.value }))}
|
||||
placeholder="e.g., Production API Key"
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Scopes</Label>
|
||||
<div className="mt-2 space-y-2 max-h-48 overflow-y-auto">
|
||||
{API_SCOPES.map(scope => (
|
||||
<div key={scope.id} className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id={scope.id}
|
||||
checked={createForm.scopes.includes(scope.id)}
|
||||
onCheckedChange={(checked) => handleScopeChange(scope.id, !!checked)}
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor={scope.id} className="text-sm font-medium">
|
||||
{scope.label}
|
||||
</Label>
|
||||
<p className="text-xs text-gray-500">{scope.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="expires-days">Expiration (days)</Label>
|
||||
<Select
|
||||
value={createForm.expires_days?.toString() || ''}
|
||||
onValueChange={(value) => setCreateForm(prev => ({
|
||||
...prev,
|
||||
expires_days: value ? parseInt(value) : undefined
|
||||
}))}
|
||||
>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Never expires" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="">Never expires</SelectItem>
|
||||
<SelectItem value="7">7 days</SelectItem>
|
||||
<SelectItem value="30">30 days</SelectItem>
|
||||
<SelectItem value="90">90 days</SelectItem>
|
||||
<SelectItem value="365">1 year</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleCreateAPIKey}
|
||||
disabled={!createForm.name || createForm.scopes.length === 0}
|
||||
className="w-full"
|
||||
>
|
||||
Create API Key
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{newKey && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">API Key Created Successfully!</p>
|
||||
<p className="text-sm">
|
||||
Please copy your API key now. You won't be able to see it again.
|
||||
</p>
|
||||
<div className="flex items-center space-x-2 bg-gray-50 p-2 rounded">
|
||||
<code className="flex-1 text-sm">
|
||||
{showNewKey ? newKey : '•'.repeat(40)}
|
||||
</code>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowNewKey(!showNewKey)}
|
||||
>
|
||||
{showNewKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copyToClipboard(newKey)}
|
||||
>
|
||||
<Copy className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setNewKey(null)}
|
||||
>
|
||||
I've saved the key
|
||||
</Button>
|
||||
</div>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{apiKeys.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="text-center py-8">
|
||||
<Key className="w-12 h-12 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-2">No API Keys</h3>
|
||||
<p className="text-gray-600 mb-4">
|
||||
Create your first API key to start using the Hive API programmatically.
|
||||
</p>
|
||||
<Button onClick={() => setIsCreateDialogOpen(true)}>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Create API Key
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
apiKeys.map(apiKey => (
|
||||
<Card key={apiKey.id}>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center space-x-3 mb-2">
|
||||
<h3 className="text-lg font-medium text-gray-900">
|
||||
{apiKey.name}
|
||||
</h3>
|
||||
<Badge variant={apiKey.is_active ? "default" : "secondary"}>
|
||||
{apiKey.is_active ? "Active" : "Disabled"}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm text-gray-600">
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex items-center space-x-1">
|
||||
<Key className="w-4 h-4" />
|
||||
<span>Key: {apiKey.key_prefix}...</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copyToClipboard(`${apiKey.key_prefix}...`)}
|
||||
className="h-auto p-1"
|
||||
>
|
||||
{copiedKeyId === apiKey.id ? (
|
||||
<CheckCircle className="w-3 h-3 text-green-600" />
|
||||
) : (
|
||||
<Copy className="w-3 h-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-1">
|
||||
<Calendar className="w-4 h-4" />
|
||||
<span>Created: {formatDate(apiKey.created_at)}</span>
|
||||
</div>
|
||||
|
||||
{apiKey.last_used && (
|
||||
<div className="flex items-center space-x-1">
|
||||
<span>Last used: {formatDate(apiKey.last_used)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{apiKey.expires_at && (
|
||||
<div className="flex items-center space-x-1 text-amber-600">
|
||||
<Calendar className="w-4 h-4" />
|
||||
<span>Expires: {formatDate(apiKey.expires_at)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center space-x-1">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Scopes:</span>
|
||||
<div className="flex space-x-1">
|
||||
{apiKey.scopes.map(scope => (
|
||||
<Badge key={scope} variant="outline" className="text-xs">
|
||||
{scope}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleToggleAPIKey(apiKey.id, !apiKey.is_active)}
|
||||
>
|
||||
{apiKey.is_active ? 'Disable' : 'Enable'}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDeleteAPIKey(apiKey.id, apiKey.name)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default APIKeyManager;
|
||||
303
frontend/src/components/auth/AuthDashboard.tsx
Normal file
303
frontend/src/components/auth/AuthDashboard.tsx
Normal file
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* Authentication Dashboard Component
|
||||
* Main dashboard for authentication and authorization management
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import {
|
||||
User,
|
||||
Key,
|
||||
Shield,
|
||||
Clock,
|
||||
Settings,
|
||||
LogOut,
|
||||
Calendar,
|
||||
Activity
|
||||
} from 'lucide-react';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import { APIKeyManager } from './APIKeyManager';
|
||||
|
||||
export const AuthDashboard: React.FC = () => {
|
||||
const { user, tokens, logout } = useAuth();
|
||||
const [activeTab, setActiveTab] = useState('profile');
|
||||
|
||||
const handleLogout = async () => {
|
||||
await logout();
|
||||
};
|
||||
|
||||
const formatDate = (dateString?: string) => {
|
||||
if (!dateString) return 'Never';
|
||||
return new Date(dateString).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
};
|
||||
|
||||
const getTokenExpirationTime = () => {
|
||||
if (!tokens?.access_token) return null;
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(atob(tokens.access_token.split('.')[1]));
|
||||
return new Date(payload.exp * 1000);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const tokenExpiration = getTokenExpirationTime();
|
||||
const isTokenExpiringSoon = tokenExpiration && (tokenExpiration.getTime() - Date.now()) < 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-6">
|
||||
<div className="max-w-6xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Authentication Dashboard</h1>
|
||||
<p className="text-gray-600 mt-1">
|
||||
Manage your account, tokens, and API keys
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button onClick={handleLogout} variant="outline">
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
Sign Out
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Quick Stats */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-blue-100 rounded-lg">
|
||||
<User className="w-5 h-5 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Account Status</p>
|
||||
<p className="font-medium">
|
||||
{user?.is_active ? 'Active' : 'Inactive'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-green-100 rounded-lg">
|
||||
<Shield className="w-5 h-5 text-green-600" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Role</p>
|
||||
<p className="font-medium">
|
||||
{user?.is_superuser ? 'Administrator' : 'User'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className={`p-2 rounded-lg ${isTokenExpiringSoon ? 'bg-red-100' : 'bg-yellow-100'}`}>
|
||||
<Clock className={`w-5 h-5 ${isTokenExpiringSoon ? 'text-red-600' : 'text-yellow-600'}`} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Token Expires</p>
|
||||
<p className="font-medium text-xs">
|
||||
{tokenExpiration ? formatDate(tokenExpiration.toISOString()) : 'Unknown'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="p-2 bg-purple-100 rounded-lg">
|
||||
<Activity className="w-5 h-5 text-purple-600" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Last Login</p>
|
||||
<p className="font-medium text-xs">
|
||||
{formatDate(user?.last_login)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
|
||||
<TabsList className="grid w-full grid-cols-3">
|
||||
<TabsTrigger value="profile">Profile</TabsTrigger>
|
||||
<TabsTrigger value="api-keys">API Keys</TabsTrigger>
|
||||
<TabsTrigger value="tokens">Tokens</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="profile" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center space-x-2">
|
||||
<User className="w-5 h-5" />
|
||||
<span>User Profile</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700">Username</label>
|
||||
<p className="mt-1 text-gray-900">{user?.username}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700">Email</label>
|
||||
<p className="mt-1 text-gray-900">{user?.email}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700">Full Name</label>
|
||||
<p className="mt-1 text-gray-900">{user?.full_name || 'Not set'}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700">Account Created</label>
|
||||
<p className="mt-1 text-gray-900">{formatDate(user?.created_at)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 pt-4">
|
||||
<Badge variant={user?.is_active ? "default" : "secondary"}>
|
||||
{user?.is_active ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
|
||||
<Badge variant={user?.is_verified ? "default" : "secondary"}>
|
||||
{user?.is_verified ? "Verified" : "Unverified"}
|
||||
</Badge>
|
||||
|
||||
{user?.is_superuser && (
|
||||
<Badge variant="destructive">
|
||||
Administrator
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t">
|
||||
<Button variant="outline">
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
Edit Profile
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="api-keys">
|
||||
<APIKeyManager />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="tokens" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center space-x-2">
|
||||
<Key className="w-5 h-5" />
|
||||
<span>Authentication Tokens</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h4 className="font-medium">Access Token</h4>
|
||||
<Badge variant={isTokenExpiringSoon ? "destructive" : "default"}>
|
||||
{isTokenExpiringSoon ? "Expiring Soon" : "Active"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm text-gray-600">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Calendar className="w-4 h-4" />
|
||||
<span>
|
||||
Expires: {tokenExpiration ? formatDate(tokenExpiration.toISOString()) : 'Unknown'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Key className="w-4 h-4" />
|
||||
<span>Type: Bearer Token</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h4 className="font-medium">Refresh Token</h4>
|
||||
<Badge variant="secondary">
|
||||
Available
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm text-gray-600">
|
||||
<p>Used to automatically refresh access tokens when they expire.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t">
|
||||
<div className="flex space-x-2">
|
||||
<Button variant="outline">
|
||||
Refresh Token
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleLogout}>
|
||||
Revoke All Tokens
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Token Usage Guidelines</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3 text-sm">
|
||||
<div>
|
||||
<h5 className="font-medium">Bearer Token Authentication</h5>
|
||||
<p className="text-gray-600">
|
||||
Include your access token in API requests using the Authorization header:
|
||||
</p>
|
||||
<code className="block mt-1 p-2 bg-gray-100 rounded text-xs">
|
||||
Authorization: Bearer YOUR_ACCESS_TOKEN
|
||||
</code>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h5 className="font-medium">Token Security</h5>
|
||||
<ul className="list-disc list-inside text-gray-600 space-y-1">
|
||||
<li>Never share your tokens with others</li>
|
||||
<li>Use HTTPS for all API requests</li>
|
||||
<li>Store tokens securely in your applications</li>
|
||||
<li>Revoke tokens if they may be compromised</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthDashboard;
|
||||
178
frontend/src/components/auth/LoginForm.tsx
Normal file
178
frontend/src/components/auth/LoginForm.tsx
Normal file
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Login Form Component
|
||||
* Provides user authentication interface with JWT token support
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Eye, EyeOff, Lock, User, AlertCircle } from 'lucide-react';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
|
||||
interface LoginFormProps {
|
||||
onSuccess?: () => void;
|
||||
redirectTo?: string;
|
||||
}
|
||||
|
||||
export const LoginForm: React.FC<LoginFormProps> = ({ onSuccess, redirectTo = '/dashboard' }) => {
|
||||
const [formData, setFormData] = useState({
|
||||
username: '',
|
||||
password: '',
|
||||
});
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[name]: value,
|
||||
}));
|
||||
// Clear error when user starts typing
|
||||
if (error) setError('');
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
await login(formData.username, formData.password);
|
||||
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
} else {
|
||||
navigate(redirectTo);
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Login failed. Please check your credentials.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const togglePasswordVisibility = () => {
|
||||
setShowPassword(!showPassword);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 px-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="mx-auto mb-4 w-12 h-12 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<Lock className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl font-bold text-gray-900">
|
||||
Welcome to Hive
|
||||
</CardTitle>
|
||||
<p className="text-gray-600 mt-2">
|
||||
Sign in to your account to continue
|
||||
</p>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
value={formData.username}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Enter your username"
|
||||
className="pl-10"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formData.password}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Enter your password"
|
||||
className="pl-10 pr-10"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={togglePasswordVisibility}
|
||||
className="absolute right-3 top-3 text-gray-400 hover:text-gray-600"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isLoading || !formData.username || !formData.password}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
Signing in...
|
||||
</>
|
||||
) : (
|
||||
'Sign In'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-6 text-center text-sm text-gray-600">
|
||||
<p>
|
||||
Need help?{' '}
|
||||
<Link
|
||||
to="/docs"
|
||||
className="text-blue-600 hover:text-blue-500 font-medium"
|
||||
>
|
||||
View documentation
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Development info */}
|
||||
{process.env.NODE_ENV === 'development' && (
|
||||
<div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
|
||||
<p className="text-xs text-yellow-800">
|
||||
<strong>Development Mode:</strong><br />
|
||||
Default credentials: admin / admin123
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginForm;
|
||||
@@ -1,105 +1,229 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
/**
|
||||
* Authentication Context
|
||||
* Manages user authentication state, JWT tokens, and API key authentication
|
||||
*/
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
role: string;
|
||||
email?: string;
|
||||
email: string;
|
||||
full_name?: string;
|
||||
is_active: boolean;
|
||||
is_superuser: boolean;
|
||||
is_verified: boolean;
|
||||
created_at: string;
|
||||
last_login?: string;
|
||||
}
|
||||
|
||||
interface AuthTokens {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
tokens: AuthTokens | null;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
login: (username: string, password: string) => Promise<boolean>;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
token: string | null;
|
||||
refreshToken: () => Promise<boolean>;
|
||||
updateUser: (userData: Partial<User>) => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null);
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: React.ReactNode;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const API_BASE_URL = process.env.REACT_APP_API_URL || '/api';
|
||||
|
||||
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [tokens, setTokens] = useState<AuthTokens | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// Check for existing authentication on mount
|
||||
useEffect(() => {
|
||||
const checkAuth = () => {
|
||||
const storedToken = localStorage.getItem('auth_token');
|
||||
const storedUser = localStorage.getItem('user');
|
||||
const isAuthenticated = !!user && !!tokens;
|
||||
|
||||
if (storedToken && storedUser) {
|
||||
try {
|
||||
const parsedUser = JSON.parse(storedUser);
|
||||
setToken(storedToken);
|
||||
setUser(parsedUser);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse stored user data:', error);
|
||||
localStorage.removeItem('auth_token');
|
||||
localStorage.removeItem('user');
|
||||
// Initialize auth state from localStorage
|
||||
useEffect(() => {
|
||||
const initializeAuth = async () => {
|
||||
try {
|
||||
const storedTokens = localStorage.getItem('hive_tokens');
|
||||
const storedUser = localStorage.getItem('hive_user');
|
||||
|
||||
if (storedTokens && storedUser) {
|
||||
const parsedTokens: AuthTokens = JSON.parse(storedTokens);
|
||||
const parsedUser: User = JSON.parse(storedUser);
|
||||
|
||||
// Check if tokens are still valid
|
||||
if (await validateTokens(parsedTokens)) {
|
||||
setTokens(parsedTokens);
|
||||
setUser(parsedUser);
|
||||
} else {
|
||||
// Try to refresh tokens
|
||||
const refreshed = await refreshTokenWithStoredData(parsedTokens);
|
||||
if (!refreshed) {
|
||||
clearAuthData();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error initializing auth:', error);
|
||||
clearAuthData();
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
initializeAuth();
|
||||
}, []);
|
||||
|
||||
const login = async (username: string, password: string): Promise<boolean> => {
|
||||
const validateTokens = async (tokens: AuthTokens): Promise<boolean> => {
|
||||
try {
|
||||
// In a real application, this would make an API call
|
||||
// For demo purposes, we'll simulate authentication
|
||||
if (username === 'admin' && password === 'hiveadmin') {
|
||||
const mockToken = 'mock-jwt-token-' + Date.now();
|
||||
const mockUser: User = {
|
||||
id: '1',
|
||||
username: 'admin',
|
||||
name: 'System Administrator',
|
||||
role: 'administrator',
|
||||
email: 'admin@hive.local'
|
||||
};
|
||||
|
||||
setToken(mockToken);
|
||||
setUser(mockUser);
|
||||
|
||||
localStorage.setItem('auth_token', mockToken);
|
||||
localStorage.setItem('user', JSON.stringify(mockUser));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
const response = await fetch(`${API_BASE_URL}/auth/me`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${tokens.access_token}`,
|
||||
},
|
||||
});
|
||||
return response.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
setUser(null);
|
||||
setToken(null);
|
||||
localStorage.removeItem('auth_token');
|
||||
localStorage.removeItem('user');
|
||||
const refreshTokenWithStoredData = async (oldTokens: AuthTokens): Promise<boolean> => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
refresh_token: oldTokens.refresh_token,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const newTokens: AuthTokens = {
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
token_type: data.token_type,
|
||||
expires_in: data.expires_in,
|
||||
};
|
||||
|
||||
setTokens(newTokens);
|
||||
setUser(data.user);
|
||||
|
||||
localStorage.setItem('hive_tokens', JSON.stringify(newTokens));
|
||||
localStorage.setItem('hive_user', JSON.stringify(data.user));
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Token refresh failed:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const value: AuthContextType = {
|
||||
const login = async (username: string, password: string): Promise<void> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('username', username);
|
||||
formData.append('password', password);
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/auth/login`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.detail || 'Login failed');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const newTokens: AuthTokens = {
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
token_type: data.token_type,
|
||||
expires_in: data.expires_in,
|
||||
};
|
||||
|
||||
setTokens(newTokens);
|
||||
setUser(data.user);
|
||||
|
||||
// Store in localStorage
|
||||
localStorage.setItem('hive_tokens', JSON.stringify(newTokens));
|
||||
localStorage.setItem('hive_user', JSON.stringify(data.user));
|
||||
|
||||
} catch (error: any) {
|
||||
throw new Error(error.message || 'Login failed');
|
||||
}
|
||||
};
|
||||
|
||||
const logout = async (): Promise<void> => {
|
||||
try {
|
||||
// Call logout endpoint if we have a token
|
||||
if (tokens) {
|
||||
await fetch(`${API_BASE_URL}/auth/logout`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${tokens.access_token}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Logout API call failed:', error);
|
||||
} finally {
|
||||
clearAuthData();
|
||||
}
|
||||
};
|
||||
|
||||
const refreshToken = async (): Promise<boolean> => {
|
||||
if (!tokens?.refresh_token) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return await refreshTokenWithStoredData(tokens);
|
||||
};
|
||||
|
||||
const updateUser = (userData: Partial<User>): void => {
|
||||
if (user) {
|
||||
const updatedUser = { ...user, ...userData };
|
||||
setUser(updatedUser);
|
||||
localStorage.setItem('hive_user', JSON.stringify(updatedUser));
|
||||
}
|
||||
};
|
||||
|
||||
const clearAuthData = (): void => {
|
||||
setUser(null);
|
||||
setTokens(null);
|
||||
localStorage.removeItem('hive_tokens');
|
||||
localStorage.removeItem('hive_user');
|
||||
};
|
||||
|
||||
const contextValue: AuthContextType = {
|
||||
user,
|
||||
isAuthenticated: !!user && !!token,
|
||||
tokens,
|
||||
isAuthenticated,
|
||||
isLoading,
|
||||
login,
|
||||
logout,
|
||||
token
|
||||
refreshToken,
|
||||
updateUser,
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
<AuthContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
@@ -107,19 +231,55 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||
|
||||
export const useAuth = (): AuthContextType => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
// Helper hook for protected routes
|
||||
export const useRequireAuth = () => {
|
||||
const { isAuthenticated, isLoading } = useAuth();
|
||||
|
||||
return {
|
||||
isAuthenticated,
|
||||
isLoading,
|
||||
shouldRedirect: !isLoading && !isAuthenticated
|
||||
// Hook for making authenticated API requests
|
||||
export const useAuthenticatedFetch = () => {
|
||||
const { tokens, refreshToken, logout } = useAuth();
|
||||
|
||||
const authenticatedFetch = async (url: string, options: RequestInit = {}): Promise<Response> => {
|
||||
if (!tokens) {
|
||||
throw new Error('No authentication tokens available');
|
||||
}
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
'Authorization': `Bearer ${tokens.access_token}`,
|
||||
};
|
||||
|
||||
let response = await fetch(url, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
// If token expired, try to refresh and retry
|
||||
if (response.status === 401) {
|
||||
const refreshed = await refreshToken();
|
||||
if (refreshed) {
|
||||
// Retry with new token
|
||||
response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...headers,
|
||||
'Authorization': `Bearer ${tokens.access_token}`,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Refresh failed, logout user
|
||||
logout();
|
||||
throw new Error('Authentication expired');
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
};
|
||||
|
||||
return authenticatedFetch;
|
||||
};
|
||||
|
||||
export default AuthContext;
|
||||
Reference in New Issue
Block a user