feat(api-keys): add api keys management and authentication for n8n workflows
Deploy Canina / deploy (push) Successful in 3m11s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 9s

This commit is contained in:
parsa aghaei committed 2026-09-08 12:57:32 +03:30
1 parent ba9472c938
commit 1fff11ee4f
24 files changed
+158204 -5768

No files matched your search

@@ -36,6 +36,7 @@ import {
Menu,
RotateCcw,
Activity,
Key,
} from 'lucide-react';
import api from '../services/api';
@@ -188,6 +189,7 @@ export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
{ icon: DollarSign, label: 'تنظیمات مالی و مالیات', path: '/settings/financial' },
{ icon: MessageSquare, label: 'درگاه پیامک (MeliPayamak)', path: '/settings/sms' },
{ icon: ShieldCheck, label: 'گواهی SSL و امنیت', path: '/settings/ssl' },
{ icon: Key, label: 'کلیدهای دسترسی (API Keys)', path: '/settings/api-keys' },
{ icon: Globe, label: 'تنظیمات سئو (SEO)', path: '/settings/seo' },
{ icon: Sliders, label: 'تنظیمات سیستمی پیشرفته', path: '/settings/system' },
],
@@ -0,0 +1,541 @@
import { useState, useEffect } from 'react';
import {
Key,
Plus,
Trash2,
Copy,
Check,
Shield,
Clock,
AlertTriangle,
RefreshCw,
Power,
ExternalLink,
Lock,
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import api from '../services/api';
import Spinner from '../components/ui/Spinner';
import Button from '../components/ui/Button';
import type { ApiKeyItem, CreateApiKeyPayload } from '../types/admin';
export default function ApiKeysPage() {
const [keys, setKeys] = useState<ApiKeyItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isCreating, setIsCreating] = useState(false);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
// Success modal showing the created key
const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
// Form states
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [expiryOption, setExpiryOption] = useState<'never' | '30d' | '90d' | '1y'>('never');
const [selectedScopes, setSelectedScopes] = useState<string[]>(['*']);
const scopeOptions = [
{ id: '*', label: 'دسترسی کامل (Full Access)', desc: 'دسترسی نامحدود به تمام بخش‌های API' },
{ id: 'orders:read', label: 'مشاهده سفارشات', desc: 'خواندن لیست و جزئیات سفارش‌ها' },
{ id: 'orders:write', label: 'تغییر وضعیت سفارشات', desc: 'به‌روزرسانی و ثبت وضعیت سفارش‌ها' },
{ id: 'products:read', label: 'مشاهده محصولات', desc: 'دریافت مشخصات، کاتالوگ و موجودی کالاها' },
{ id: 'products:write', label: 'ویرایش محصولات', desc: 'تغییر قیمت، موجودی یا افزودن محصول' },
{ id: 'users:read', label: 'مشاهده کاربران', desc: 'دریافت اطلاعات و آمار کاربران' },
];
const fetchKeys = async () => {
try {
setIsLoading(true);
const res = await api.get('/admin/api-keys');
if (res.data?.success) {
setKeys(res.data.data || []);
}
} catch (err) {
console.error('Failed to fetch api keys', err);
toast.error('خطا در بارگذاری کلیدهای دسترسی');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchKeys();
}, []);
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
toast.error('لطفاً عنوان کلید را وارد کنید');
return;
}
try {
setIsCreating(true);
let expiresAt: string | undefined = undefined;
const now = new Date();
if (expiryOption === '30d') {
expiresAt = new Date(now.setDate(now.getDate() + 30)).toISOString();
} else if (expiryOption === '90d') {
expiresAt = new Date(now.setDate(now.getDate() + 90)).toISOString();
} else if (expiryOption === '1y') {
expiresAt = new Date(now.setFullYear(now.getFullYear() + 1)).toISOString();
}
const payload: CreateApiKeyPayload = {
name: name.trim(),
description: description.trim() || undefined,
scopes: selectedScopes.includes('*') ? ['*'] : selectedScopes,
expiresAt,
};
const res = await api.post('/admin/api-keys', payload);
if (res.data?.success) {
toast.success('کلید دسترسی با موفقیت ایجاد شد');
setNewlyCreatedKey(res.data.data.rawKey);
setIsCreateModalOpen(false);
setName('');
setDescription('');
setExpiryOption('never');
setSelectedScopes(['*']);
fetchKeys();
}
} catch (err) {
console.error('Failed to create api key', err);
} finally {
setIsCreating(false);
}
};
const handleToggleStatus = async (id: string) => {
try {
const res = await api.patch(`/admin/api-keys/${id}/toggle`);
if (res.data?.success) {
toast.success(res.data.message || 'وضعیت کلید تغییر کرد');
fetchKeys();
}
} catch (err) {
console.error('Failed to toggle status', err);
}
};
const handleDelete = async (id: string, keyName: string) => {
if (!window.confirm(`آیا از حذف کلید دسترسی "${keyName}" اطمینان دارید؟ تمام وب‌هوک‌ها یا سیستم‌های متصل به آن قطع خواهند شد.`)) {
return;
}
try {
const res = await api.delete(`/admin/api-keys/${id}`);
if (res.data?.success) {
toast.success('کلید دسترسی با موفقیت حذف شد');
setKeys((prev) => prev.filter((k) => k.id !== id));
}
} catch (err) {
console.error('Failed to delete key', err);
}
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
setCopied(true);
toast.success('کلید در کلیپ‌بورد کپی شد');
setTimeout(() => setCopied(false), 3000);
};
const toggleScope = (scopeId: string) => {
if (scopeId === '*') {
setSelectedScopes(['*']);
return;
}
setSelectedScopes((prev) => {
const withoutAll = prev.filter((s) => s !== '*');
if (withoutAll.includes(scopeId)) {
const next = withoutAll.filter((s) => s !== scopeId);
return next.length === 0 ? ['*'] : next;
} else {
return [...withoutAll, scopeId];
}
});
};
return (
<div className="space-y-6 font-vazir text-right" dir="rtl">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-2">
<div className="p-2 bg-purple-50 text-purple-600 rounded-xl">
<Key className="w-6 h-6" />
</div>
<h1 className="text-xl font-black text-gray-900">کلیدهای دسترسی API (API Keys)</h1>
</div>
<p className="text-sm text-gray-500 mt-1">
ایجاد و مدیریت توکن‌های دائمی برای اتصال سرویس‌های اتوماسیون (نظیر n8n، Zapier یا اسکریپت‌ها)
</p>
</div>
<div className="flex items-center gap-3">
<Button
variant="outline"
onClick={fetchKeys}
disabled={isLoading}
className="flex items-center gap-1.5"
>
<RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
<span>بروزرسانی</span>
</Button>
<Button
variant="primary"
onClick={() => setIsCreateModalOpen(true)}
className="flex items-center gap-1.5 bg-purple-600 hover:bg-purple-700 text-white font-bold"
>
<Plus className="w-4 h-4" />
<span>ساخت API Key جدید</span>
</Button>
</div>
</div>
{/* Usage Guide in n8n */}
<div className="bg-gradient-to-r from-purple-50/70 to-indigo-50/70 border border-purple-100/80 rounded-2xl p-5 text-gray-700">
<div className="flex items-start gap-3">
<div className="p-2 bg-purple-600 text-white rounded-lg mt-0.5 shrink-0">
<ExternalLink className="w-4 h-4" />
</div>
<div className="space-y-1 text-xs sm:text-sm">
<h4 className="font-bold text-purple-950 text-sm">راهنمای استفاده در n8n یا ابزارهای مشابه</h4>
<p className="text-gray-600 leading-relaxed">
در نودهای <strong className="text-gray-900">HTTP Request</strong> ورک‌فلوهای n8n، در بخش <strong>Authentication</strong> گزینه <strong>Header Auth</strong> را انتخاب کنید. سپس نام هدر را برابر <code className="bg-purple-100 text-purple-800 px-1.5 py-0.5 rounded font-mono font-bold">x-api-key</code> و مقدار آن را برابر کلید تولید شده قرار دهید. کلیدها تا زمان انقضا یا باطل شدن به صورت دائمی معتبر خواهند بود.
</p>
</div>
</div>
</div>
{/* Keys Table */}
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
{isLoading ? (
<div className="p-16 flex flex-col items-center justify-center gap-3">
<Spinner className="w-8 h-8 text-purple-600" />
<span className="text-sm font-bold text-gray-500">در حال بارگذاری لیست کلیدها...</span>
</div>
) : keys.length === 0 ? (
<div className="p-16 text-center">
<div className="w-16 h-16 bg-purple-50 text-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4">
<Key className="w-8 h-8" />
</div>
<h3 className="text-base font-bold text-gray-900 mb-1">هیچ کلید دسترسی تعریف نشده است</h3>
<p className="text-sm text-gray-500 max-w-md mx-auto mb-6">
جهت برقراری ارتباط ایمن با ورک‌فلوهای n8n، می‌توانید همین حالا اولین API Key خود را ایجاد کنید.
</p>
<Button
variant="primary"
onClick={() => setIsCreateModalOpen(true)}
className="bg-purple-600 hover:bg-purple-700 text-white font-bold"
>
<Plus className="w-4 h-4 ml-1" />
ساخت اولین کلید
</Button>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-right border-collapse text-sm">
<thead>
<tr className="bg-gray-50/80 border-b border-gray-100 text-gray-500 font-bold">
<th className="py-4 px-6">عنوان کلید</th>
<th className="py-4 px-6">پیش‌نمایش کلید</th>
<th className="py-4 px-6">دسترسی‌ها (Scopes)</th>
<th className="py-4 px-6">تاریخ انقضا</th>
<th className="py-4 px-6">آخرین استفاده</th>
<th className="py-4 px-6 text-center">وضعیت</th>
<th className="py-4 px-6 text-center">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{keys.map((k) => (
<tr key={k.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6">
<div className="font-bold text-gray-900">{k.name}</div>
{k.description && (
<div className="text-xs text-gray-400 mt-0.5">{k.description}</div>
)}
</td>
<td className="py-4 px-6">
<div className="inline-flex items-center gap-1.5 font-mono text-xs bg-gray-100 px-2.5 py-1 rounded-md text-gray-700 font-semibold">
<span>{k.keyPrefix}</span>
<span className="text-gray-400">••••••••••••••••</span>
</div>
</td>
<td className="py-4 px-6">
<div className="flex flex-wrap gap-1 max-w-xs">
{k.scopes.map((s, idx) => (
<span
key={idx}
className={`text-xs px-2 py-0.5 rounded-full font-medium ${
s === '*'
? 'bg-purple-100 text-purple-800'
: 'bg-gray-100 text-gray-700'
}`}
>
{s === '*' ? 'دسترسی کامل' : s}
</span>
))}
</div>
</td>
<td className="py-4 px-6 text-gray-600 text-xs">
{k.expiresAt ? (
<div className="flex items-center gap-1">
<Clock className="w-3.5 h-3.5 text-gray-400" />
<span className={k.isExpired ? 'text-red-600 font-bold' : ''}>
{new Date(k.expiresAt).toLocaleDateString('fa-IR')}
{k.isExpired && ' (منقضی شده)'}
</span>
</div>
) : (
<span className="text-emerald-600 font-semibold">نامحدود (دائمی)</span>
)}
</td>
<td className="py-4 px-6 text-gray-500 text-xs">
{k.lastUsedAt ? (
new Date(k.lastUsedAt).toLocaleString('fa-IR', {
dateStyle: 'short',
timeStyle: 'short',
})
) : (
<span className="text-gray-400">تاکنون استفاده نشده</span>
)}
</td>
<td className="py-4 px-6 text-center">
<span
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-bold ${
k.status === 'ACTIVE' && !k.isExpired
? 'bg-emerald-50 text-emerald-700 border border-emerald-200/60'
: 'bg-red-50 text-red-700 border border-red-200/60'
}`}
>
{k.status === 'ACTIVE' && !k.isExpired ? 'فعال' : 'غیرفعال / باطل'}
</span>
</td>
<td className="py-4 px-6 text-center">
<div className="flex items-center justify-center gap-2">
<button
onClick={() => handleToggleStatus(k.id)}
title={k.status === 'ACTIVE' ? 'غیرفعال کردن کلید' : 'فعال کردن مجدد'}
className={`p-1.5 rounded-lg border transition-colors ${
k.status === 'ACTIVE'
? 'text-gray-500 hover:text-amber-600 hover:bg-amber-50 border-gray-200'
: 'text-gray-500 hover:text-emerald-600 hover:bg-emerald-50 border-gray-200'
}`}
>
<Power className="w-4 h-4" />
</button>
<button
onClick={() => handleDelete(k.id, k.name)}
title="حذف دائمی کلید"
className="p-1.5 rounded-lg border border-gray-200 text-gray-500 hover:text-red-600 hover:bg-red-50 transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Modal: Create API Key */}
{isCreateModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div className="bg-white rounded-2xl w-full max-w-lg overflow-hidden shadow-xl animate-scale-up">
<div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="p-1.5 bg-purple-50 text-purple-600 rounded-lg">
<Key className="w-5 h-5" />
</div>
<h3 className="font-bold text-gray-900 text-base">ساخت کلید دسترسی جدید</h3>
</div>
<button
onClick={() => setIsCreateModalOpen(false)}
className="text-gray-400 hover:text-gray-600 text-xl font-bold"
>
&times;
</button>
</div>
<form onSubmit={handleCreate} className="p-6 space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">
عنوان کلید <span className="text-red-500">*</span>
</label>
<input
type="text"
required
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="مثلاً: ورک‌فلو n8n یا اتصال انبار"
className="w-full px-3.5 py-2 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-purple-600/20 focus:border-purple-600"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">توضیحات (اختیاری)</label>
<input
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="کاربرد این کلید در کجاست؟"
className="w-full px-3.5 py-2 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-purple-600/20 focus:border-purple-600"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">مدت اعتبار و انقضا</label>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
{[
{ id: 'never', label: 'بدون انقضا (دائمی)' },
{ id: '30d', label: '۳۰ روزه' },
{ id: '90d', label: '۹۰ روزه' },
{ id: '1y', label: 'یک‌ساله' },
].map((opt) => (
<button
key={opt.id}
type="button"
onClick={() => setExpiryOption(opt.id as any)}
className={`py-2 px-2 text-xs rounded-xl border font-bold transition-all ${
expiryOption === opt.id
? 'bg-purple-50 border-purple-600 text-purple-700 shadow-sm'
: 'bg-gray-50 border-gray-200 text-gray-600 hover:bg-gray-100'
}`}
>
{opt.label}
</button>
))}
</div>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-2">سطح دسترسی (Scopes)</label>
<div className="space-y-2 max-h-48 overflow-y-auto pr-1">
{scopeOptions.map((scope) => {
const isChecked = selectedScopes.includes(scope.id);
return (
<div
key={scope.id}
onClick={() => toggleScope(scope.id)}
className={`p-2.5 rounded-xl border cursor-pointer transition-all flex items-start gap-2.5 ${
isChecked
? 'bg-purple-50/50 border-purple-300'
: 'bg-white border-gray-200 hover:bg-gray-50'
}`}
>
<input
type="checkbox"
checked={isChecked}
onChange={() => {}}
className="mt-0.5 rounded text-purple-600 focus:ring-purple-500"
/>
<div className="text-xs">
<div className="font-bold text-gray-900">{scope.label}</div>
<div className="text-gray-500 text-[11px]">{scope.desc}</div>
</div>
</div>
);
})}
</div>
</div>
<div className="pt-4 border-t border-gray-100 flex items-center justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => setIsCreateModalOpen(false)}
>
انصراف
</Button>
<Button
type="submit"
variant="primary"
disabled={isCreating}
className="bg-purple-600 hover:bg-purple-700 text-white font-bold"
>
{isCreating ? 'در حال ایجاد...' : 'تولید کلید دسترسی'}
</Button>
</div>
</form>
</div>
</div>
)}
{/* Modal: Show Newly Created Key (Once-only) */}
{newlyCreatedKey && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
<div className="bg-white rounded-2xl w-full max-w-lg overflow-hidden shadow-2xl animate-scale-up border-2 border-emerald-500">
<div className="bg-emerald-600 text-white px-6 py-4 flex items-center gap-3">
<Shield className="w-6 h-6" />
<div>
<h3 className="font-bold text-base">کلید دسترسی با موفقیت تولید شد</h3>
<p className="text-xs text-emerald-100">لطفاً کلید زیر را فوراً ذخیره کنید</p>
</div>
</div>
<div className="p-6 space-y-4">
<div className="bg-amber-50 border border-amber-200 rounded-xl p-3.5 flex items-start gap-2.5 text-xs text-amber-900">
<AlertTriangle className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
<p className="leading-relaxed">
<strong>هشدار امنیتی:</strong> این کلید محرمانه <strong>تنها یک‌بار</strong> به شما نمایش داده می‌شود. به محض بستن این پنجره، دیگر امکان بازیابی متن کامل کلید وجود نخواهد داشت. لطفاً آن را در محلی امن (یا در بخش Credentials نود n8n) کپی نمایید.
</p>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">کلید دسترسی (API Key):</label>
<div className="relative">
<input
type="text"
readOnly
value={newlyCreatedKey}
className="w-full bg-gray-50 border border-gray-300 font-mono text-xs sm:text-sm px-3.5 py-3 rounded-xl pr-3 pl-24 text-gray-900 select-all font-bold"
/>
<button
onClick={() => copyToClipboard(newlyCreatedKey)}
className="absolute left-1.5 top-1.5 bottom-1.5 px-3 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-xs font-bold flex items-center gap-1.5 shadow-sm transition-all"
>
{copied ? (
<>
<Check className="w-3.5 h-3.5" />
<span>کپی شد</span>
</>
) : (
<>
<Copy className="w-3.5 h-3.5" />
<span>کپی کلید</span>
</>
)}
</button>
</div>
</div>
<div className="pt-2 flex justify-end">
<Button
variant="primary"
onClick={() => setNewlyCreatedKey(null)}
className="bg-gray-900 hover:bg-black text-white font-bold"
>
کلید را ذخیره کردم، بستن پنجره
</Button>
</div>
</div>
</div>
</div>
)}
</div>
);
}
@@ -38,6 +38,7 @@ const ShippingSettingsPage = lazyWithRetry(() => import('../pages/ShippingSettin
const SystemSettingsPage = lazyWithRetry(() => import('../pages/SystemSettingsPage'));
const SmsSettingsPage = lazyWithRetry(() => import('../pages/SmsSettingsPage'));
const SslSettingsPage = lazyWithRetry(() => import('../pages/SslSettingsPage'));
const ApiKeysPage = lazyWithRetry(() => import('../pages/ApiKeysPage'));
const Transactions = lazyWithRetry(() => import('../pages/Transactions'));
const Tickets = lazyWithRetry(() => import('../pages/Tickets'));
const Reviews = lazyWithRetry(() => import('../pages/Reviews'));
@@ -79,6 +80,7 @@ export const router = createBrowserRouter([
{ path: 'settings/payment-methods', element: <PaymentGatewaysPage /> },
{ path: 'settings/shipping', element: <ShippingSettingsPage /> },
{ path: 'settings/ssl', element: <SslSettingsPage /> },
{ path: 'settings/api-keys', element: <ApiKeysPage /> },
{ path: 'settings/sms', element: <SmsSettingsPage /> },
{ path: 'settings/seo', element: <SeoSettingsPage /> },
{ path: 'settings/financial', element: <FinancialSettingsPage /> },
+21
View File
@@ -226,4 +226,25 @@ export interface PricingSettings {
defaultWholesaleMarginPercent: number;
}
export interface ApiKeyItem {
id: string;
name: string;
keyPrefix: string;
scopes: string[];
status: 'ACTIVE' | 'REVOKED';
description?: string | null;
expiresAt?: string | null;
lastUsedAt?: string | null;
createdAt: string;
updatedAt?: string;
isExpired?: boolean;
}
export interface CreateApiKeyPayload {
name: string;
description?: string;
scopes?: string[];
expiresAt?: string;
}