Compare commits
2 Commits
59f160609b
...
f2772c392c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2772c392c | ||
|
|
936d48fbb9 |
32
src/App.tsx
32
src/App.tsx
@@ -11,6 +11,7 @@ import { PlaylistsPage } from './pages/PlaylistsPage'
|
||||
import { ExtractionsPage } from './pages/ExtractionsPage'
|
||||
import { UsersPage } from './pages/admin/UsersPage'
|
||||
import { SettingsPage } from './pages/admin/SettingsPage'
|
||||
import { AccountPage } from './pages/AccountPage'
|
||||
import { Toaster } from './components/ui/sonner'
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
@@ -27,6 +28,24 @@ function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
function AdminRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, loading } = useAuth()
|
||||
|
||||
if (loading) {
|
||||
return <div className="min-h-screen flex items-center justify-center">Loading...</div>
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/login" replace />
|
||||
}
|
||||
|
||||
if (user.role !== 'admin') {
|
||||
return <Navigate to="/" replace />
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
function AppRoutes() {
|
||||
const { user } = useAuth()
|
||||
|
||||
@@ -55,15 +74,20 @@ function AppRoutes() {
|
||||
<ExtractionsPage />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/admin/users" element={
|
||||
<Route path="/account" element={
|
||||
<ProtectedRoute>
|
||||
<UsersPage />
|
||||
<AccountPage />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route path="/admin/users" element={
|
||||
<AdminRoute>
|
||||
<UsersPage />
|
||||
</AdminRoute>
|
||||
} />
|
||||
<Route path="/admin/settings" element={
|
||||
<ProtectedRoute>
|
||||
<AdminRoute>
|
||||
<SettingsPage />
|
||||
</ProtectedRoute>
|
||||
</AdminRoute>
|
||||
} />
|
||||
</Routes>
|
||||
)
|
||||
|
||||
@@ -29,6 +29,8 @@ export const API_CONFIG = {
|
||||
OAUTH_AUTHORIZE: (provider: string) => `/api/v1/auth/${provider}/authorize`,
|
||||
OAUTH_CALLBACK: (provider: string) => `/api/v1/auth/${provider}/callback`,
|
||||
EXCHANGE_OAUTH_TOKEN: '/api/v1/auth/exchange-oauth-token',
|
||||
API_TOKEN: '/api/v1/auth/api-token',
|
||||
API_TOKEN_STATUS: '/api/v1/auth/api-token/status',
|
||||
},
|
||||
},
|
||||
} as const
|
||||
|
||||
54
src/lib/api/services/admin.ts
Normal file
54
src/lib/api/services/admin.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { apiClient } from '../client'
|
||||
import type { User } from '@/types/auth'
|
||||
|
||||
export interface Plan {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
description?: string
|
||||
credits: number
|
||||
max_credits: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface UserUpdate {
|
||||
name?: string
|
||||
plan_id?: number
|
||||
credits?: number
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
export interface MessageResponse {
|
||||
message: string
|
||||
}
|
||||
|
||||
export class AdminService {
|
||||
async listUsers(limit = 100, offset = 0): Promise<User[]> {
|
||||
return apiClient.get<User[]>(`/api/v1/admin/users/`, {
|
||||
params: { limit, offset }
|
||||
})
|
||||
}
|
||||
|
||||
async getUser(userId: number): Promise<User> {
|
||||
return apiClient.get<User>(`/api/v1/admin/users/${userId}`)
|
||||
}
|
||||
|
||||
async updateUser(userId: number, data: UserUpdate): Promise<User> {
|
||||
return apiClient.patch<User>(`/api/v1/admin/users/${userId}`, data)
|
||||
}
|
||||
|
||||
async disableUser(userId: number): Promise<MessageResponse> {
|
||||
return apiClient.post<MessageResponse>(`/api/v1/admin/users/${userId}/disable`)
|
||||
}
|
||||
|
||||
async enableUser(userId: number): Promise<MessageResponse> {
|
||||
return apiClient.post<MessageResponse>(`/api/v1/admin/users/${userId}/enable`)
|
||||
}
|
||||
|
||||
async listPlans(): Promise<Plan[]> {
|
||||
return apiClient.get<Plan[]>(`/api/v1/admin/users/plans/list`)
|
||||
}
|
||||
}
|
||||
|
||||
export const adminService = new AdminService()
|
||||
@@ -36,6 +36,36 @@ export interface ExchangeOAuthTokenResponse {
|
||||
user_id: string
|
||||
}
|
||||
|
||||
export interface ApiTokenRequest {
|
||||
expires_days?: number
|
||||
}
|
||||
|
||||
export interface ApiTokenResponse {
|
||||
api_token: string
|
||||
expires_at?: string
|
||||
}
|
||||
|
||||
export interface ApiTokenStatusResponse {
|
||||
has_token: boolean
|
||||
expires_at?: string
|
||||
is_expired: boolean
|
||||
}
|
||||
|
||||
export interface UpdateProfileRequest {
|
||||
name?: string
|
||||
}
|
||||
|
||||
export interface ChangePasswordRequest {
|
||||
current_password?: string
|
||||
new_password: string
|
||||
}
|
||||
|
||||
export interface UserProvider {
|
||||
provider: string
|
||||
display_name: string
|
||||
connected_at?: string
|
||||
}
|
||||
|
||||
export class AuthService {
|
||||
/**
|
||||
* Authenticate user with email and password
|
||||
@@ -150,6 +180,48 @@ export class AuthService {
|
||||
throw new Error('Token refresh failed')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user profile information
|
||||
*/
|
||||
async updateProfile(data: UpdateProfileRequest): Promise<User> {
|
||||
return apiClient.patch<User>(API_CONFIG.ENDPOINTS.AUTH.ME, data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Change user password
|
||||
*/
|
||||
async changePassword(data: ChangePasswordRequest): Promise<void> {
|
||||
return apiClient.post<void>('/api/v1/auth/change-password', data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new API token
|
||||
*/
|
||||
async generateApiToken(request: ApiTokenRequest = {}): Promise<ApiTokenResponse> {
|
||||
return apiClient.post<ApiTokenResponse>(API_CONFIG.ENDPOINTS.AUTH.API_TOKEN, request)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get API token status
|
||||
*/
|
||||
async getApiTokenStatus(): Promise<ApiTokenStatusResponse> {
|
||||
return apiClient.get<ApiTokenStatusResponse>(API_CONFIG.ENDPOINTS.AUTH.API_TOKEN_STATUS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete API token
|
||||
*/
|
||||
async deleteApiToken(): Promise<void> {
|
||||
return apiClient.delete<void>(API_CONFIG.ENDPOINTS.AUTH.API_TOKEN)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user's connected authentication providers
|
||||
*/
|
||||
async getUserProviders(): Promise<UserProvider[]> {
|
||||
return apiClient.get<UserProvider[]>('/api/v1/auth/user-providers')
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService()
|
||||
652
src/pages/AccountPage.tsx
Normal file
652
src/pages/AccountPage.tsx
Normal file
@@ -0,0 +1,652 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { AppLayout } from '@/components/AppLayout'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
User,
|
||||
Key,
|
||||
Shield,
|
||||
Palette,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Copy,
|
||||
Trash2,
|
||||
Github,
|
||||
Mail,
|
||||
CheckCircle2
|
||||
} from 'lucide-react'
|
||||
import { useAuth } from '@/contexts/AuthContext'
|
||||
import { useTheme } from '@/hooks/use-theme'
|
||||
import { authService, type ApiTokenStatusResponse, type UserProvider } from '@/lib/api/services/auth'
|
||||
|
||||
export function AccountPage() {
|
||||
const { user, setUser } = useAuth()
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
// Profile state
|
||||
const [profileName, setProfileName] = useState('')
|
||||
const [profileSaving, setProfileSaving] = useState(false)
|
||||
|
||||
// Password state
|
||||
const [passwordData, setPasswordData] = useState({
|
||||
current_password: '',
|
||||
new_password: '',
|
||||
confirm_password: ''
|
||||
})
|
||||
const [passwordSaving, setPasswordSaving] = useState(false)
|
||||
const [showCurrentPassword, setShowCurrentPassword] = useState(false)
|
||||
const [showNewPassword, setShowNewPassword] = useState(false)
|
||||
|
||||
// API Token state
|
||||
const [apiTokenStatus, setApiTokenStatus] = useState<ApiTokenStatusResponse | null>(null)
|
||||
const [apiTokenLoading, setApiTokenLoading] = useState(true)
|
||||
const [generatedToken, setGeneratedToken] = useState('')
|
||||
const [showGeneratedToken, setShowGeneratedToken] = useState(false)
|
||||
const [tokenExpireDays, setTokenExpireDays] = useState('365')
|
||||
|
||||
// Providers state
|
||||
const [providers, setProviders] = useState<UserProvider[]>([])
|
||||
const [providersLoading, setProvidersLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setProfileName(user.name)
|
||||
}
|
||||
loadApiTokenStatus()
|
||||
loadProviders()
|
||||
}, [user])
|
||||
|
||||
const loadApiTokenStatus = async () => {
|
||||
try {
|
||||
const status = await authService.getApiTokenStatus()
|
||||
setApiTokenStatus(status)
|
||||
} catch (error) {
|
||||
console.error('Failed to load API token status:', error)
|
||||
} finally {
|
||||
setApiTokenLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadProviders = async () => {
|
||||
try {
|
||||
const userProviders = await authService.getUserProviders()
|
||||
setProviders(userProviders)
|
||||
} catch (error) {
|
||||
console.error('Failed to load providers:', error)
|
||||
setProviders([])
|
||||
} finally {
|
||||
setProvidersLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleProfileSave = async () => {
|
||||
if (!user || !profileName.trim()) return
|
||||
|
||||
setProfileSaving(true)
|
||||
try {
|
||||
const updatedUser = await authService.updateProfile({ name: profileName.trim() })
|
||||
setUser?.(updatedUser)
|
||||
toast.success('Profile updated successfully')
|
||||
} catch (error) {
|
||||
toast.error('Failed to update profile')
|
||||
console.error('Profile update error:', error)
|
||||
} finally {
|
||||
setProfileSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePasswordChange = async () => {
|
||||
// Check if user has password authentication from providers
|
||||
const hasPasswordProvider = providers.some(provider => provider.provider === 'password')
|
||||
|
||||
// Validate required fields
|
||||
if (hasPasswordProvider && !passwordData.current_password) {
|
||||
toast.error('Current password is required')
|
||||
return
|
||||
}
|
||||
|
||||
if (!passwordData.new_password) {
|
||||
toast.error('New password is required')
|
||||
return
|
||||
}
|
||||
|
||||
if (passwordData.new_password !== passwordData.confirm_password) {
|
||||
toast.error('New passwords do not match')
|
||||
return
|
||||
}
|
||||
|
||||
if (passwordData.new_password.length < 8) {
|
||||
toast.error('New password must be at least 8 characters long')
|
||||
return
|
||||
}
|
||||
|
||||
setPasswordSaving(true)
|
||||
try {
|
||||
await authService.changePassword({
|
||||
current_password: hasPasswordProvider ? passwordData.current_password : undefined,
|
||||
new_password: passwordData.new_password
|
||||
})
|
||||
setPasswordData({ current_password: '', new_password: '', confirm_password: '' })
|
||||
toast.success(hasPasswordProvider ? 'Password changed successfully' : 'Password set successfully')
|
||||
|
||||
// Reload providers since password status might have changed
|
||||
loadProviders()
|
||||
} catch (error) {
|
||||
toast.error('Failed to change password')
|
||||
console.error('Password change error:', error)
|
||||
} finally {
|
||||
setPasswordSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleGenerateApiToken = async () => {
|
||||
try {
|
||||
const response = await authService.generateApiToken({
|
||||
expires_days: parseInt(tokenExpireDays)
|
||||
})
|
||||
setGeneratedToken(response.api_token)
|
||||
setShowGeneratedToken(true)
|
||||
await loadApiTokenStatus()
|
||||
toast.success('API token generated successfully')
|
||||
} catch (error) {
|
||||
toast.error('Failed to generate API token')
|
||||
console.error('API token generation error:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteApiToken = async () => {
|
||||
try {
|
||||
await authService.deleteApiToken()
|
||||
await loadApiTokenStatus()
|
||||
toast.success('API token deleted successfully')
|
||||
} catch (error) {
|
||||
toast.error('Failed to delete API token')
|
||||
console.error('API token deletion error:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
toast.success('Copied to clipboard')
|
||||
}
|
||||
|
||||
const getProviderIcon = (provider: string) => {
|
||||
switch (provider.toLowerCase()) {
|
||||
case 'github':
|
||||
return <Github className="h-4 w-4" />
|
||||
case 'google':
|
||||
return <Mail className="h-4 w-4" />
|
||||
case 'password':
|
||||
return <Key className="h-4 w-4" />
|
||||
default:
|
||||
return <Shield className="h-4 w-4" />
|
||||
}
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<AppLayout
|
||||
breadcrumb={{
|
||||
items: [
|
||||
{ label: 'Dashboard', href: '/' },
|
||||
{ label: 'Account' }
|
||||
]
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 rounded-xl bg-muted/50 p-4">
|
||||
<Skeleton className="h-8 w-48 mb-6" />
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-6 w-32" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</AppLayout>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppLayout
|
||||
breadcrumb={{
|
||||
items: [
|
||||
{ label: 'Dashboard', href: '/' },
|
||||
{ label: 'Account' }
|
||||
]
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-3xl font-bold">Account Settings</h1>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Profile Information */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<User className="h-5 w-5" />
|
||||
Profile Information
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email Address</Label>
|
||||
<Input
|
||||
id="email"
|
||||
value={user.email}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Email cannot be changed
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Display Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={profileName}
|
||||
onChange={(e) => setProfileName(e.target.value)}
|
||||
placeholder="Enter your display name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Account Details</Label>
|
||||
<div className="text-sm text-muted-foreground space-y-1">
|
||||
<div>Role: <Badge variant={user.role === 'admin' ? 'destructive' : 'secondary'}>{user.role}</Badge></div>
|
||||
<div>Credits: <span className="font-medium">{user.credits.toLocaleString()}</span></div>
|
||||
<div>Plan: <span className="font-medium">{user.plan.name}</span></div>
|
||||
<div>Member since: {new Date(user.created_at).toLocaleDateString()}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleProfileSave}
|
||||
disabled={profileSaving || profileName === user.name}
|
||||
className="w-full"
|
||||
>
|
||||
{profileSaving ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Theme Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Palette className="h-5 w-5" />
|
||||
Appearance
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Theme Preference</Label>
|
||||
<Select value={theme} onValueChange={(value: 'light' | 'dark' | 'system') => setTheme(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="light">Light</SelectItem>
|
||||
<SelectItem value="dark">Dark</SelectItem>
|
||||
<SelectItem value="system">System</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Choose how the interface appears to you
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="pt-4">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Current theme: <span className="font-medium capitalize">{theme}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Password Management */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5" />
|
||||
Security
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{providers.some(provider => provider.provider === 'password') ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="current-password">Current Password</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="current-password"
|
||||
type={showCurrentPassword ? 'text' : 'password'}
|
||||
value={passwordData.current_password}
|
||||
onChange={(e) => setPasswordData(prev => ({ ...prev, current_password: e.target.value }))}
|
||||
placeholder="Enter current password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowCurrentPassword(!showCurrentPassword)}
|
||||
>
|
||||
{showCurrentPassword ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-password">New Password</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="new-password"
|
||||
type={showNewPassword ? 'text' : 'password'}
|
||||
value={passwordData.new_password}
|
||||
onChange={(e) => setPasswordData(prev => ({ ...prev, new_password: e.target.value }))}
|
||||
placeholder="Enter new password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowNewPassword(!showNewPassword)}
|
||||
>
|
||||
{showNewPassword ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirm-password">Confirm New Password</Label>
|
||||
<Input
|
||||
id="confirm-password"
|
||||
type="password"
|
||||
value={passwordData.confirm_password}
|
||||
onChange={(e) => setPasswordData(prev => ({ ...prev, confirm_password: e.target.value }))}
|
||||
placeholder="Confirm new password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handlePasswordChange}
|
||||
disabled={passwordSaving}
|
||||
className="w-full"
|
||||
>
|
||||
{passwordSaving ? 'Changing Password...' : 'Change Password'}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
💡 <strong>Set up password authentication</strong>
|
||||
<br />
|
||||
You signed up with OAuth and don't have a password yet. Set one now to enable password login.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-password">Create Password</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="new-password"
|
||||
type={showNewPassword ? 'text' : 'password'}
|
||||
value={passwordData.new_password}
|
||||
onChange={(e) => setPasswordData(prev => ({ ...prev, new_password: e.target.value }))}
|
||||
placeholder="Enter your new password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowNewPassword(!showNewPassword)}
|
||||
>
|
||||
{showNewPassword ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirm-password">Confirm Password</Label>
|
||||
<Input
|
||||
id="confirm-password"
|
||||
type="password"
|
||||
value={passwordData.confirm_password}
|
||||
onChange={(e) => setPasswordData(prev => ({ ...prev, confirm_password: e.target.value }))}
|
||||
placeholder="Confirm your password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handlePasswordChange}
|
||||
disabled={passwordSaving}
|
||||
className="w-full"
|
||||
>
|
||||
{passwordSaving ? 'Setting Password...' : 'Set Password'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* API Token Management */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Key className="h-5 w-5" />
|
||||
API Token
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{apiTokenLoading ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{apiTokenStatus?.has_token ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>API Token Active</span>
|
||||
{apiTokenStatus.expires_at && (
|
||||
<span className="text-muted-foreground">
|
||||
(Expires: {new Date(apiTokenStatus.expires_at).toLocaleDateString()})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleDeleteApiToken}
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Token
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="expire-days">Token Expiration</Label>
|
||||
<Select value={tokenExpireDays} onValueChange={setTokenExpireDays}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="30">30 days</SelectItem>
|
||||
<SelectItem value="90">90 days</SelectItem>
|
||||
<SelectItem value="365">1 year</SelectItem>
|
||||
<SelectItem value="3650">10 years</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button onClick={handleGenerateApiToken} className="w-full">
|
||||
Generate API Token
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
API tokens allow external applications to access your account programmatically
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Authentication Providers */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5" />
|
||||
Authentication Methods
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available methods to sign in to your account. Use any of these to access your account.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{providersLoading ? (
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 2 }).map((_, i) => (
|
||||
<div key={i} className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-8 w-20" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{/* All Authentication Providers from API */}
|
||||
{providers.map((provider) => {
|
||||
const isOAuth = provider.provider !== 'password'
|
||||
|
||||
return (
|
||||
<div key={provider.provider} className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
{getProviderIcon(provider.provider)}
|
||||
<span className="font-medium">{provider.display_name}</span>
|
||||
<Badge variant="secondary">
|
||||
{isOAuth ? 'OAuth' : 'Password Authentication'}
|
||||
</Badge>
|
||||
{provider.connected_at && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Connected {new Date(provider.connected_at).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant="outline" className="text-green-700 border-green-200 bg-green-50 dark:text-green-400 dark:border-green-800 dark:bg-green-900/20">
|
||||
Available
|
||||
</Badge>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* API Token Provider */}
|
||||
{apiTokenStatus?.has_token && (
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4" />
|
||||
<span className="font-medium">API Token</span>
|
||||
<Badge variant="secondary">API Access</Badge>
|
||||
{apiTokenStatus.expires_at && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Expires {new Date(apiTokenStatus.expires_at).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant="outline" className="text-blue-700 border-blue-200 bg-blue-50 dark:text-blue-400 dark:border-blue-800 dark:bg-blue-900/20">
|
||||
Available
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{providers.length === 0 && !apiTokenStatus?.has_token && (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
No authentication methods configured
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Generated Token Dialog */}
|
||||
<Dialog open={showGeneratedToken} onOpenChange={setShowGeneratedToken}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>API Token Generated</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Your API Token</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={generatedToken}
|
||||
readOnly
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => copyToClipboard(generatedToken)}
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded-lg">
|
||||
<p className="text-sm text-yellow-800 dark:text-yellow-200">
|
||||
⚠️ <strong>Important:</strong> This token will only be shown once.
|
||||
Copy it now and store it securely.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setShowGeneratedToken(false)} className="w-full">
|
||||
I've Saved My Token
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</AppLayout>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,121 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { AppLayout } from '@/components/AppLayout'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Sheet, SheetContent } from '@/components/ui/sheet'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { toast } from 'sonner'
|
||||
import { Edit, UserCheck, UserX } from 'lucide-react'
|
||||
import { adminService, type Plan } from '@/lib/api/services/admin'
|
||||
import type { User } from '@/types/auth'
|
||||
|
||||
interface EditUserData {
|
||||
name: string
|
||||
plan_id: number
|
||||
credits: number
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
export function UsersPage() {
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
const [plans, setPlans] = useState<Plan[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [editingUser, setEditingUser] = useState<User | null>(null)
|
||||
const [editData, setEditData] = useState<EditUserData>({
|
||||
name: '',
|
||||
plan_id: 0,
|
||||
credits: 0,
|
||||
is_active: true
|
||||
})
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
loadData()
|
||||
}, [])
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const [usersData, plansData] = await Promise.all([
|
||||
adminService.listUsers(),
|
||||
adminService.listPlans()
|
||||
])
|
||||
setUsers(usersData)
|
||||
setPlans(plansData)
|
||||
} catch (error) {
|
||||
toast.error('Failed to load data')
|
||||
console.error('Error loading data:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEditUser = (user: User) => {
|
||||
setEditingUser(user)
|
||||
setEditData({
|
||||
name: user.name,
|
||||
plan_id: user.plan.id,
|
||||
credits: user.credits,
|
||||
is_active: user.is_active
|
||||
})
|
||||
}
|
||||
|
||||
const handleSaveUser = async () => {
|
||||
if (!editingUser) return
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const updatedUser = await adminService.updateUser(editingUser.id, editData)
|
||||
setUsers(prev => prev.map(u => u.id === editingUser.id ? updatedUser : u))
|
||||
setEditingUser(null)
|
||||
toast.success('User updated successfully')
|
||||
} catch (error) {
|
||||
toast.error('Failed to update user')
|
||||
console.error('Error updating user:', error)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleUserStatus = async (user: User) => {
|
||||
try {
|
||||
if (user.is_active) {
|
||||
await adminService.disableUser(user.id)
|
||||
toast.success('User disabled successfully')
|
||||
} else {
|
||||
await adminService.enableUser(user.id)
|
||||
toast.success('User enabled successfully')
|
||||
}
|
||||
// Reload data to get updated user status
|
||||
loadData()
|
||||
} catch (error) {
|
||||
toast.error(`Failed to ${user.is_active ? 'disable' : 'enable'} user`)
|
||||
console.error('Error toggling user status:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const getRoleBadge = (role: string) => {
|
||||
return (
|
||||
<Badge variant={role === 'admin' ? 'destructive' : 'secondary'}>
|
||||
{role}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
const getStatusBadge = (isActive: boolean) => {
|
||||
return (
|
||||
<Badge variant={isActive ? 'default' : 'secondary'}>
|
||||
{isActive ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<AppLayout
|
||||
breadcrumb={{
|
||||
@@ -11,12 +126,245 @@ export function UsersPage() {
|
||||
]
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 rounded-xl bg-muted/50 p-4">
|
||||
<h1 className="text-2xl font-bold mb-4">User Management</h1>
|
||||
<p className="text-muted-foreground">
|
||||
User administration interface coming soon...
|
||||
</p>
|
||||
<div className="flex-1 space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className="h-10 w-32" />
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-6 w-32" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-12 w-full" />
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</AppLayout>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppLayout
|
||||
breadcrumb={{
|
||||
items: [
|
||||
{ label: 'Dashboard', href: '/' },
|
||||
{ label: 'Admin' },
|
||||
{ label: 'Users' }
|
||||
]
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-3xl font-bold">User Management</h1>
|
||||
<Button onClick={loadData} disabled={loading}>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Users ({users.length})</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Role</TableHead>
|
||||
<TableHead>Plan</TableHead>
|
||||
<TableHead>Credits</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">{user.name}</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell>{getRoleBadge(user.role)}</TableCell>
|
||||
<TableCell>{user.plan.name}</TableCell>
|
||||
<TableCell>{user.credits.toLocaleString()}</TableCell>
|
||||
<TableCell>{getStatusBadge(user.is_active)}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleEditUser(user)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleToggleUserStatus(user)}
|
||||
>
|
||||
{user.is_active ? (
|
||||
<UserX className="h-4 w-4" />
|
||||
) : (
|
||||
<UserCheck className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Edit User Sheet */}
|
||||
<Sheet open={!!editingUser} onOpenChange={(open) => !open && setEditingUser(null)}>
|
||||
<SheetContent className="w-full sm:max-w-lg overflow-y-auto">
|
||||
<div className="px-6">
|
||||
<div className="pt-4 pb-6">
|
||||
<h2 className="text-xl font-semibold">Edit User</h2>
|
||||
</div>
|
||||
|
||||
{editingUser && (
|
||||
<div className="space-y-8 pb-6">
|
||||
{/* User Information Section */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-semibold text-base">User Information</h3>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
<div className="grid grid-cols-3 gap-2 text-sm">
|
||||
<span className="text-muted-foreground font-medium">User ID:</span>
|
||||
<span className="col-span-2 font-mono">{editingUser.id}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-sm">
|
||||
<span className="text-muted-foreground font-medium">Email:</span>
|
||||
<span className="col-span-2 break-all">{editingUser.email}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-sm">
|
||||
<span className="text-muted-foreground font-medium">Role:</span>
|
||||
<span className="col-span-2">{getRoleBadge(editingUser.role)}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-sm">
|
||||
<span className="text-muted-foreground font-medium">Created:</span>
|
||||
<span className="col-span-2">{new Date(editingUser.created_at).toLocaleDateString()}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-sm">
|
||||
<span className="text-muted-foreground font-medium">Last Updated:</span>
|
||||
<span className="col-span-2">{new Date(editingUser.updated_at).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Editable Fields Section */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-semibold text-base">Editable Settings</h3>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name" className="text-sm font-medium">Display Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={editData.name}
|
||||
onChange={(e) => setEditData(prev => ({ ...prev, name: e.target.value }))}
|
||||
placeholder="Enter user's display name"
|
||||
className="h-10"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This is the name displayed throughout the application
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="plan" className="text-sm font-medium">Subscription Plan</Label>
|
||||
<Select
|
||||
value={editData.plan_id.toString()}
|
||||
onValueChange={(value) => setEditData(prev => ({ ...prev, plan_id: parseInt(value) }))}
|
||||
>
|
||||
<SelectTrigger className="h-10">
|
||||
<SelectValue placeholder="Select a plan" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{plans.map((plan) => (
|
||||
<SelectItem key={plan.id} value={plan.id.toString()}>
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="font-medium">{plan.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{plan.max_credits.toLocaleString()} max credits
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Current plan: <span className="font-medium">{editingUser.plan.name}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="credits" className="text-sm font-medium">Current Credits</Label>
|
||||
<Input
|
||||
id="credits"
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
value={editData.credits}
|
||||
onChange={(e) => setEditData(prev => ({ ...prev, credits: parseInt(e.target.value) || 0 }))}
|
||||
placeholder="Enter credit amount"
|
||||
className="h-10"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Maximum allowed: <span className="font-medium">{editingUser.plan.max_credits.toLocaleString()}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium">Account Status</Label>
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-medium">Allow Login Access</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{editData.is_active ? 'User can log in and use the platform' : 'User is blocked from logging in and accessing the platform'}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
id="active"
|
||||
checked={editData.is_active}
|
||||
onCheckedChange={(checked) => setEditData(prev => ({ ...prev, is_active: checked }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex gap-3 pt-6 border-t">
|
||||
<Button
|
||||
onClick={handleSaveUser}
|
||||
disabled={saving}
|
||||
className="flex-1 h-11"
|
||||
>
|
||||
{saving ? 'Saving Changes...' : 'Save Changes'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setEditingUser(null)}
|
||||
disabled={saving}
|
||||
className="px-6 h-11"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</AppLayout>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user