mirror of https://github.com/kortix-ai/suna.git
Merge pull request #938 from KrishavRajSingh/krishav/feat/manage_key_ui
Krishav/feat/manage key UI
This commit is contained in:
commit
d72f84240a
|
@ -190,6 +190,9 @@ api_router.include_router(pipedream_api.router)
|
||||||
from auth import phone_verification_supabase_mfa
|
from auth import phone_verification_supabase_mfa
|
||||||
api_router.include_router(phone_verification_supabase_mfa.router)
|
api_router.include_router(phone_verification_supabase_mfa.router)
|
||||||
|
|
||||||
|
from local_env_manager import api as local_env_manager_api
|
||||||
|
api_router.include_router(local_env_manager_api.router)
|
||||||
|
|
||||||
@api_router.get("/health")
|
@api_router.get("/health")
|
||||||
async def health_check():
|
async def health_check():
|
||||||
logger.info("Health check endpoint called")
|
logger.info("Health check endpoint called")
|
||||||
|
|
|
@ -0,0 +1,44 @@
|
||||||
|
from fastapi import APIRouter
|
||||||
|
from utils.config import config, EnvMode
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from typing import Dict
|
||||||
|
from dotenv import load_dotenv, set_key, find_dotenv, dotenv_values
|
||||||
|
from utils.logger import logger
|
||||||
|
|
||||||
|
router = APIRouter(tags=["local-env-manager"])
|
||||||
|
|
||||||
|
@router.get("/env-vars")
|
||||||
|
def get_env_vars() -> Dict[str, str]:
|
||||||
|
if config.ENV_MODE != EnvMode.LOCAL:
|
||||||
|
raise HTTPException(status_code=403, detail="Env vars management only available in local mode")
|
||||||
|
|
||||||
|
try:
|
||||||
|
env_path = find_dotenv()
|
||||||
|
if not env_path:
|
||||||
|
logger.error("Could not find .env file")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
return dotenv_values(env_path)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to get env vars: {e}")
|
||||||
|
raise HTTPException(status_code=500, detail=f"Failed to get env variables: {e}")
|
||||||
|
|
||||||
|
@router.post("/env-vars")
|
||||||
|
def save_env_vars(request: Dict[str, str]) -> Dict[str, str]:
|
||||||
|
if config.ENV_MODE != EnvMode.LOCAL:
|
||||||
|
raise HTTPException(status_code=403, detail="Env vars management only available in local mode")
|
||||||
|
|
||||||
|
try:
|
||||||
|
env_path = find_dotenv()
|
||||||
|
if not env_path:
|
||||||
|
raise HTTPException(status_code=500, detail="Could not find .env file")
|
||||||
|
|
||||||
|
for key, value in request.items():
|
||||||
|
set_key(env_path, key, value)
|
||||||
|
|
||||||
|
load_dotenv(override=True)
|
||||||
|
logger.info(f"Env variables saved successfully: {request}")
|
||||||
|
return {"message": "Env variables saved successfully"}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to save env variables: {e}")
|
||||||
|
raise HTTPException(status_code=500, detail=f"Failed to save env variables: {e}")
|
|
@ -37,7 +37,7 @@ services:
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
volumes:
|
volumes:
|
||||||
- ./backend/.env:/app/.env:ro
|
- ./backend/.env:/app/.env
|
||||||
env_file:
|
env_file:
|
||||||
- ./backend/.env
|
- ./backend/.env
|
||||||
environment:
|
environment:
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
import { isLocalMode } from "@/lib/config";
|
||||||
|
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||||
|
import { Shield } from "lucide-react";
|
||||||
|
import { LocalEnvManager } from "@/components/env-manager/local-env-manager";
|
||||||
|
|
||||||
|
export default function LocalEnvManagerPage() {
|
||||||
|
|
||||||
|
return <LocalEnvManager />
|
||||||
|
}
|
|
@ -3,6 +3,7 @@
|
||||||
import { Separator } from '@/components/ui/separator';
|
import { Separator } from '@/components/ui/separator';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { usePathname } from 'next/navigation';
|
import { usePathname } from 'next/navigation';
|
||||||
|
import { isLocalMode } from '@/lib/config';
|
||||||
|
|
||||||
export default function PersonalAccountSettingsPage({
|
export default function PersonalAccountSettingsPage({
|
||||||
children,
|
children,
|
||||||
|
@ -15,6 +16,7 @@ export default function PersonalAccountSettingsPage({
|
||||||
// { name: "Teams", href: "/settings/teams" },
|
// { name: "Teams", href: "/settings/teams" },
|
||||||
{ name: 'Billing', href: '/settings/billing' },
|
{ name: 'Billing', href: '/settings/billing' },
|
||||||
{ name: 'Usage Logs', href: '/settings/usage-logs' },
|
{ name: 'Usage Logs', href: '/settings/usage-logs' },
|
||||||
|
...(isLocalMode() ? [{ name: 'Local .Env Manager', href: '/settings/env-manager' }] : []),
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
|
@ -0,0 +1,224 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Eye, EyeOff, Plus, Trash } from "lucide-react";
|
||||||
|
import { Button } from "../ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";
|
||||||
|
import { isLocalMode } from "@/lib/config";
|
||||||
|
import { Input } from "../ui/input";
|
||||||
|
import { Label } from "../ui/label";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { backendApi } from "@/lib/api-client";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
|
||||||
|
interface APIKeyForm {
|
||||||
|
[key: string]: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LocalEnvManager() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [visibleKeys, setVisibleKeys] = useState<Record<string, boolean>>({});
|
||||||
|
const [newApiKeys, setNewApiKeys] = useState<{key: string, value: string, id: string}[]>([]);
|
||||||
|
|
||||||
|
const {data: apiKeys, isLoading} = useQuery({
|
||||||
|
queryKey: ['api-keys'],
|
||||||
|
queryFn: async() => {
|
||||||
|
const response = await backendApi.get('/env-vars');
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
enabled: isLocalMode()
|
||||||
|
});
|
||||||
|
|
||||||
|
const { register, handleSubmit, formState: { errors, isDirty }, reset } = useForm<APIKeyForm>({
|
||||||
|
defaultValues: apiKeys || {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSave = async (data: APIKeyForm) => {
|
||||||
|
const duplicate_key = newApiKeys.find(entry => data[entry.key.trim()]);
|
||||||
|
if (duplicate_key) {
|
||||||
|
toast.error(`Key ${duplicate_key.key} already exists`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const submitData = {
|
||||||
|
...data,
|
||||||
|
...Object.fromEntries(newApiKeys.map(entry => [entry.key.trim(), entry.value.trim()]))
|
||||||
|
}
|
||||||
|
|
||||||
|
updateApiKeys.mutate(submitData);
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAddNewKey = () => {
|
||||||
|
setNewApiKeys([...newApiKeys, {key: "", value: "", id: crypto.randomUUID()}]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkKeyIsDuplicate = (key: string) => {
|
||||||
|
const trimmedKey = key.trim();
|
||||||
|
const keyIsDuplicate =
|
||||||
|
trimmedKey &&
|
||||||
|
(
|
||||||
|
(apiKeys && Object.keys(apiKeys).includes(trimmedKey)) ||
|
||||||
|
newApiKeys.filter(e => e.key.trim() === trimmedKey).length > 1
|
||||||
|
);
|
||||||
|
return keyIsDuplicate;
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleNewKeyChange = (id: string, field: string, value: string) => {
|
||||||
|
setNewApiKeys(prev =>
|
||||||
|
prev.map(entry => entry.id === id ? {...entry, [field]: value} : entry)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteKey = (id: string) => {
|
||||||
|
setNewApiKeys(prev => prev.filter(entry => entry.id !== id));
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasEmptyKeyValues = newApiKeys.some(entry => entry.key.trim() === "" || entry.value.trim() === "");
|
||||||
|
const hasDuplicateKeys = (): boolean => {
|
||||||
|
const allKeys = [...Object.keys(apiKeys || {}), ...newApiKeys.map(entry => entry.key.trim())];
|
||||||
|
const uniqueKeys = new Set(allKeys);
|
||||||
|
return uniqueKeys.size !== allKeys.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateApiKeys = useMutation({
|
||||||
|
mutationFn: async (data: APIKeyForm) => {
|
||||||
|
const response = await backendApi.post('/env-vars', data);
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ['api-keys'] });
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
onSuccess: (data) => {
|
||||||
|
toast.success(data.message);
|
||||||
|
setNewApiKeys([]);
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error('Failed to update API keys');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const keysArray = apiKeys ? Object.entries(apiKeys).map(([key, value]) => ({
|
||||||
|
id: key,
|
||||||
|
name: key,
|
||||||
|
value: value
|
||||||
|
})) : [];
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (apiKeys) {
|
||||||
|
reset(apiKeys);
|
||||||
|
}
|
||||||
|
}, [apiKeys, reset]);
|
||||||
|
|
||||||
|
const toggleKeyVisibility = (keyId: string) => {
|
||||||
|
setVisibleKeys(prev => ({
|
||||||
|
...prev,
|
||||||
|
[keyId]: !prev[keyId]
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Local .Env Manager</CardTitle>
|
||||||
|
<CardDescription>Loading...</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
</Card>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Local .Env Manager</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{isLocalMode() ? (
|
||||||
|
<>
|
||||||
|
Manage your local environment variables
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
Local .Env Manager is only available in local mode.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
{isLocalMode() && (
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit(handleSave)} className="space-y-4">
|
||||||
|
{keysArray && keysArray?.map(key => (
|
||||||
|
|
||||||
|
<div key={key.id} className="space-y-2">
|
||||||
|
<Label htmlFor={key.id}>{key.name}</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
id={key.id}
|
||||||
|
type={visibleKeys[key.id] ? 'text' : 'password'}
|
||||||
|
placeholder={key.name}
|
||||||
|
{...register(key.id)}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
className="absolute right-0 top-0 h-full px-3"
|
||||||
|
onClick={() => toggleKeyVisibility(key.id)}>
|
||||||
|
{visibleKeys[key.id] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{errors[key.id] && <p className="text-red-500">{errors[key.id]?.message}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
))}
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
{newApiKeys.map(entry => {
|
||||||
|
const keyIsDuplicate = checkKeyIsDuplicate(entry.key);
|
||||||
|
return (
|
||||||
|
|
||||||
|
<div key={entry.id} className="space-y-2">
|
||||||
|
<Label htmlFor={entry.id}>{entry.key || "New API Key"}</Label>
|
||||||
|
<div className="space-x-2 flex">
|
||||||
|
<Input
|
||||||
|
id={`${entry.id}-key`}
|
||||||
|
type="text"
|
||||||
|
placeholder="KEY"
|
||||||
|
value={entry.key}
|
||||||
|
onChange={(e) => handleNewKeyChange(entry.id, 'key', e.target.value)}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
id={`${entry.id}-value`}
|
||||||
|
type="text"
|
||||||
|
placeholder="VALUE"
|
||||||
|
value={entry.value}
|
||||||
|
onChange={(e) => handleNewKeyChange(entry.id, 'value', e.target.value)}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleDeleteKey(entry.id)}
|
||||||
|
>
|
||||||
|
<Trash className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{keyIsDuplicate && <p className="text-red-400 font-light">Key already exists</p>}
|
||||||
|
</div>
|
||||||
|
)})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleAddNewKey}
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add New Key
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="default"
|
||||||
|
disabled={(!isDirty && newApiKeys.length === 0) || hasEmptyKeyValues || hasDuplicateKeys()}
|
||||||
|
>Save</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
}
|
|
@ -17,6 +17,7 @@ import {
|
||||||
AudioWaveform,
|
AudioWaveform,
|
||||||
Sun,
|
Sun,
|
||||||
Moon,
|
Moon,
|
||||||
|
KeyRound,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { useAccounts } from '@/hooks/use-accounts';
|
import { useAccounts } from '@/hooks/use-accounts';
|
||||||
import NewTeamForm from '@/components/basejump/new-team-form';
|
import NewTeamForm from '@/components/basejump/new-team-form';
|
||||||
|
@ -48,6 +49,7 @@ import {
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
import { createClient } from '@/lib/supabase/client';
|
import { createClient } from '@/lib/supabase/client';
|
||||||
import { useTheme } from 'next-themes';
|
import { useTheme } from 'next-themes';
|
||||||
|
import { isLocalMode } from '@/lib/config';
|
||||||
|
|
||||||
export function NavUserWithTeams({
|
export function NavUserWithTeams({
|
||||||
user,
|
user,
|
||||||
|
@ -286,6 +288,12 @@ export function NavUserWithTeams({
|
||||||
Billing
|
Billing
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
{isLocalMode() && <DropdownMenuItem asChild>
|
||||||
|
<Link href="/settings/env-manager">
|
||||||
|
<KeyRound className="h-4 w-4" />
|
||||||
|
Local .Env Manager
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>}
|
||||||
{/* <DropdownMenuItem asChild>
|
{/* <DropdownMenuItem asChild>
|
||||||
<Link href="/settings">
|
<Link href="/settings">
|
||||||
<Settings className="mr-2 h-4 w-4" />
|
<Settings className="mr-2 h-4 w-4" />
|
||||||
|
|
|
@ -14,7 +14,7 @@ import {
|
||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from '@/components/ui/tooltip';
|
} from '@/components/ui/tooltip';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Check, ChevronDown, Search, AlertTriangle, Crown, ArrowUpRight, Brain, Plus, Edit, Trash, Cpu } from 'lucide-react';
|
import { Check, ChevronDown, Search, AlertTriangle, Crown, ArrowUpRight, Brain, Plus, Edit, Trash, Cpu, Key, KeyRound } from 'lucide-react';
|
||||||
import {
|
import {
|
||||||
ModelOption,
|
ModelOption,
|
||||||
SubscriptionStatus,
|
SubscriptionStatus,
|
||||||
|
@ -32,6 +32,7 @@ import { cn } from '@/lib/utils';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import { isLocalMode } from '@/lib/config';
|
import { isLocalMode } from '@/lib/config';
|
||||||
import { CustomModelDialog, CustomModelFormData } from './custom-model-dialog';
|
import { CustomModelDialog, CustomModelFormData } from './custom-model-dialog';
|
||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
interface CustomModel {
|
interface CustomModel {
|
||||||
id: string;
|
id: string;
|
||||||
|
@ -674,6 +675,22 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
|
||||||
<div className="px-3 py-3 flex justify-between items-center">
|
<div className="px-3 py-3 flex justify-between items-center">
|
||||||
<span className="text-xs font-medium text-muted-foreground">All Models</span>
|
<span className="text-xs font-medium text-muted-foreground">All Models</span>
|
||||||
{isLocalMode() && (
|
{isLocalMode() && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Link
|
||||||
|
href="/settings/env-manager"
|
||||||
|
className="h-6 w-6 p-0 flex items-center justify-center"
|
||||||
|
>
|
||||||
|
<KeyRound className="h-3.5 w-3.5" />
|
||||||
|
</Link>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="bottom" className="text-xs">
|
||||||
|
Local .Env Manager
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
|
@ -694,6 +711,7 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{uniqueModels
|
{uniqueModels
|
||||||
|
|
Loading…
Reference in New Issue