mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Add single-user authentication system with Better Auth integration (#76)
* Add Better Auth integration with session management - Implement user authentication using Better Auth library - Add login, register, and sign out functionality - Support passkey/WebAuthn authentication - Create database schema for users, sessions, accounts, passkeys - Add AuthProvider context and ProtectedRoute components - Add account settings page in settings dialog - Protect all API routes with authentication middleware - Update environment configuration for auth providers * Add single-user authentication system with admin setup - Add first-run Setup page for initial admin account creation - Add environment-based admin configuration (ADMIN_EMAIL, ADMIN_PASSWORD) - Add password reset capability via ADMIN_PASSWORD_RESET environment flag - Migrate to data routers with auth loaders, remove ProtectedRoute - Add change password functionality to account settings - Enforce AUTH_SECRET requirement in production - Auto-disable registration when admin is pre-configured via environment * Track busy/idle session status across hooks * Bump version to 0.7.5 * Update pnpm to 10.28.1
This commit is contained in:
1 parent
af292758c3
commit
81a66d2ddb
29 files changed
+2324
-149
No files matched your search
@@ -0,0 +1,348 @@
|
||||
import { useState } from 'react'
|
||||
import { Edit2 } from 'lucide-react'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Loader2, User, KeyRound, LogOut, Plus, Trash2, AlertCircle, CheckCircle, Lock } from 'lucide-react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { passkey, changePassword } from '@/lib/auth-client'
|
||||
|
||||
interface Passkey {
|
||||
id: string
|
||||
name?: string
|
||||
credentialID: string
|
||||
createdAt: string
|
||||
deviceType: string
|
||||
}
|
||||
|
||||
export function AccountSettings() {
|
||||
const { user, addPasskey, logout } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const [passkeyName, setPasskeyName] = useState('')
|
||||
const [currentPassword, setCurrentPassword] = useState('')
|
||||
const [newPassword, setNewPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState<string | null>(null)
|
||||
const [showChangePassword, setShowChangePassword] = useState(false)
|
||||
const [editingProfile, setEditingProfile] = useState(false)
|
||||
|
||||
const { data: passkeys, isLoading: passkeysLoading } = useQuery({
|
||||
queryKey: ['passkeys'],
|
||||
queryFn: async () => {
|
||||
const response = await fetch('/api/auth/passkey/list-user-passkeys', {
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!response.ok) return []
|
||||
return response.json() as Promise<Passkey[]>
|
||||
},
|
||||
enabled: !!user,
|
||||
})
|
||||
|
||||
const addPasskeyMutation = useMutation({
|
||||
mutationFn: async (name: string) => {
|
||||
return addPasskey(name || undefined)
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
} else {
|
||||
setSuccess('Passkey added successfully')
|
||||
setPasskeyName('')
|
||||
queryClient.invalidateQueries({ queryKey: ['passkeys'] })
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to add passkey')
|
||||
},
|
||||
})
|
||||
|
||||
const deletePasskeyMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await passkey.deletePasskey({ id })
|
||||
if (response.error) {
|
||||
throw new Error(response.error.message || 'Failed to delete passkey')
|
||||
}
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
setSuccess('Passkey deleted successfully')
|
||||
queryClient.invalidateQueries({ queryKey: ['passkeys'] })
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete passkey')
|
||||
},
|
||||
})
|
||||
|
||||
const changePasswordMutation = useMutation({
|
||||
mutationFn: async ({ currentPassword, newPassword }: { currentPassword: string; newPassword: string }) => {
|
||||
const response = await changePassword({ currentPassword, newPassword })
|
||||
if (response.error) {
|
||||
throw new Error(response.error.message || 'Failed to change password')
|
||||
}
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
setSuccess('Password changed successfully')
|
||||
setCurrentPassword('')
|
||||
setNewPassword('')
|
||||
setShowChangePassword(false)
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to change password')
|
||||
},
|
||||
})
|
||||
|
||||
const handleAddPasskey = async () => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
addPasskeyMutation.mutate(passkeyName)
|
||||
}
|
||||
|
||||
const handleDeletePasskey = (id: string) => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
if (confirm('Are you sure you want to delete this passkey?')) {
|
||||
deletePasskeyMutation.mutate(id)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChangePassword = () => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
if (newPassword.length < 8) {
|
||||
setError('New password must be at least 8 characters')
|
||||
return
|
||||
}
|
||||
changePasswordMutation.mutate({ currentPassword, newPassword })
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4 sm:space-y-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<Alert className="border-green-500 text-green-700 dark:text-green-400">
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>{success}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-3 sm:pb-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
<CardTitle className="text-base sm:text-lg">Profile</CardTitle>
|
||||
</div>
|
||||
{!editingProfile && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} className="h-8">
|
||||
<Edit2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{editingProfile ? (
|
||||
<div className="space-y-3 sm:space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs sm:text-sm">Name</Label>
|
||||
<Input value={user.name} disabled className="h-9 sm:h-10 text-sm" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs sm:text-sm">Email</Label>
|
||||
<Input value={user.email} disabled className="h-9 sm:h-10 text-sm" />
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setEditingProfile(false)} className="h-9 sm:h-10">
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 sm:space-y-3">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Name</span>
|
||||
<span className="text-sm font-medium truncate">{user.name}</span>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Email</span>
|
||||
<span className="text-sm truncate">{user.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-2 sm:pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
|
||||
<Lock className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
Change Password
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs sm:text-sm">Update your account password</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!showChangePassword ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowChangePassword(true)}
|
||||
className="h-9 sm:h-10"
|
||||
>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Change Password
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-3 sm:space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="current-password" className="text-xs sm:text-sm">Current Password</Label>
|
||||
<Input
|
||||
id="current-password"
|
||||
type="password"
|
||||
value={currentPassword}
|
||||
onChange={(e) => setCurrentPassword(e.target.value)}
|
||||
placeholder="Enter current password"
|
||||
className="h-9 sm:h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="new-password" className="text-xs sm:text-sm">New Password</Label>
|
||||
<Input
|
||||
id="new-password"
|
||||
type="password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="At least 8 characters"
|
||||
className="h-9 sm:h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleChangePassword}
|
||||
disabled={changePasswordMutation.isPending || !currentPassword || !newPassword}
|
||||
className="h-9 sm:h-10"
|
||||
>
|
||||
{changePasswordMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Change Password
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setShowChangePassword(false)}
|
||||
className="h-9 sm:h-10"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-2 sm:pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
|
||||
<KeyRound className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
Passkeys
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs sm:text-sm">Manage passkeys for passwordless sign-in</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 sm:space-y-4">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<Input
|
||||
placeholder="Passkey name (optional)"
|
||||
value={passkeyName}
|
||||
onChange={(e) => setPasskeyName(e.target.value)}
|
||||
className="h-9 sm:h-10 text-sm"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleAddPasskey}
|
||||
disabled={addPasskeyMutation.isPending}
|
||||
className="h-9 sm:h-10 whitespace-nowrap"
|
||||
>
|
||||
{addPasskeyMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Add Passkey
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{passkeysLoading ? (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : passkeys && passkeys.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{passkeys.map((pk) => (
|
||||
<div
|
||||
key={pk.id}
|
||||
className="flex items-center justify-between p-2.5 sm:p-3 bg-muted rounded-lg"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-medium text-sm truncate">{pk.name || 'Unnamed Passkey'}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{pk.deviceType} - {new Date(pk.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 ml-2 flex-shrink-0"
|
||||
onClick={() => handleDeletePasskey(pk.id)}
|
||||
disabled={deletePasskeyMutation.isPending}
|
||||
>
|
||||
{deletePasskeyMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs sm:text-sm text-muted-foreground text-center py-3">
|
||||
No passkeys registered. Add one for passwordless sign-in.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-2 sm:pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-base sm:text-lg text-destructive">
|
||||
<LogOut className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
Sign Out
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs sm:text-sm">Sign out of your account</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button variant="destructive" onClick={logout} className="h-9 sm:h-10">
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sign Out
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export function ProviderSettings() {
|
||||
const [oauthDialogOpen, setOauthDialogOpen] = useState(false)
|
||||
const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false)
|
||||
const [oauthResponse, setOauthResponse] = useState<OAuthAuthorizeResponse | null>(null)
|
||||
const [connectedExpanded, setConnectedExpanded] = useState(true)
|
||||
const [connectedExpanded, setConnectedExpanded] = useState(false)
|
||||
const [availableExpanded, setAvailableExpanded] = useState(false)
|
||||
const [availableSearch, setAvailableSearch] = useState('')
|
||||
const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false)
|
||||
@@ -173,7 +173,7 @@ export function ProviderSettings() {
|
||||
|
||||
return (
|
||||
<Card key={provider.id} className="bg-card border-border">
|
||||
<CardHeader className="p-4">
|
||||
<CardHeader className="p-2">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<CardTitle className="text-base">
|
||||
@@ -357,39 +357,36 @@ export function ProviderSettings() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-h-64 overflow-y-auto">
|
||||
<div className="space-y-2 max-h-64 overflow-y-auto scrollbar-thin pt-4 pb-1 pr-1 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{filteredAvailableProviders.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-2">
|
||||
{availableSearch ? 'No providers match your search.' : 'No available providers.'}
|
||||
</p>
|
||||
) : (
|
||||
filteredAvailableProviders.map((provider) => {
|
||||
filteredAvailableProviders.map((provider, index) => {
|
||||
const modelCount = Object.keys(provider.models || {}).length
|
||||
return (
|
||||
<Card key={provider.id} className="bg-card border-border">
|
||||
<CardHeader className="p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<CardTitle className="text-sm truncate">
|
||||
{provider.name || provider.id}
|
||||
</CardTitle>
|
||||
{modelCount > 0 && (
|
||||
<CardDescription className="text-xs">
|
||||
{modelCount} model{modelCount !== 1 ? 's' : ''}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleAddApiKey(provider)}
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 mr-1" />
|
||||
Add Key
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<div key={provider.id} className={`flex items-center justify-between gap-2 py-1.5 px-2 rounded-md hover:bg-accent/80 transition-colors ${index % 2 === 1 ? 'bg-accent/30' : ''}`}>
|
||||
<div className="flex-1 min-w-0">
|
||||
<span className="text-sm truncate block">
|
||||
{provider.name || provider.id}
|
||||
</span>
|
||||
{modelCount > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{modelCount} model{modelCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleAddApiKey(provider)}
|
||||
className="h-7 px-2"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 mr-1" />
|
||||
Add Key
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
|
||||
@@ -4,9 +4,10 @@ import { GitSettings } from '@/components/settings/GitSettings'
|
||||
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
|
||||
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
||||
import { AccountSettings } from '@/components/settings/AccountSettings'
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch } from 'lucide-react'
|
||||
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch, User } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
|
||||
@@ -15,7 +16,7 @@ interface SettingsDialogProps {
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers'
|
||||
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account'
|
||||
|
||||
export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
const [mobileView, setMobileView] = useState<SettingsView>('menu')
|
||||
@@ -39,6 +40,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
}, [bindSwipe])
|
||||
|
||||
const menuItems = [
|
||||
{ id: 'account', icon: User, label: 'Account', description: 'Profile, passkeys, and sign out' },
|
||||
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
|
||||
{ id: 'git', icon: GitBranch, label: 'Git', description: 'Git identity and credentials for repositories' },
|
||||
{ id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' },
|
||||
@@ -65,9 +67,12 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
Settings
|
||||
</h2>
|
||||
</div>
|
||||
<Tabs defaultValue="general" className="w-full flex flex-col flex-1 min-h-0">
|
||||
<Tabs defaultValue="account" className="w-full flex flex-col flex-1 min-h-0">
|
||||
<div className="px-6 pt-6 pb-4 flex-shrink-0">
|
||||
<TabsList className="grid w-full grid-cols-5 bg-card border border-border p-1">
|
||||
<TabsList className="grid w-full grid-cols-6 bg-card p-1">
|
||||
<TabsTrigger value="account" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
|
||||
Account
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="general" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
|
||||
General
|
||||
</TabsTrigger>
|
||||
@@ -88,6 +93,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="px-6 pb-6">
|
||||
<TabsContent value="account" className="mt-0"><AccountSettings /></TabsContent>
|
||||
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
|
||||
<TabsContent value="git" className="mt-0"><GitSettings /></TabsContent>
|
||||
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
||||
@@ -148,6 +154,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{mobileView === 'account' && <AccountSettings />}
|
||||
{mobileView === 'general' && <GeneralSettings />}
|
||||
{mobileView === 'git' && <GitSettings />}
|
||||
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
|
||||
|
||||
Reference in new issue
Block a user