User management

This commit is contained in:
Louis Knight-Webb
2025-06-14 16:26:48 -04:00
parent e099269ed2
commit ca231bd6be
31 changed files with 2581 additions and 56 deletions

View File

@@ -1,25 +1,48 @@
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
interface ApiResponse<T> {
success: boolean
data?: T
message?: string
}
import { Alert, AlertDescription } from '@/components/ui/alert'
import { ProjectsPage } from '@/components/projects/projects-page'
import { UsersPage } from '@/components/users/users-page'
import { LoginForm } from '@/components/auth/login-form'
import { ApiResponse } from 'shared/types'
import { authStorage, isAuthenticated, logout, makeAuthenticatedRequest } from '@/lib/auth'
import { ArrowLeft, Heart, Activity, FolderOpen, Users, CheckCircle, AlertCircle, LogOut } from 'lucide-react'
function App() {
const [currentPage, setCurrentPage] = useState<'home' | 'projects' | 'users'>('home')
const [message, setMessage] = useState<string>('')
const [messageType, setMessageType] = useState<'success' | 'error'>('success')
const [loading, setLoading] = useState(false)
const [authenticated, setAuthenticated] = useState(false)
const currentUser = authStorage.getUser()
useEffect(() => {
setAuthenticated(isAuthenticated())
}, [])
const handleLogin = () => {
setAuthenticated(true)
setCurrentPage('home')
}
const handleLogout = () => {
logout()
setAuthenticated(false)
setCurrentPage('home')
}
const fetchHello = async () => {
setLoading(true)
try {
const response = await fetch('/api/hello?name=Bloop')
const response = await makeAuthenticatedRequest('/api/hello?name=Bloop')
const data = await response.json()
setMessage(data.message)
setMessageType('success')
} catch (error) {
setMessage('Error connecting to backend')
setMessageType('error')
} finally {
setLoading(false)
}
@@ -28,42 +51,240 @@ function App() {
const checkHealth = async () => {
setLoading(true)
try {
const response = await fetch('/api/health')
const response = await makeAuthenticatedRequest('/api/health')
const data: ApiResponse<string> = await response.json()
setMessage(data.message || 'Health check completed')
setMessageType('success')
} catch (error) {
setMessage('Backend health check failed')
setMessageType('error')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen bg-background p-8">
<div className="max-w-2xl mx-auto">
<Card>
<CardHeader>
<CardTitle>Welcome to Bloop</CardTitle>
<CardDescription>
A full-stack monorepo with Rust backend and React frontend
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-4">
<Button onClick={fetchHello} disabled={loading}>
Say Hello
</Button>
<Button onClick={checkHealth} variant="outline" disabled={loading}>
Check Health
</Button>
</div>
{message && (
<div className="p-4 bg-muted rounded-md">
<p className="text-sm">{message}</p>
if (!authenticated) {
return <LoginForm onSuccess={handleLogin} />
}
if (currentPage === 'projects' || currentPage === 'users') {
return (
<div className="min-h-screen bg-background">
<div className="border-b">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<div className="flex items-center space-x-6">
<h2 className="text-lg font-semibold">Bloop</h2>
<div className="flex items-center space-x-1">
<Button
variant={currentPage === 'projects' ? 'default' : 'ghost'}
size="sm"
onClick={() => setCurrentPage('projects')}
>
<FolderOpen className="mr-2 h-4 w-4" />
Projects
</Button>
{currentUser?.is_admin && (
<Button
variant={currentPage === 'users' ? 'default' : 'ghost'}
size="sm"
onClick={() => setCurrentPage('users')}
>
<Users className="mr-2 h-4 w-4" />
Users
</Button>
)}
</div>
</div>
<div className="flex items-center space-x-4">
<div className="text-sm text-muted-foreground">
Welcome, {currentUser?.email}
</div>
<Button variant="ghost" onClick={() => setCurrentPage('home')}>
<ArrowLeft className="mr-2 h-4 w-4" />
Home
</Button>
<Button variant="ghost" onClick={handleLogout}>
<LogOut className="mr-2 h-4 w-4" />
Logout
</Button>
</div>
</div>
</div>
</div>
<div className="max-w-7xl mx-auto p-6 sm:p-8">
{currentPage === 'projects' ? <ProjectsPage /> : <UsersPage />}
</div>
</div>
)
}
return (
<div className="min-h-screen bg-gradient-to-br from-background to-muted/20">
<div className="container mx-auto px-4 py-12">
<div className="max-w-4xl mx-auto">
<div className="text-center mb-12">
<div className="flex items-center justify-center mb-6">
<div className="rounded-full bg-primary/10 p-4">
<Heart className="h-8 w-8 text-primary" />
</div>
</div>
<h1 className="text-4xl font-bold tracking-tight mb-4">
Welcome to Bloop
</h1>
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
A modern full-stack monorepo built with Rust backend and React frontend.
Get started by exploring our features below.
</p>
</div>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 mb-8">
<Card className="hover:shadow-md transition-shadow">
<CardHeader>
<div className="flex items-center">
<div className="rounded-lg bg-blue-100 p-2 mr-3">
<Heart className="h-5 w-5 text-blue-600" />
</div>
<CardTitle className="text-lg">API Test</CardTitle>
</div>
<CardDescription>
Test the connection between frontend and backend
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={fetchHello}
disabled={loading}
className="w-full"
size="sm"
>
<Heart className="mr-2 h-4 w-4" />
Say Hello
</Button>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader>
<div className="flex items-center">
<div className="rounded-lg bg-green-100 p-2 mr-3">
<Activity className="h-5 w-5 text-green-600" />
</div>
<CardTitle className="text-lg">Health Check</CardTitle>
</div>
<CardDescription>
Monitor the health status of your backend services
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={checkHealth}
variant="outline"
disabled={loading}
className="w-full"
size="sm"
>
<Activity className="mr-2 h-4 w-4" />
Check Health
</Button>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader>
<div className="flex items-center">
<div className="rounded-lg bg-purple-100 p-2 mr-3">
<FolderOpen className="h-5 w-5 text-purple-600" />
</div>
<CardTitle className="text-lg">Projects</CardTitle>
</div>
<CardDescription>
Manage your projects with full CRUD operations
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={() => setCurrentPage('projects')}
className="w-full"
size="sm"
>
<FolderOpen className="mr-2 h-4 w-4" />
View Projects
</Button>
</CardContent>
</Card>
{currentUser?.is_admin && (
<Card className="hover:shadow-md transition-shadow">
<CardHeader>
<div className="flex items-center">
<div className="rounded-lg bg-orange-100 p-2 mr-3">
<Users className="h-5 w-5 text-orange-600" />
</div>
<CardTitle className="text-lg">Users</CardTitle>
</div>
<CardDescription>
Manage user accounts and permissions
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={() => setCurrentPage('users')}
className="w-full"
size="sm"
>
<Users className="mr-2 h-4 w-4" />
Manage Users
</Button>
</CardContent>
</Card>
)}
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader>
<div className="flex items-center">
<div className="rounded-lg bg-red-100 p-2 mr-3">
<LogOut className="h-5 w-5 text-red-600" />
</div>
<CardTitle className="text-lg">Account</CardTitle>
</div>
<CardDescription>
Logged in as {currentUser?.email}
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={handleLogout}
variant="outline"
className="w-full"
size="sm"
>
<LogOut className="mr-2 h-4 w-4" />
Logout
</Button>
</CardContent>
</Card>
</div>
{message && (
<Alert variant={messageType === 'error' ? 'destructive' : 'default'} className="max-w-2xl mx-auto">
{messageType === 'error' ? (
<AlertCircle className="h-4 w-4" />
) : (
<CheckCircle className="h-4 w-4" />
)}
<AlertDescription>
{message}
</AlertDescription>
</Alert>
)}
<div className="mt-12 text-center">
<p className="text-sm text-muted-foreground">
Built with using Rust, React, TypeScript, and Tailwind CSS
</p>
</div>
</div>
</div>
</div>
)

View File

@@ -0,0 +1,118 @@
import { useState } from 'react'
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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { LoginRequest, LoginResponse, ApiResponse } from 'shared/types'
import { authStorage } from '@/lib/auth'
import { LogIn, AlertCircle } from 'lucide-react'
interface LoginFormProps {
onSuccess: () => void
}
export function LoginForm({ onSuccess }: LoginFormProps) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
const loginData: LoginRequest = { email, password }
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(loginData),
})
if (!response.ok) {
if (response.status === 401) {
throw new Error('Invalid email or password')
}
throw new Error('Login failed')
}
const data: ApiResponse<LoginResponse> = await response.json()
if (data.success && data.data) {
authStorage.setToken(data.data.token)
authStorage.setUser(data.data.user)
onSuccess()
} else {
throw new Error('Login failed')
}
} catch (error) {
setError(error instanceof Error ? error.message : 'An error occurred')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted/20">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
<LogIn className="h-6 w-6 text-primary" />
</div>
<CardTitle className="text-2xl">Welcome back</CardTitle>
<CardDescription>
Sign in to your account to continue
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
required
/>
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{error}
</AlertDescription>
</Alert>
)}
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</Button>
</form>
<div className="mt-6 text-center text-sm text-muted-foreground">
<p>Default admin credentials:</p>
<p>Email: admin@example.com</p>
<p>Password: Check your ADMIN_PASSWORD env var</p>
</div>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,211 @@
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Project, ApiResponse } from 'shared/types'
import { ProjectForm } from './project-form'
import { ArrowLeft, Edit, Trash2, Calendar, Clock, User, AlertCircle, Loader2 } from 'lucide-react'
interface ProjectDetailProps {
projectId: string
onBack: () => void
}
export function ProjectDetail({ projectId, onBack }: ProjectDetailProps) {
const [project, setProject] = useState<Project | null>(null)
const [loading, setLoading] = useState(false)
const [showEditForm, setShowEditForm] = useState(false)
const [error, setError] = useState('')
const fetchProject = async () => {
setLoading(true)
setError('')
try {
const response = await fetch(`/api/projects/${projectId}`)
const data: ApiResponse<Project> = await response.json()
if (data.success && data.data) {
setProject(data.data)
} else {
setError('Project not found')
}
} catch (error) {
console.error('Failed to fetch project:', error)
setError('Failed to load project')
} finally {
setLoading(false)
}
}
const handleDelete = async () => {
if (!project) return
if (!confirm(`Are you sure you want to delete "${project.name}"? This action cannot be undone.`)) return
try {
const response = await fetch(`/api/projects/${projectId}`, {
method: 'DELETE',
})
if (response.ok) {
onBack()
}
} catch (error) {
console.error('Failed to delete project:', error)
setError('Failed to delete project')
}
}
const handleEditSuccess = () => {
setShowEditForm(false)
fetchProject()
}
useEffect(() => {
fetchProject()
}, [projectId])
if (loading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Loading project...
</div>
)
}
if (error || !project) {
return (
<div className="space-y-4">
<Button variant="outline" onClick={onBack}>
<ArrowLeft className="mr-2 h-4 w-4" />
Back to Projects
</Button>
<Card>
<CardContent className="py-12 text-center">
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-lg bg-muted">
<AlertCircle className="h-6 w-6 text-muted-foreground" />
</div>
<h3 className="mt-4 text-lg font-semibold">Project not found</h3>
<p className="mt-2 text-sm text-muted-foreground">
{error || 'The project you\'re looking for doesn\'t exist or has been deleted.'}
</p>
<Button className="mt-4" onClick={onBack}>
Back to Projects
</Button>
</CardContent>
</Card>
</div>
)
}
return (
<div className="space-y-6">
<div className="flex justify-between items-start">
<div className="flex items-center space-x-4">
<Button variant="outline" onClick={onBack}>
<ArrowLeft className="mr-2 h-4 w-4" />
Back to Projects
</Button>
<div>
<h1 className="text-2xl font-bold">{project.name}</h1>
<p className="text-sm text-muted-foreground">Project details and settings</p>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={() => setShowEditForm(true)}>
<Edit className="mr-2 h-4 w-4" />
Edit
</Button>
<Button
variant="outline"
onClick={handleDelete}
className="text-red-600 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</Button>
</div>
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{error}
</AlertDescription>
</Alert>
)}
<div className="grid gap-6 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<Calendar className="mr-2 h-5 w-5" />
Project Information
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-muted-foreground">Status</span>
<Badge variant="secondary">Active</Badge>
</div>
<div className="space-y-2">
<div className="flex items-center text-sm">
<Calendar className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Created:</span>
<span className="ml-2">{new Date(project.created_at).toLocaleDateString()}</span>
</div>
<div className="flex items-center text-sm">
<Clock className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Last Updated:</span>
<span className="ml-2">{new Date(project.updated_at).toLocaleDateString()}</span>
</div>
<div className="flex items-center text-sm">
<User className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Owner ID:</span>
<code className="ml-2 text-xs bg-muted px-1 py-0.5 rounded">
{project.owner_id.substring(0, 8)}...
</code>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Project Details</CardTitle>
<CardDescription>
Technical information about this project
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div>
<h4 className="text-sm font-medium text-muted-foreground">Project ID</h4>
<code className="mt-1 block text-xs bg-muted p-2 rounded font-mono">
{project.id}
</code>
</div>
<div>
<h4 className="text-sm font-medium text-muted-foreground">Created At</h4>
<p className="mt-1 text-sm">
{new Date(project.created_at).toLocaleString()}
</p>
</div>
<div>
<h4 className="text-sm font-medium text-muted-foreground">Last Modified</h4>
<p className="mt-1 text-sm">
{new Date(project.updated_at).toLocaleString()}
</p>
</div>
</CardContent>
</Card>
</div>
<ProjectForm
open={showEditForm}
onClose={() => setShowEditForm(false)}
onSuccess={handleEditSuccess}
project={project}
/>
</div>
)
}

View File

@@ -0,0 +1,127 @@
import { useState } from 'react'
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 { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Project, CreateProject, UpdateProject } from 'shared/types'
import { AlertCircle } from 'lucide-react'
interface ProjectFormProps {
open: boolean
onClose: () => void
onSuccess: () => void
project?: Project | null
}
export function ProjectForm({ open, onClose, onSuccess, project }: ProjectFormProps) {
const [name, setName] = useState(project?.name || '')
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const isEditing = !!project
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
if (isEditing) {
const updateData: UpdateProject = { name }
const response = await fetch(`/api/projects/${project.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updateData),
})
if (!response.ok) {
throw new Error('Failed to update project')
}
} else {
// For now, using a placeholder owner_id - this should come from auth
const createData: CreateProject = {
name,
owner_id: '00000000-0000-0000-0000-000000000000'
}
const response = await fetch('/api/projects', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(createData),
})
if (!response.ok) {
throw new Error('Failed to create project')
}
}
onSuccess()
setName('')
} catch (error) {
setError(error instanceof Error ? error.message : 'An error occurred')
} finally {
setLoading(false)
}
}
const handleClose = () => {
setName(project?.name || '')
setError('')
onClose()
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>
{isEditing ? 'Edit Project' : 'Create New Project'}
</DialogTitle>
<DialogDescription>
{isEditing
? 'Make changes to your project here. Click save when you\'re done.'
: 'Add a new project to your workspace. You can always edit it later.'
}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Project Name</Label>
<Input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter project name"
required
/>
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{error}
</AlertDescription>
</Alert>
)}
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={handleClose}
disabled={loading}
>
Cancel
</Button>
<Button type="submit" disabled={loading || !name.trim()}>
{loading ? 'Saving...' : isEditing ? 'Save Changes' : 'Create Project'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,169 @@
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Project, ApiResponse } from 'shared/types'
import { ProjectForm } from './project-form'
import { Plus, Edit, Trash2, Calendar, AlertCircle, Loader2 } from 'lucide-react'
export function ProjectList() {
const [projects, setProjects] = useState<Project[]>([])
const [loading, setLoading] = useState(false)
const [showForm, setShowForm] = useState(false)
const [editingProject, setEditingProject] = useState<Project | null>(null)
const [error, setError] = useState('')
const fetchProjects = async () => {
setLoading(true)
setError('')
try {
const response = await fetch('/api/projects')
const data: ApiResponse<Project[]> = await response.json()
if (data.success && data.data) {
setProjects(data.data)
} else {
setError('Failed to load projects')
}
} catch (error) {
console.error('Failed to fetch projects:', error)
setError('Failed to connect to server')
} finally {
setLoading(false)
}
}
const handleDelete = async (id: string, name: string) => {
if (!confirm(`Are you sure you want to delete "${name}"? This action cannot be undone.`)) return
try {
const response = await fetch(`/api/projects/${id}`, {
method: 'DELETE',
})
if (response.ok) {
fetchProjects()
}
} catch (error) {
console.error('Failed to delete project:', error)
setError('Failed to delete project')
}
}
const handleEdit = (project: Project) => {
setEditingProject(project)
setShowForm(true)
}
const handleFormSuccess = () => {
setShowForm(false)
setEditingProject(null)
fetchProjects()
}
useEffect(() => {
fetchProjects()
}, [])
return (
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold tracking-tight">Projects</h1>
<p className="text-muted-foreground">
Manage your projects and track their progress
</p>
</div>
<Button onClick={() => setShowForm(true)}>
<Plus className="mr-2 h-4 w-4" />
Create Project
</Button>
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{error}
</AlertDescription>
</Alert>
)}
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Loading projects...
</div>
) : projects.length === 0 ? (
<Card>
<CardContent className="py-12 text-center">
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-lg bg-muted">
<Plus className="h-6 w-6" />
</div>
<h3 className="mt-4 text-lg font-semibold">No projects yet</h3>
<p className="mt-2 text-sm text-muted-foreground">
Get started by creating your first project.
</p>
<Button
className="mt-4"
onClick={() => setShowForm(true)}
>
<Plus className="mr-2 h-4 w-4" />
Create your first project
</Button>
</CardContent>
</Card>
) : (
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{projects.map((project) => (
<Card key={project.id} className="hover:shadow-md transition-shadow">
<CardHeader className="pb-3">
<div className="flex items-start justify-between">
<CardTitle className="text-lg">{project.name}</CardTitle>
<Badge variant="secondary" className="ml-2">
Active
</Badge>
</div>
<CardDescription className="flex items-center">
<Calendar className="mr-1 h-3 w-3" />
Created {new Date(project.created_at).toLocaleDateString()}
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleEdit(project)}
className="h-8"
>
<Edit className="mr-1 h-3 w-3" />
Edit
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleDelete(project.id, project.name)}
className="h-8 text-red-600 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="mr-1 h-3 w-3" />
Delete
</Button>
</div>
</CardContent>
</Card>
))}
</div>
)}
<ProjectForm
open={showForm}
onClose={() => {
setShowForm(false)
setEditingProject(null)
}}
onSuccess={handleFormSuccess}
project={editingProject}
/>
</div>
)
}

View File

@@ -0,0 +1,18 @@
import { useState } from 'react'
import { ProjectList } from './project-list'
import { ProjectDetail } from './project-detail'
export function ProjectsPage() {
const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null)
if (selectedProjectId) {
return (
<ProjectDetail
projectId={selectedProjectId}
onBack={() => setSelectedProjectId(null)}
/>
)
}
return <ProjectList />
}

View File

@@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

View File

@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,113 @@
import * as React from "react"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & {
open?: boolean
onOpenChange?: (open: boolean) => void
}
>(({ className, open, onOpenChange, children, ...props }, ref) => {
if (!open) return null
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<div
className="fixed inset-0 bg-black/50"
onClick={() => onOpenChange?.(false)}
/>
<div
ref={ref}
className={cn(
"relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg duration-200 sm:rounded-lg",
className
)}
{...props}
>
<button
className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
onClick={() => onOpenChange?.(false)}
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</button>
{children}
</div>
</div>
)
})
Dialog.displayName = "Dialog"
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = "DialogTitle"
const DialogDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = "DialogDescription"
const DialogContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("grid gap-4", className)} {...props} />
))
DialogContent.displayName = "DialogContent"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
export {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
}

View File

@@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }

View File

@@ -0,0 +1,117 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,185 @@
import { useState } from 'react'
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 { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { User, CreateUser, UpdateUser } from 'shared/types'
import { makeAuthenticatedRequest, authStorage } from '@/lib/auth'
import { AlertCircle } from 'lucide-react'
interface UserFormProps {
open: boolean
onClose: () => void
onSuccess: () => void
user?: User | null
}
export function UserForm({ open, onClose, onSuccess, user }: UserFormProps) {
const [email, setEmail] = useState(user?.email || '')
const [password, setPassword] = useState('')
const [isAdmin, setIsAdmin] = useState(user?.is_admin || false)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const currentUser = authStorage.getUser()
const isEditing = !!user
const canEditAdminStatus = currentUser?.is_admin && currentUser.id !== user?.id
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
if (isEditing) {
const updateData: UpdateUser = {
email: email !== user.email ? email : undefined,
password: password ? password : undefined,
is_admin: canEditAdminStatus && isAdmin !== user.is_admin ? isAdmin : undefined
}
// Remove undefined values
Object.keys(updateData).forEach(key => {
if (updateData[key as keyof UpdateUser] === undefined) {
delete updateData[key as keyof UpdateUser]
}
})
const response = await makeAuthenticatedRequest(`/api/users/${user.id}`, {
method: 'PUT',
body: JSON.stringify(updateData),
})
if (!response.ok) {
throw new Error('Failed to update user')
}
} else {
if (!password) {
throw new Error('Password is required for new users')
}
const createData: CreateUser = {
email,
password,
is_admin: currentUser?.is_admin ? isAdmin : false
}
const response = await makeAuthenticatedRequest('/api/users', {
method: 'POST',
body: JSON.stringify(createData),
})
if (!response.ok) {
if (response.status === 409) {
throw new Error('A user with this email already exists')
}
throw new Error('Failed to create user')
}
}
onSuccess()
resetForm()
} catch (error) {
setError(error instanceof Error ? error.message : 'An error occurred')
} finally {
setLoading(false)
}
}
const resetForm = () => {
setEmail(user?.email || '')
setPassword('')
setIsAdmin(user?.is_admin || false)
setError('')
}
const handleClose = () => {
resetForm()
onClose()
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>
{isEditing ? 'Edit User' : 'Create New User'}
</DialogTitle>
<DialogDescription>
{isEditing
? 'Make changes to the user account here. Click save when you\'re done.'
: 'Add a new user to the system. They will be able to log in with these credentials.'
}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter email address"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">
{isEditing ? 'New Password (leave blank to keep current)' : 'Password'}
</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={isEditing ? "Enter new password" : "Enter password"}
required={!isEditing}
/>
</div>
{canEditAdminStatus && (
<div className="flex items-center space-x-2">
<input
type="checkbox"
id="isAdmin"
checked={isAdmin}
onChange={(e) => setIsAdmin(e.target.checked)}
className="rounded border-gray-300"
/>
<Label htmlFor="isAdmin" className="text-sm font-medium">
Administrator privileges
</Label>
</div>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{error}
</AlertDescription>
</Alert>
)}
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={handleClose}
disabled={loading}
>
Cancel
</Button>
<Button type="submit" disabled={loading || !email.trim()}>
{loading ? 'Saving...' : isEditing ? 'Save Changes' : 'Create User'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,188 @@
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { User, ApiResponse } from 'shared/types'
import { UserForm } from './user-form'
import { makeAuthenticatedRequest, authStorage } from '@/lib/auth'
import { Plus, Edit, Trash2, Calendar, AlertCircle, Loader2, Shield, User as UserIcon } from 'lucide-react'
export function UserList() {
const [users, setUsers] = useState<User[]>([])
const [loading, setLoading] = useState(false)
const [showForm, setShowForm] = useState(false)
const [editingUser, setEditingUser] = useState<User | null>(null)
const [error, setError] = useState('')
const currentUser = authStorage.getUser()
const fetchUsers = async () => {
setLoading(true)
setError('')
try {
const response = await makeAuthenticatedRequest('/api/users')
const data: ApiResponse<User[]> = await response.json()
if (data.success && data.data) {
setUsers(data.data)
} else {
setError('Failed to load users')
}
} catch (error) {
console.error('Failed to fetch users:', error)
setError('Failed to connect to server')
} finally {
setLoading(false)
}
}
const handleDelete = async (id: string, email: string) => {
if (!confirm(`Are you sure you want to delete user "${email}"? This action cannot be undone.`)) return
try {
const response = await makeAuthenticatedRequest(`/api/users/${id}`, {
method: 'DELETE',
})
if (response.ok) {
fetchUsers()
} else if (response.status === 403) {
setError('You cannot delete this user')
} else {
setError('Failed to delete user')
}
} catch (error) {
console.error('Failed to delete user:', error)
setError('Failed to delete user')
}
}
const handleEdit = (user: User) => {
setEditingUser(user)
setShowForm(true)
}
const handleFormSuccess = () => {
setShowForm(false)
setEditingUser(null)
fetchUsers()
}
useEffect(() => {
fetchUsers()
}, [])
return (
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold tracking-tight">Users</h1>
<p className="text-muted-foreground">
Manage user accounts and permissions
</p>
</div>
{currentUser?.is_admin && (
<Button onClick={() => setShowForm(true)}>
<Plus className="mr-2 h-4 w-4" />
Add User
</Button>
)}
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{error}
</AlertDescription>
</Alert>
)}
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Loading users...
</div>
) : users.length === 0 ? (
<Card>
<CardContent className="py-12 text-center">
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-lg bg-muted">
<UserIcon className="h-6 w-6" />
</div>
<h3 className="mt-4 text-lg font-semibold">No users found</h3>
<p className="mt-2 text-sm text-muted-foreground">
Get started by creating the first user account.
</p>
{currentUser?.is_admin && (
<Button
className="mt-4"
onClick={() => setShowForm(true)}
>
<Plus className="mr-2 h-4 w-4" />
Add your first user
</Button>
)}
</CardContent>
</Card>
) : (
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{users.map((user) => (
<Card key={user.id} className="hover:shadow-md transition-shadow">
<CardHeader className="pb-3">
<div className="flex items-start justify-between">
<CardTitle className="text-lg flex items-center">
{user.is_admin ? (
<Shield className="mr-2 h-4 w-4 text-orange-500" />
) : (
<UserIcon className="mr-2 h-4 w-4 text-blue-500" />
)}
{user.email}
</CardTitle>
<Badge variant={user.is_admin ? "default" : "secondary"}>
{user.is_admin ? "Admin" : "User"}
</Badge>
</div>
<CardDescription className="flex items-center">
<Calendar className="mr-1 h-3 w-3" />
Joined {new Date(user.created_at).toLocaleDateString()}
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleEdit(user)}
className="h-8"
>
<Edit className="mr-1 h-3 w-3" />
Edit
</Button>
{currentUser?.is_admin && currentUser.id !== user.id && (
<Button
variant="outline"
size="sm"
onClick={() => handleDelete(user.id, user.email)}
className="h-8 text-red-600 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="mr-1 h-3 w-3" />
Delete
</Button>
)}
</div>
</CardContent>
</Card>
))}
</div>
)}
<UserForm
open={showForm}
onClose={() => {
setShowForm(false)
setEditingUser(null)
}}
onSuccess={handleFormSuccess}
user={editingUser}
/>
</div>
)
}

View File

@@ -0,0 +1,5 @@
import { UserList } from './user-list'
export function UsersPage() {
return <UserList />
}

63
frontend/src/lib/auth.ts Normal file
View File

@@ -0,0 +1,63 @@
import { User } from 'shared/types'
const TOKEN_KEY = 'auth_token'
const USER_KEY = 'auth_user'
export const authStorage = {
getToken: (): string | null => {
return localStorage.getItem(TOKEN_KEY)
},
setToken: (token: string): void => {
localStorage.setItem(TOKEN_KEY, token)
},
removeToken: (): void => {
localStorage.removeItem(TOKEN_KEY)
},
getUser: (): User | null => {
const user = localStorage.getItem(USER_KEY)
return user ? JSON.parse(user) : null
},
setUser: (user: User): void => {
localStorage.setItem(USER_KEY, JSON.stringify(user))
},
removeUser: (): void => {
localStorage.removeItem(USER_KEY)
},
clear: (): void => {
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(USER_KEY)
}
}
export const getAuthHeaders = (): Record<string, string> => {
const token = authStorage.getToken()
return token ? { Authorization: `Bearer ${token}` } : {}
}
export const makeAuthenticatedRequest = async (url: string, options: RequestInit = {}) => {
const headers = {
'Content-Type': 'application/json',
...getAuthHeaders(),
...(options.headers || {})
}
return fetch(url, {
...options,
headers
})
}
export const isAuthenticated = (): boolean => {
return !!authStorage.getToken()
}
export const logout = (): void => {
authStorage.clear()
window.location.href = '/'
}