Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

Add APIKEYS to settings

Khuram Niaz3bf64a6edd75
diff --git a/prisma/migrations/20260219201822_apply/migration.sql b/prisma/migrations/20260219201822_apply/migration.sql
new file mode 100644
index 0000000..810b8ef
--- /dev/null
+++ b/prisma/migrations/20260219201822_apply/migration.sql
@@ -0,0 +1,20 @@
+-- CreateTable
+CREATE TABLE "ApiKey" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "userId" TEXT NOT NULL,
+ "provider" TEXT NOT NULL,
+ "encryptedKey" TEXT NOT NULL,
+ "iv" TEXT NOT NULL,
+ "last4" TEXT NOT NULL,
+ "label" TEXT,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ "lastUsedAt" DATETIME,
+ CONSTRAINT "ApiKey_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- CreateIndex
+CREATE INDEX "ApiKey_userId_idx" ON "ApiKey"("userId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "ApiKey_userId_provider_key" ON "ApiKey"("userId", "provider");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 07678aa..d7436a1 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -30,6 +30,24 @@ model User {
Task Task[]
Automation Automation[]
Settings UserSettings?
+ ApiKey ApiKey[]
+}
+
+model ApiKey {
+ id String @id @default(uuid())
+ userId String
+ user User @relation(fields: [userId], references: [id])
+ provider String
+ encryptedKey String
+ iv String
+ last4 String
+ label String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ lastUsedAt DateTime?
+
+ @@unique([userId, provider])
+ @@index([userId])
}
model UserSettings {
diff --git a/src/actions/apiKey.actions.ts b/src/actions/apiKey.actions.ts
new file mode 100644
index 0000000..2b10880
--- /dev/null
+++ b/src/actions/apiKey.actions.ts
@@ -0,0 +1,145 @@
+"use server";
+
+import db from "@/lib/db";
+import { getCurrentUser } from "@/utils/user.utils";
+import { handleError } from "@/lib/utils";
+import { encrypt, getLast4 } from "@/lib/encryption";
+import { apiKeySaveSchema } from "@/models/apiKey.schema";
+import type { ApiKeyClientResponse, ApiKeyProvider } from "@/models/apiKey.model";
+
+export async function getUserApiKeys(): Promise<{
+ success: boolean;
+ data?: ApiKeyClientResponse[];
+ message?: string;
+}> {
+ try {
+ const user = await getCurrentUser();
+ if (!user) return { success: false, message: "Not authenticated" };
+
+ const keys = await db.apiKey.findMany({
+ where: { userId: user.id },
+ select: {
+ id: true,
+ provider: true,
+ last4: true,
+ label: true,
+ createdAt: true,
+ lastUsedAt: true,
+ },
+ });
+
+ return {
+ success: true,
+ data: keys.map((k) => ({
+ ...k,
+ provider: k.provider as ApiKeyProvider,
+ })),
+ };
+ } catch (error) {
+ return handleError(error, "Failed to fetch API keys") as {
+ success: boolean;
+ message: string;
+ };
+ }
+}
+
+export async function saveApiKey(input: {
+ provider: string;
+ key: string;
+ label?: string;
+}): Promise<{
+ success: boolean;
+ data?: ApiKeyClientResponse;
+ message?: string;
+}> {
+ try {
+ const user = await getCurrentUser();
+ if (!user) return { success: false, message: "Not authenticated" };
+
+ const parsed = apiKeySaveSchema.parse(input);
+ const { encrypted, iv } = encrypt(parsed.key);
+ const last4 = getLast4(parsed.key);
+
+ const apiKey = await db.apiKey.upsert({
+ where: {
+ userId_provider: {
+ userId: user.id,
+ provider: parsed.provider,
+ },
+ },
+ create: {
+ userId: user.id,
+ provider: parsed.provider,
+ encryptedKey: encrypted,
+ iv,
+ last4,
+ label: parsed.label,
+ },
+ update: {
+ encryptedKey: encrypted,
+ iv,
+ last4,
+ label: parsed.label,
+ },
+ select: {
+ id: true,
+ provider: true,
+ last4: true,
+ label: true,
+ createdAt: true,
+ lastUsedAt: true,
+ },
+ });
+
+ return {
+ success: true,
+ data: { ...apiKey, provider: apiKey.provider as ApiKeyProvider },
+ };
+ } catch (error) {
+ return handleError(error, "Failed to save API key") as {
+ success: boolean;
+ message: string;
+ };
+ }
+}
+
+export async function deleteApiKey(provider: string): Promise<{
+ success: boolean;
+ message?: string;
+}> {
+ try {
+ const user = await getCurrentUser();
+ if (!user) return { success: false, message: "Not authenticated" };
+
+ await db.apiKey.deleteMany({
+ where: { userId: user.id, provider },
+ });
+
+ return { success: true };
+ } catch (error) {
+ return handleError(error, "Failed to delete API key") as {
+ success: boolean;
+ message: string;
+ };
+ }
+}
+
+export async function getOllamaBaseUrl(): Promise<string> {
+ try {
+ const user = await getCurrentUser();
+ if (user) {
+ const apiKey = await db.apiKey.findUnique({
+ where: {
+ userId_provider: { userId: user.id, provider: "ollama" },
+ },
+ });
+ if (apiKey) {
+ const { decrypt } = await import("@/lib/encryption");
+ return decrypt(apiKey.encryptedKey, apiKey.iv);
+ }
+ }
+ } catch {
+ // Fall through to defaults
+ }
+ return process.env.OLLAMA_BASE_URL || "http://127.0.0.1:11434";
+}
diff --git a/src/app/api/ai/deepseek/models/route.ts b/src/app/api/ai/deepseek/models/route.ts
index 4322c14..a7f8cac 100644
--- a/src/app/api/ai/deepseek/models/route.ts
+++ b/src/app/api/ai/deepseek/models/route.ts
@@ -1,8 +1,13 @@
+import { auth } from "@/auth";
import { NextResponse } from "next/server";
+import { resolveApiKey } from "@/lib/api-key-resolver";
export async function GET() {
try {
- const apiKey = process.env.DEEPSEEK_API_KEY;
+ const session = await auth();
+ const userId = session?.user?.id;
+
+ const apiKey = await resolveApiKey(userId, "deepseek");
if (!apiKey) {
return NextResponse.json(
diff --git a/src/app/api/ai/resume/match/route.ts b/src/app/api/ai/resume/match/route.ts
index 1fc40b9..1c12998 100644
--- a/src/app/api/ai/resume/match/route.ts
+++ b/src/app/api/ai/resume/match/route.ts
@@ -90,9 +90,10 @@ export const POST = async (req: NextRequest) => {
const { normalizedText: resumeText } = resumePreprocessResult.data;
const { normalizedText: jobText } = jobPreprocessResult.data;
- const model = getModel(
+ const model = await getModel(
selectedModel.provider,
selectedModel.model || "llama3.2",
+ userId,
);
// Single comprehensive LLM call
diff --git a/src/app/api/ai/resume/review/route.ts b/src/app/api/ai/resume/review/route.ts
index 5f151d7..055ea86 100644
--- a/src/app/api/ai/resume/review/route.ts
+++ b/src/app/api/ai/resume/review/route.ts
@@ -65,9 +65,10 @@ export const POST = async (req: NextRequest) => {
}
const { normalizedText } = preprocessResult.data;
- const model = getModel(
+ const model = await getModel(
selectedModel.provider,
selectedModel.model || "llama3.2",
+ userId,
);
// Single comprehensive LLM call
diff --git a/src/app/api/settings/api-keys/verify/route.ts b/src/app/api/settings/api-keys/verify/route.ts
new file mode 100644
index 0000000..1be9982
--- /dev/null
+++ b/src/app/api/settings/api-keys/verify/route.ts
@@ -0,0 +1,93 @@
+import { auth } from "@/auth";
+import { NextRequest, NextResponse } from "next/server";
+
+export async function POST(req: NextRequest) {
+ const session = await auth();
+ if (!session?.user?.id) {
+ return NextResponse.json({ success: false, error: "Not authenticated" }, { status: 401 });
+ }
+
+ const { provider, key } = await req.json();
+
+ if (!provider || !key) {
+ return NextResponse.json(
+ { success: false, error: "Provider and key are required" },
+ { status: 400 },
+ );
+ }
+
+ try {
+ switch (provider) {
+ case "openai": {
+ const res = await fetch("https://api.openai.com/v1/models", {
+ headers: { Authorization: `Bearer ${key}` },
+ });
+ if (!res.ok) {
+ return NextResponse.json({
+ success: false,
+ error: res.status === 401 ? "Invalid API key" : `OpenAI returned ${res.status}`,
+ });
+ }
+ return NextResponse.json({ success: true });
+ }
+
+ case "deepseek": {
+ const res = await fetch("https://api.deepseek.com/models", {
+ headers: { Authorization: `Bearer ${key}` },
+ });
+ if (!res.ok) {
+ return NextResponse.json({
+ success: false,
+ error: res.status === 401 ? "Invalid API key" : `DeepSeek returned ${res.status}`,
+ });
+ }
+ return NextResponse.json({ success: true });
+ }
+
+ case "rapidapi": {
+ const res = await fetch(
+ "https://jsearch.p.rapidapi.com/search?query=test&num_pages=1",
+ {
+ headers: {
+ "X-RapidAPI-Key": key,
+ "X-RapidAPI-Host": "jsearch.p.rapidapi.com",
+ },
+ },
+ );
+ if (!res.ok) {
+ return NextResponse.json({
+ success: false,
+ error: res.status === 403 ? "Invalid API key" : `RapidAPI returned ${res.status}`,
+ });
+ }
+ return NextResponse.json({ success: true });
+ }
+
+ case "ollama": {
+ const baseUrl = key.replace(/\/+$/, "");
+ const res = await fetch(`${baseUrl}/api/tags`);
+ if (!res.ok) {
+ return NextResponse.json({
+ success: false,
+ error: `Cannot connect to Ollama at ${baseUrl}`,
+ });
+ }
+ return NextResponse.json({ success: true });
+ }
+
+ default:
+ return NextResponse.json(
+ { success: false, error: "Unknown provider" },
+ { status: 400 },
+ );
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Verification failed";
+ return NextResponse.json({
+ success: false,
+ error: message.includes("fetch failed") || message.includes("ECONNREFUSED")
+ ? `Cannot connect to ${provider} service`
+ : message,
+ });
+ }
+}
diff --git a/src/app/dashboard/settings/page.tsx b/src/app/dashboard/settings/page.tsx
index 91c55dc..f3d2fa8 100644
--- a/src/app/dashboard/settings/page.tsx
+++ b/src/app/dashboard/settings/page.tsx
@@ -1,26 +1,30 @@
+"use client";
+
+import { useState } from "react";
import AiSettings from "@/components/settings/AiSettings";
+import ApiKeySettings from "@/components/settings/ApiKeySettings";
import DisplaySettings from "@/components/settings/DisplaySettings";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import React from "react";
+import SettingsSidebar, { type SettingsSection } from "@/components/settings/SettingsSidebar";
function Settings() {
+ const [activeSection, setActiveSection] = useState<SettingsSection>("ai-provider");
+
return (
<div className="flex flex-col col-span-3">
<h3 className="text-2xl font-semibold leading-none tracking-tight mb-4">
Settings
</h3>
- <Tabs defaultValue="ai">
- <TabsList>
- <TabsTrigger value="ai">AI</TabsTrigger>
- <TabsTrigger value="display">Display</TabsTrigger>
- </TabsList>
- <TabsContent value="display">
- <DisplaySettings />
- </TabsContent>
- <TabsContent value="ai">
- <AiSettings />
- </TabsContent>
- </Tabs>
+ <div className="flex gap-6">
+ <SettingsSidebar
+ activeSection={activeSection}
+ onSectionChange={setActiveSection}
+ />
+ <div className="flex-1 min-w-0">
+ {activeSection === "ai-provider" && <AiSettings />}
+ {activeSection === "api-keys" && <ApiKeySettings />}
+ {activeSection === "appearance" && <DisplaySettings />}
+ </div>
+ </div>
</div>
);
}
diff --git a/src/components/settings/AiSettings.tsx b/src/components/settings/AiSettings.tsx
index 0bb59d7..9843dd9 100644
--- a/src/components/settings/AiSettings.tsx
+++ b/src/components/settings/AiSettings.tsx
@@ -1,6 +1,5 @@
"use client";
import { useEffect, useState } from "react";
-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import {
AiModel,
AiProvider,
@@ -22,6 +21,7 @@ import { toast } from "../ui/use-toast";
import { XCircle, CheckCircle, Loader2 } from "lucide-react";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
import { getUserSettings, updateAiSettings } from "@/actions/userSettings.actions";
+import { getOllamaBaseUrl } from "@/actions/apiKey.actions";
interface OllamaModelResponse {
models: {
@@ -57,6 +57,7 @@ function AiSettings() {
const [fetchError, setFetchError] = useState<string>("");
const [runningModelError, setRunningModelError] = useState<string>("");
const [runningModelName, setRunningModelName] = useState<string>("");
+ const [ollamaBaseUrl, setOllamaBaseUrl] = useState("http://127.0.0.1:11434");
const setSelectedProvider = (provider: AiProvider) => {
setSelectedModel({ provider, model: undefined });
@@ -69,12 +70,10 @@ function AiSettings() {
setRunningModelName("");
setRunningModelError("");
- // Check if the selected model is running (only for Ollama)
if (selectedModel.provider === AiProvider.OLLAMA) {
const result = await checkIfModelIsRunning(model, selectedModel.provider);
if (result.isRunning && result.runningModelName) {
setRunningModelName(result.runningModelName);
- // Keep the model alive indefinitely
await keepModelAlive(result.runningModelName);
} else if (result.error) {
setRunningModelError(result.error);
@@ -86,9 +85,14 @@ function AiSettings() {
const fetchSettings = async () => {
setIsLoadingSettings(true);
try {
- const result = await getUserSettings();
- if (result.success && result.data?.settings?.ai) {
- const aiSettings = result.data.settings.ai;
+ const [settingsResult, resolvedUrl] = await Promise.all([
+ getUserSettings(),
+ getOllamaBaseUrl(),
+ ]);
+ setOllamaBaseUrl(resolvedUrl);
+
+ if (settingsResult.success && settingsResult.data?.settings?.ai) {
+ const aiSettings = settingsResult.data.settings.ai;
setSelectedModel({
provider: aiSettings.provider || defaultModel.provider,
model: aiSettings.model,
@@ -118,7 +122,7 @@ function AiSettings() {
setIsLoadingModels(true);
setFetchError("");
try {
- const response = await fetch("http://localhost:11434/api/tags");
+ const response = await fetch(`${ollamaBaseUrl}/api/tags`);
if (!response.ok) {
if (selectedModel.provider === AiProvider.OLLAMA) {
setFetchError(
@@ -131,7 +135,6 @@ function AiSettings() {
const modelNames = data.models.map((model) => model.name);
setOllamaModels(modelNames);
- // Fetch and auto-select running model
await fetchRunningModel();
} catch (error) {
console.error("Error fetching Ollama models:", error);
@@ -147,8 +150,7 @@ function AiSettings() {
const keepModelAlive = async (modelName: string) => {
try {
- // Send a request to keep the model loaded for 1 hour
- await fetch("http://localhost:11434/api/generate", {
+ await fetch(`${ollamaBaseUrl}/api/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -156,7 +158,7 @@ function AiSettings() {
body: JSON.stringify({
model: modelName,
prompt: "",
- keep_alive: "1h", // Keep loaded for 1 hour
+ keep_alive: "1h",
stream: false,
}),
});
@@ -169,7 +171,7 @@ function AiSettings() {
setRunningModelError("");
setRunningModelName("");
try {
- const response = await fetch("http://localhost:11434/api/ps");
+ const response = await fetch(`${ollamaBaseUrl}/api/ps`);
if (!response.ok) {
if (selectedModel.provider === AiProvider.OLLAMA) {
setRunningModelError(
@@ -180,13 +182,11 @@ function AiSettings() {
}
const data: OllamaRunningModelResponse = await response.json();
if (data.models && data.models.length > 0) {
- // Auto-select the first running model
const runningModelName = data.models[0].name;
setSelectedModel({
provider: AiProvider.OLLAMA,
model: runningModelName,
});
- // Verify the model is running using shared utility
const result = await checkIfModelIsRunning(
runningModelName,
AiProvider.OLLAMA,
@@ -220,7 +220,6 @@ function AiSettings() {
try {
const response = await fetch("/api/ai/deepseek/models");
if (!response.ok) {
- // Fall back to enum models if API fails
const fallbackModels = Object.values(DeepseekModel);
setDeepseekModels(fallbackModels);
return;
@@ -232,7 +231,6 @@ function AiSettings() {
);
} catch (error) {
console.error("Error fetching DeepSeek models:", error);
- // Fall back to enum models if API fails
setDeepseekModels(Object.values(DeepseekModel));
} finally {
setIsLoadingModels(false);
@@ -292,44 +290,79 @@ function AiSettings() {
};
if (isLoadingSettings) {
return (
- <Card>
- <CardHeader>
- <CardTitle>AI Settings</CardTitle>
- </CardHeader>
- <CardContent className="ml-4">
- <div className="flex items-center gap-2">
- <Loader2 className="h-4 w-4 animate-spin" />
- <span>Loading settings...</span>
- </div>
- </CardContent>
- </Card>
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-medium">AI Provider</h3>
+ <p className="text-sm text-muted-foreground">
+ Configure your AI service provider and model.
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>Loading settings...</span>
+ </div>
+ </div>
);
}
return (
- <Card>
- <CardHeader>
- <CardTitle>AI Settings</CardTitle>
- </CardHeader>
- <CardContent className="ml-4">
- <div>
- <Label className="my-4" htmlFor="ai-provider">
- AI Service Provider
- </Label>
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-medium">AI Provider</h3>
+ <p className="text-sm text-muted-foreground">
+ Configure your AI service provider and model.
+ </p>
+ </div>
+ <div>
+ <Label className="my-4" htmlFor="ai-provider">
+ AI Service Provider
+ </Label>
+ <Select
+ value={selectedModel.provider}
+ onValueChange={setSelectedProvider}
+ >
+ <SelectTrigger
+ id="ai-provider"
+ aria-label="Select AI provider"
+ className="w-[180px]"
+ >
+ <SelectValue placeholder="Select AI Service Provider" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {Object.entries(AiProvider).map(([key, value]) => (
+ <SelectItem key={key} value={value} className="capitalize">
+ {value}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </div>
+ <div>
+ <Label className="my-4" htmlFor="ai-model">
+ Model
+ </Label>
+ <div className="flex items-start gap-2">
<Select
- value={selectedModel.provider}
- onValueChange={setSelectedProvider}
+ value={selectedModel.model}
+ onValueChange={setSelectedProviderModel}
+ disabled={isLoadingModels}
>
<SelectTrigger
- id="ai-provider"
- aria-label="Select AI provider"
+ id="ai-model"
+ aria-label="Select Model"
className="w-[180px]"
>
- <SelectValue placeholder="Select AI Service Provider" />
+ <SelectValue
+ placeholder={
+ isLoadingModels ? "Loading models..." : "Select AI Model"
+ }
+ />
</SelectTrigger>
<SelectContent>
<SelectGroup>
- {Object.entries(AiProvider).map(([key, value]) => (
+ {getModelsList(selectedModel.provider).map(([key, value]) => (
<SelectItem key={key} value={value} className="capitalize">
{value}
</SelectItem>
@@ -337,74 +370,41 @@ function AiSettings() {
</SelectGroup>
</SelectContent>
</Select>
- </div>
- <div>
- <Label className="my-4" htmlFor="ai-model">
- Model
- </Label>
- <div className="flex items-start gap-2">
- <Select
- value={selectedModel.model}
- onValueChange={setSelectedProviderModel}
- disabled={isLoadingModels}
- >
- <SelectTrigger
- id="ai-model"
- aria-label="Select Model"
- className="w-[180px]"
- >
- <SelectValue
- placeholder={
- isLoadingModels ? "Loading models..." : "Select AI Model"
- }
- />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {getModelsList(selectedModel.provider).map(([key, value]) => (
- <SelectItem key={key} value={value} className="capitalize">
- {value}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- {fetchError && (
- <div className="flex items-center gap-1 text-red-600 text-sm mt-2">
- <XCircle className="h-4 w-4 flex-shrink-0" />
- <span>{fetchError}</span>
- </div>
- )}
- </div>
- {runningModelName && (
- <div className="flex items-center gap-1 text-green-600 text-sm mt-2">
- <CheckCircle className="h-4 w-4 flex-shrink-0" />
- <span>{runningModelName} is running</span>
- </div>
- )}
- {runningModelError && (
+ {fetchError && (
<div className="flex items-center gap-1 text-red-600 text-sm mt-2">
<XCircle className="h-4 w-4 flex-shrink-0" />
- <span>{runningModelError}</span>
+ <span>{fetchError}</span>
</div>
)}
</div>
- <Button
- className="mt-8"
- onClick={saveModelSettings}
- disabled={
- !selectedModel.model ||
- (selectedModel.provider === AiProvider.OLLAMA &&
- !runningModelName) ||
- isLoadingModels ||
- isSaving
- }
- >
- {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
- Save
- </Button>
- </CardContent>
- </Card>
+ {runningModelName && (
+ <div className="flex items-center gap-1 text-green-600 text-sm mt-2">
+ <CheckCircle className="h-4 w-4 flex-shrink-0" />
+ <span>{runningModelName} is running</span>
+ </div>
+ )}
+ {runningModelError && (
+ <div className="flex items-center gap-1 text-red-600 text-sm mt-2">
+ <XCircle className="h-4 w-4 flex-shrink-0" />
+ <span>{runningModelError}</span>
+ </div>
+ )}
+ </div>
+ <Button
+ className="mt-4"
+ onClick={saveModelSettings}
+ disabled={
+ !selectedModel.model ||
+ (selectedModel.provider === AiProvider.OLLAMA &&
+ !runningModelName) ||
+ isLoadingModels ||
+ isSaving
+ }
+ >
+ {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ Save
+ </Button>
+ </div>
);
}
diff --git a/src/components/settings/ApiKeySettings.tsx b/src/components/settings/ApiKeySettings.tsx
new file mode 100644
index 0000000..3dcdce0
--- /dev/null
+++ b/src/components/settings/ApiKeySettings.tsx
@@ -0,0 +1,311 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Badge } from "../ui/badge";
+import { Label } from "../ui/label";
+import { toast } from "../ui/use-toast";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "../ui/alert-dialog";
+import { Loader2, Plus, Trash2, CheckCircle } from "lucide-react";
+import { getUserApiKeys, saveApiKey, deleteApiKey } from "@/actions/apiKey.actions";
+import type { ApiKeyClientResponse, ApiKeyProvider } from "@/models/apiKey.model";
+
+interface ProviderConfig {
+ id: ApiKeyProvider;
+ name: string;
+ placeholder: string;
+ inputType: "password" | "text";
+ description: string;
+}
+
+const PROVIDERS: ProviderConfig[] = [
+ {
+ id: "openai",
+ name: "OpenAI",
+ placeholder: "sk-...",
+ inputType: "password",
+ description: "Used for GPT models in resume review and job matching",
+ },
+ {
+ id: "deepseek",
+ name: "DeepSeek",
+ placeholder: "sk-...",
+ inputType: "password",
+ description: "Used for DeepSeek models in resume review and job matching",
+ },
+ {
+ id: "rapidapi",
+ name: "RapidAPI",
+ placeholder: "Your RapidAPI key",
+ inputType: "password",
+ description: "Used for JSearch job discovery automations",
+ },
+ {
+ id: "ollama",
+ name: "Ollama",
+ placeholder: "http://127.0.0.1:11434",
+ inputType: "text",
+ description: "Base URL for your Ollama instance",
+ },
+];
+
+function ApiKeySettings() {
+ const [keys, setKeys] = useState<ApiKeyClientResponse[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [editingProvider, setEditingProvider] = useState<ApiKeyProvider | null>(null);
+ const [inputValue, setInputValue] = useState("");
+ const [verifying, setVerifying] = useState(false);
+ const [deleting, setDeleting] = useState<string | null>(null);
+
+ useEffect(() => {
+ fetchKeys();
+ }, []);
+
+ const fetchKeys = async () => {
+ setIsLoading(true);
+ try {
+ const result = await getUserApiKeys();
+ if (result.success && result.data) {
+ setKeys(result.data);
+ }
+ } catch (error) {
+ console.error("Error fetching API keys:", error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const getKeyForProvider = (provider: ApiKeyProvider) =>
+ keys.find((k) => k.provider === provider);
+
+ const handleVerifyAndSave = async (provider: ApiKeyProvider) => {
+ if (!inputValue.trim()) return;
+
+ setVerifying(true);
+ try {
+ const verifyRes = await fetch("/api/settings/api-keys/verify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider, key: inputValue }),
+ });
+ const verifyData = await verifyRes.json();
+
+ if (!verifyData.success) {
+ toast({
+ variant: "destructive",
+ title: "Verification failed",
+ description: verifyData.error || "Could not verify the key",
+ });
+ return;
+ }
+
+ const saveResult = await saveApiKey({ provider, key: inputValue });
+ if (saveResult.success) {
+ toast({
+ variant: "success",
+ title: "API key saved",
+ description: `${PROVIDERS.find((p) => p.id === provider)?.name} key verified and saved.`,
+ });
+ setEditingProvider(null);
+ setInputValue("");
+ await fetchKeys();
+ } else {
+ toast({
+ variant: "destructive",
+ title: "Save failed",
+ description: saveResult.message || "Failed to save API key",
+ });
+ }
+ } catch (error) {
+ console.error("Error saving API key:", error);
+ toast({
+ variant: "destructive",
+ title: "Error",
+ description: "An unexpected error occurred",
+ });
+ } finally {
+ setVerifying(false);
+ }
+ };
+
+ const handleDelete = async (provider: ApiKeyProvider) => {
+ setDeleting(provider);
+ try {
+ const result = await deleteApiKey(provider);
+ if (result.success) {
+ toast({
+ variant: "success",
+ title: "API key deleted",
+ description: `${PROVIDERS.find((p) => p.id === provider)?.name} key removed.`,
+ });
+ await fetchKeys();
+ } else {
+ toast({
+ variant: "destructive",
+ title: "Error",
+ description: result.message || "Failed to delete API key",
+ });
+ }
+ } catch (error) {
+ console.error("Error deleting API key:", error);
+ } finally {
+ setDeleting(null);
+ }
+ };
+
+ const handleCancel = () => {
+ setEditingProvider(null);
+ setInputValue("");
+ };
+
+ if (isLoading) {
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-medium">API Keys</h3>
+ <p className="text-sm text-muted-foreground">
+ Manage your API keys for AI providers and external services.
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>Loading keys...</span>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-medium">API Keys</h3>
+ <p className="text-sm text-muted-foreground">
+ Manage your API keys for AI providers and external services. Keys are encrypted and stored securely.
+ </p>
+ </div>
+
+ <div className="grid gap-4">
+ {PROVIDERS.map((provider) => {
+ const existingKey = getKeyForProvider(provider.id);
+ const isEditing = editingProvider === provider.id;
+
+ return (
+ <Card key={provider.id}>
+ <CardHeader className="pb-3">
+ <div className="flex items-center justify-between">
+ <div>
+ <CardTitle className="text-base">{provider.name}</CardTitle>
+ <CardDescription className="text-sm">
+ {provider.description}
+ </CardDescription>
+ </div>
+ {existingKey ? (
+ <Badge className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200 hover:bg-green-100 dark:hover:bg-green-900">
+ <CheckCircle className="h-3 w-3 mr-1" />
+ ····{existingKey.last4}
+ </Badge>
+ ) : (
+ <Badge variant="secondary">Not configured</Badge>
+ )}
+ </div>
+ </CardHeader>
+ <CardContent>
+ {isEditing ? (
+ <div className="space-y-3">
+ <div>
+ <Label htmlFor={`key-${provider.id}`}>
+ {provider.id === "ollama" ? "Base URL" : "API Key"}
+ </Label>
+ <Input
+ id={`key-${provider.id}`}
+ type={provider.inputType}
+ placeholder={provider.placeholder}
+ value={inputValue}
+ onChange={(e) => setInputValue(e.target.value)}
+ className="mt-1"
+ />
+ </div>
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ onClick={() => handleVerifyAndSave(provider.id)}
+ disabled={!inputValue.trim() || verifying}
+ >
+ {verifying && <Loader2 className="mr-2 h-3 w-3 animate-spin" />}
+ Verify & Save
+ </Button>
+ <Button size="sm" variant="outline" onClick={handleCancel}>
+ Cancel
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ setEditingProvider(provider.id);
+ setInputValue("");
+ }}
+ >
+ <Plus className="h-3 w-3 mr-1" />
+ {existingKey ? "Update Key" : "Add Key"}
+ </Button>
+ {existingKey && (
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button
+ size="sm"
+ variant="outline"
+ className="text-destructive hover:text-destructive"
+ disabled={deleting === provider.id}
+ >
+ {deleting === provider.id ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Trash2 className="h-3 w-3" />
+ )}
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete API Key</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to delete your {provider.name} key?
+ The system will fall back to the server environment variable if available.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={() => handleDelete(provider.id)}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+export default ApiKeySettings;
diff --git a/src/components/settings/DisplaySettings.tsx b/src/components/settings/DisplaySettings.tsx
index 3298919..cfc8029 100644
--- a/src/components/settings/DisplaySettings.tsx
+++ b/src/components/settings/DisplaySettings.tsx
@@ -1,7 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import { z } from "zod";
-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import {
Form,
FormControl,
@@ -96,27 +95,30 @@ function DisplaySettings() {
if (isLoading) {
return (
- <Card>
- <CardHeader>
- <CardTitle>Appearance</CardTitle>
- </CardHeader>
- <CardContent className="ml-4">
- <div className="flex items-center gap-2">
- <Loader2 className="h-4 w-4 animate-spin" />
- <span>Loading settings...</span>
- </div>
- </CardContent>
- </Card>
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-medium">Appearance</h3>
+ <p className="text-sm text-muted-foreground">
+ Customize the look and feel of the application.
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>Loading settings...</span>
+ </div>
+ </div>
);
}
return (
- <Card>
- <CardHeader>
- <CardTitle>Appearance</CardTitle>
- </CardHeader>
- <CardContent className="ml-4">
- <div className="mt-4">
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-medium">Appearance</h3>
+ <p className="text-sm text-muted-foreground">
+ Customize the look and feel of the application.
+ </p>
+ </div>
+ <div>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
@@ -185,9 +187,8 @@ function DisplaySettings() {
</Button>
</form>
</Form>
- </div>
- </CardContent>
- </Card>
+ </div>
+ </div>
);
}
diff --git a/src/components/settings/SettingsSidebar.tsx b/src/components/settings/SettingsSidebar.tsx
new file mode 100644
index 0000000..47dd5f5
--- /dev/null
+++ b/src/components/settings/SettingsSidebar.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { Bot, Key, Palette } from "lucide-react";
+import { Button } from "../ui/button";
+import { cn } from "@/lib/utils";
+
+export type SettingsSection = "ai-provider" | "api-keys" | "appearance";
+
+const SETTINGS_SECTIONS: {
+ id: SettingsSection;
+ label: string;
+ icon: typeof Bot;
+}[] = [
+ { id: "ai-provider", label: "AI Provider", icon: Bot },
+ { id: "api-keys", label: "API Keys", icon: Key },
+ { id: "appearance", label: "Appearance", icon: Palette },
+];
+
+interface SettingsSidebarProps {
+ activeSection: SettingsSection;
+ onSectionChange: (section: SettingsSection) => void;
+}
+
+export default function SettingsSidebar({
+ activeSection,
+ onSectionChange,
+}: SettingsSidebarProps) {
+ return (
+ <nav className="flex flex-col gap-1 w-48 shrink-0">
+ {SETTINGS_SECTIONS.map((section) => {
+ const Icon = section.icon;
+ const isActive = activeSection === section.id;
+ return (
+ <Button
+ key={section.id}
+ variant="ghost"
+ className={cn(
+ "justify-start gap-2 rounded-none border-l-2",
+ isActive
+ ? "border-l-primary bg-muted font-medium"
+ : "border-l-transparent hover:border-l-muted-foreground/25",
+ )}
+ onClick={() => onSectionChange(section.id)}
+ >
+ <Icon className="h-4 w-4" />
+ {section.label}
+ </Button>
+ );
+ })}
+ </nav>
+ );
+}
diff --git a/src/lib/ai/providers.ts b/src/lib/ai/providers.ts
index 046d86a..24d34f5 100644
--- a/src/lib/ai/providers.ts
+++ b/src/lib/ai/providers.ts
@@ -1,31 +1,32 @@
import { createOpenAI } from "@ai-sdk/openai";
import { createOllama } from "ollama-ai-provider-v2";
import { createDeepSeek } from "@ai-sdk/deepseek";
+import { resolveApiKey } from "@/lib/api-key-resolver";
export type ProviderType = "openai" | "ollama" | "deepseek";
-/**
- * Get a language model instance for the specified provider and model.
- */
-export function getModel(provider: ProviderType, modelName: string) {
+export async function getModel(
+ provider: ProviderType,
+ modelName: string,
+ userId?: string,
+) {
if (provider === "openai") {
- const openai = createOpenAI({
- apiKey: process.env.OPENAI_API_KEY,
- });
+ const apiKey = await resolveApiKey(userId, "openai");
+ if (!apiKey) throw new Error("OpenAI API key not configured");
+ const openai = createOpenAI({ apiKey });
return openai(modelName);
}
if (provider === "deepseek") {
- const deepseek = createDeepSeek({
- apiKey: process.env.DEEPSEEK_API_KEY,
- });
+ const apiKey = await resolveApiKey(userId, "deepseek");
+ if (!apiKey) throw new Error("DeepSeek API key not configured");
+ const deepseek = createDeepSeek({ apiKey });
return deepseek(modelName);
}
- // Use ollama-ai-provider-v2 for Ollama
+ const baseURL = await resolveApiKey(userId, "ollama");
const ollama = createOllama({
- baseURL: (process.env.OLLAMA_BASE_URL || "http://127.0.0.1:11434") + "/api",
+ baseURL: (baseURL || "http://127.0.0.1:11434") + "/api",
});
-
return ollama(modelName);
}
diff --git a/src/lib/api-key-resolver.ts b/src/lib/api-key-resolver.ts
new file mode 100644
index 0000000..cb2f8aa
--- /dev/null
+++ b/src/lib/api-key-resolver.ts
@@ -0,0 +1,50 @@
+import "server-only";
+
+import db from "@/lib/db";
+import { decrypt } from "@/lib/encryption";
+
+const ENV_VAR_MAP: Record<string, string> = {
+ openai: "OPENAI_API_KEY",
+ deepseek: "DEEPSEEK_API_KEY",
+ rapidapi: "RAPIDAPI_KEY",
+ ollama: "OLLAMA_BASE_URL",
+};
+
+const OLLAMA_DEFAULT = "http://127.0.0.1:11434";
+
+export async function resolveApiKey(
+ userId: string | undefined,
+ provider: string,
+): Promise<string | undefined> {
+ // Try user DB key first
+ if (userId) {
+ try {
+ const apiKey = await db.apiKey.findUnique({
+ where: { userId_provider: { userId, provider } },
+ });
+ if (apiKey) {
+ // Update lastUsedAt in background
+ db.apiKey.update({
+ where: { id: apiKey.id },
+ data: { lastUsedAt: new Date() },
+ }).catch(() => {});
+
+ return decrypt(apiKey.encryptedKey, apiKey.iv);
+ }
+ } catch {
+ // Fall through to env var
+ }
+ }
+
+ // Env var fallback
+ const envVar = ENV_VAR_MAP[provider];
+ if (envVar) {
+ const value = process.env[envVar];
+ if (value) return value;
+ }
+
+ // Ollama default
+ if (provider === "ollama") return OLLAMA_DEFAULT;
+
+ return undefined;
+}
diff --git a/src/lib/encryption.ts b/src/lib/encryption.ts
new file mode 100644
index 0000000..bcc7cb1
--- /dev/null
+++ b/src/lib/encryption.ts
@@ -0,0 +1,61 @@
+import "server-only";
+
+import { createCipheriv, createDecipheriv, randomBytes, pbkdf2Sync } from "crypto";
+
+const ALGORITHM = "aes-256-gcm";
+const IV_LENGTH = 12;
+const AUTH_TAG_LENGTH = 16;
+const KEY_LENGTH = 32;
+const PBKDF2_ITERATIONS = 100_000;
+const SALT = "jobsync-api-key-encryption";
+
+function getDerivedKey(): Buffer {
+ const secret = process.env.AUTH_SECRET;
+ if (!secret) {
+ throw new Error("AUTH_SECRET is not set");
+ }
+ return pbkdf2Sync(secret, SALT, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
+}
+
+export function encrypt(plaintext: string): { encrypted: string; iv: string } {
+ const key = getDerivedKey();
+ const iv = randomBytes(IV_LENGTH);
+ const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
+
+ let encrypted = cipher.update(plaintext, "utf8", "base64");
+ encrypted += cipher.final("base64");
+
+ const authTag = cipher.getAuthTag();
+ // Append auth tag to encrypted data
+ const combined = Buffer.concat([
+ Buffer.from(encrypted, "base64"),
+ authTag,
+ ]).toString("base64");
+
+ return {
+ encrypted: combined,
+ iv: iv.toString("base64"),
+ };
+}
+
+export function decrypt(encryptedData: string, iv: string): string {
+ const key = getDerivedKey();
+ const ivBuffer = Buffer.from(iv, "base64");
+ const combined = Buffer.from(encryptedData, "base64");
+
+ // Extract auth tag from end of combined data
+ const authTag = combined.subarray(combined.length - AUTH_TAG_LENGTH);
+ const encrypted = combined.subarray(0, combined.length - AUTH_TAG_LENGTH);
+
+ const decipher = createDecipheriv(ALGORITHM, key, ivBuffer, { authTagLength: AUTH_TAG_LENGTH });
+ decipher.setAuthTag(authTag);
+
+ let decrypted = decipher.update(encrypted);
+ decrypted = Buffer.concat([decrypted, decipher.final()]);
+
+ return decrypted.toString("utf8");
+}
+
+export function getLast4(key: string): string {
+ return key.slice(-4);
+}
diff --git a/src/lib/scraper/jsearch/index.ts b/src/lib/scraper/jsearch/index.ts
index e26a1d7..797e6e7 100644
--- a/src/lib/scraper/jsearch/index.ts
+++ b/src/lib/scraper/jsearch/index.ts
@@ -34,8 +34,9 @@ interface JSearchResponse {
data: JSearchJob[];
}
-export function createJSearchProvider(): ScraperService {
- if (!RAPIDAPI_KEY) {
+export function createJSearchProvider(rapidApiKey?: string): ScraperService {
+ const apiKey = rapidApiKey || RAPIDAPI_KEY;
+ if (!apiKey) {
throw new Error("RAPIDAPI_KEY environment variable is not set");
}
@@ -57,7 +58,7 @@ export function createJSearchProvider(): ScraperService {
const response = await fetch(url.toString(), {
method: "GET",
headers: {
- "X-RapidAPI-Key": RAPIDAPI_KEY,
+ "X-RapidAPI-Key": apiKey,
"X-RapidAPI-Host": "jsearch.p.rapidapi.com",
},
});
@@ -129,8 +130,10 @@ export function createJSearchProvider(): ScraperService {
export async function searchJSearchJobs(
keywords: string,
location: string,
+ rapidApiKey?: string,
): Promise<ScraperResult<JobDetails[]>> {
- if (!RAPIDAPI_KEY) {
+ const apiKey = rapidApiKey || RAPIDAPI_KEY;
+ if (!apiKey) {
return {
success: false,
error: { type: "network", message: "RAPIDAPI_KEY is not configured" },
@@ -147,7 +150,7 @@ export async function searchJSearchJobs(
const response = await fetch(url.toString(), {
method: "GET",
headers: {
- "X-RapidAPI-Key": RAPIDAPI_KEY,
+ "X-RapidAPI-Key": apiKey,
"X-RapidAPI-Host": "jsearch.p.rapidapi.com",
},
});
diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.ts
index 354a8b2..d28fdb6 100644
--- a/src/lib/scraper/runner.ts
+++ b/src/lib/scraper/runner.ts
@@ -29,6 +29,7 @@ import {
defaultUserSettings,
type AiSettings,
} from "@/models/userSettings.model";
+import { resolveApiKey } from "@/lib/api-key-resolver";
const MAX_JOBS_PER_RUN = 10;
@@ -193,10 +194,12 @@ export async function runAutomation(
`Searching for jobs: "${automation.keywords}" in ${automation.location}`,
);
- // Use JSearch API
+ // Use JSearch API with user's key if available
+ const rapidApiKey = await resolveApiKey(automation.userId, "rapidapi");
const searchResult = await searchJSearchJobs(
automation.keywords,
automation.location,
+ rapidApiKey,
);
if (!searchResult.success) {
@@ -311,6 +314,7 @@ export async function runAutomation(
resume as ResumeWithSections,
automation.jobBoard as JobBoard,
aiSettings,
+ automation.userId,
);
if (!matchResult.success) {
@@ -482,6 +486,7 @@ async function matchJobToResume(
resume: ResumeWithSections,
sourceBoard: JobBoard,
aiSettings: AiSettings,
+ userId: string,
): Promise<MatchResult> {
try {
const resumeText = await convertResumeForMatch(resume);
@@ -497,7 +502,7 @@ ${job.description}
const provider = aiSettings.provider;
const modelName = aiSettings.model || getDefaultModelForProvider(provider);
- const model = getModel(provider, modelName);
+ const model = await getModel(provider, modelName, userId);
const result = await generateText({
model,
diff --git a/src/models/apiKey.model.ts b/src/models/apiKey.model.ts
new file mode 100644
index 0000000..fd701a3
--- /dev/null
+++ b/src/models/apiKey.model.ts
@@ -0,0 +1,21 @@
+export type ApiKeyProvider = "openai" | "deepseek" | "ollama" | "rapidapi";
+
+export interface ApiKeyRecord {
+ id: string;
+ userId: string;
+ provider: ApiKeyProvider;
+ last4: string;
+ label: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ lastUsedAt: Date | null;
+}
+
+export interface ApiKeyClientResponse {
+ id: string;
+ provider: ApiKeyProvider;
+ last4: string;
+ label: string | null;
+ createdAt: Date;
+ lastUsedAt: Date | null;
+}
diff --git a/src/models/apiKey.schema.ts b/src/models/apiKey.schema.ts
new file mode 100644
index 0000000..814b6f3
--- /dev/null
+++ b/src/models/apiKey.schema.ts
@@ -0,0 +1,9 @@
+import { z } from "zod";
+
+export const apiKeySaveSchema = z.object({
+ provider: z.enum(["openai", "deepseek", "ollama", "rapidapi"]),
+ key: z.string().min(1, "API key is required"),
+ label: z.string().optional(),
+});
+
+export type ApiKeySaveInput = z.infer<typeof apiKeySaveSchema>;