snp-connection-monitoring/frontend/src/pages/apikeys/KeyRequestPage.tsx
HYOJIN 6f9923537e feat(phase3): API Key 관리 - 생성/발급/신청/승인/권한
백엔드:
- AES-256-GCM 암호화 (ApiKey 생성/복호화 조회)
- API Key 직접 생성 (ADMIN) + 신청→승인/반려 워크플로우
- 신청 필드 추가 (사용기간, 서비스IP, 서비스용도, 예상요청량)
- Permission CRUD (bulk delete+recreate, @Modifying JPQL)
- API Key 폐기, expires_at 자동 설정
- ErrorCode 5개 추가

프론트엔드:
- MyKeysPage: 키 목록, 상태 배지, 폐기, raw key 모달
- KeyRequestPage: 기간 프리셋/직접선택 토글, 서비스IP, 용도, 예상요청량, API 체크박스
- KeyAdminPage: 신청 검토(필드 노출+기간 조정) + 키 관리(복호화 조회, 권한 편집)

Closes #8

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 10:12:36 +09:00

400 lines
17 KiB
TypeScript

import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import type { ServiceInfo, ServiceApi } from '../../types/service';
import { getServices, getServiceApis } from '../../services/serviceService';
import { createKeyRequest } from '../../services/apiKeyService';
const METHOD_COLOR: Record<string, string> = {
GET: 'bg-green-100 text-green-800',
POST: 'bg-blue-100 text-blue-800',
PUT: 'bg-orange-100 text-orange-800',
DELETE: 'bg-red-100 text-red-800',
};
const KeyRequestPage = () => {
const navigate = useNavigate();
const [services, setServices] = useState<ServiceInfo[]>([]);
const [serviceApisMap, setServiceApisMap] = useState<Record<number, ServiceApi[]>>({});
const [expandedServices, setExpandedServices] = useState<Set<number>>(new Set());
const [selectedApiIds, setSelectedApiIds] = useState<Set<number>>(new Set());
const [keyName, setKeyName] = useState('');
const [purpose, setPurpose] = useState('');
const [serviceIp, setServiceIp] = useState('');
const [servicePurpose, setServicePurpose] = useState('');
const [dailyRequestEstimate, setDailyRequestEstimate] = useState('');
const [usagePeriodMode, setUsagePeriodMode] = useState<'preset' | 'custom'>('preset');
const [usageFromDate, setUsageFromDate] = useState('');
const [usageToDate, setUsageToDate] = useState('');
const [isLoading, setIsLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
const servicesRes = await getServices();
if (servicesRes.success && servicesRes.data) {
const activeServices = servicesRes.data.filter((s) => s.isActive);
setServices(activeServices);
const apisMap: Record<number, ServiceApi[]> = {};
await Promise.all(
activeServices.map(async (service) => {
const apisRes = await getServiceApis(service.serviceId);
if (apisRes.success && apisRes.data) {
apisMap[service.serviceId] = apisRes.data.filter((a) => a.isActive);
}
}),
);
setServiceApisMap(apisMap);
} else {
setError(servicesRes.message || '서비스 목록을 불러오는데 실패했습니다.');
}
} catch {
setError('서비스 목록을 불러오는데 실패했습니다.');
} finally {
setIsLoading(false);
}
};
fetchData();
}, []);
const handleToggleService = (serviceId: number) => {
setExpandedServices((prev) => {
const next = new Set(prev);
if (next.has(serviceId)) {
next.delete(serviceId);
} else {
next.add(serviceId);
}
return next;
});
};
const handleToggleApi = (apiId: number) => {
setSelectedApiIds((prev) => {
const next = new Set(prev);
if (next.has(apiId)) {
next.delete(apiId);
} else {
next.add(apiId);
}
return next;
});
};
const handleToggleAllServiceApis = (serviceId: number) => {
const apis = serviceApisMap[serviceId] || [];
const allSelected = apis.every((a) => selectedApiIds.has(a.apiId));
setSelectedApiIds((prev) => {
const next = new Set(prev);
apis.forEach((a) => {
if (allSelected) {
next.delete(a.apiId);
} else {
next.add(a.apiId);
}
});
return next;
});
};
const handlePresetPeriod = (months: number) => {
const from = new Date();
const to = new Date();
to.setMonth(to.getMonth() + months);
setUsageFromDate(from.toISOString().split('T')[0]);
setUsageToDate(to.toISOString().split('T')[0]);
setUsagePeriodMode('preset');
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (selectedApiIds.size === 0) {
setError('최소 하나의 API를 선택해주세요.');
return;
}
if (!usageFromDate || !usageToDate) {
setError('사용 기간을 설정해주세요.');
return;
}
setError(null);
setIsSubmitting(true);
try {
const res = await createKeyRequest({
keyName,
purpose: purpose || undefined,
requestedApiIds: Array.from(selectedApiIds),
serviceIp: serviceIp || undefined,
servicePurpose: servicePurpose || undefined,
dailyRequestEstimate: dailyRequestEstimate ? Number(dailyRequestEstimate) : undefined,
usageFromDate,
usageToDate,
});
if (res.success) {
setSuccess(true);
} else {
setError(res.message || 'API Key 신청에 실패했습니다.');
}
} catch {
setError('API Key 신청에 실패했습니다.');
} finally {
setIsSubmitting(false);
}
};
if (isLoading) {
return <div className="text-center py-10 text-gray-500"> ...</div>;
}
if (success) {
return (
<div className="max-w-lg mx-auto mt-10 text-center">
<div className="bg-green-50 border border-green-200 rounded-lg p-6">
<h2 className="text-lg font-semibold text-green-800 mb-2"> </h2>
<p className="text-green-700 text-sm mb-4">
API Key가 .
</p>
<button
onClick={() => navigate('/apikeys/my-keys')}
className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium"
>
</button>
</div>
</div>
);
}
return (
<div>
<h1 className="text-2xl font-bold text-gray-900 mb-6">API Key </h1>
{error && (
<div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>
)}
<form onSubmit={handleSubmit}>
<div className="bg-white rounded-lg shadow p-6 mb-6 space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Key Name <span className="text-red-500">*</span>
</label>
<input
type="text"
value={keyName}
onChange={(e) => setKeyName(e.target.value)}
required
placeholder="API Key 이름을 입력하세요"
className="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"> </label>
<textarea
value={purpose}
onChange={(e) => setPurpose(e.target.value)}
rows={2}
placeholder="사용 목적을 입력하세요"
className="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
<span className="text-red-500">*</span>
</label>
<div className="flex items-center gap-2 mb-2">
<button type="button" onClick={() => handlePresetPeriod(3)}
disabled={usagePeriodMode === 'custom'}
className={`px-3 py-1.5 text-sm rounded-lg border ${usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-blue-50'}`}>
3
</button>
<button type="button" onClick={() => handlePresetPeriod(6)}
disabled={usagePeriodMode === 'custom'}
className={`px-3 py-1.5 text-sm rounded-lg border ${usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-blue-50'}`}>
6
</button>
<button type="button" onClick={() => handlePresetPeriod(9)}
disabled={usagePeriodMode === 'custom'}
className={`px-3 py-1.5 text-sm rounded-lg border ${usagePeriodMode === 'custom' ? 'opacity-40 cursor-not-allowed' : 'hover:bg-blue-50'}`}>
9
</button>
<span className="text-gray-400 mx-1">|</span>
<label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer select-none">
<button type="button"
onClick={() => setUsagePeriodMode(usagePeriodMode === 'custom' ? 'preset' : 'custom')}
className={`relative w-10 h-5 rounded-full transition-colors ${usagePeriodMode === 'custom' ? 'bg-blue-600' : 'bg-gray-300'}`}>
<span className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${usagePeriodMode === 'custom' ? 'translate-x-5' : ''}`} />
</button>
</label>
</div>
<div className="flex items-center gap-2">
<input type="date" value={usageFromDate}
onChange={(e) => setUsageFromDate(e.target.value)}
readOnly={usagePeriodMode !== 'custom'}
className={`border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none ${usagePeriodMode !== 'custom' ? 'bg-gray-50 text-gray-500' : ''}`} />
<span className="text-gray-500">~</span>
<input type="date" value={usageToDate}
onChange={(e) => setUsageToDate(e.target.value)}
readOnly={usagePeriodMode !== 'custom'}
className={`border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none ${usagePeriodMode !== 'custom' ? 'bg-gray-50 text-gray-500' : ''}`} />
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
IP <span className="text-red-500">*</span>
</label>
<input type="text" value={serviceIp}
onChange={(e) => setServiceIp(e.target.value)}
required placeholder="예: 192.168.1.100"
className="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none" />
<p className="text-xs text-gray-400 mt-1"> API Key로 IP</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
<span className="text-red-500">*</span>
</label>
<select value={servicePurpose}
onChange={(e) => setServicePurpose(e.target.value)}
required
className="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
<option value=""></option>
<option value="로컬 환경"> </option>
<option value="개발 서버"> </option>
<option value="검증 서버"> </option>
<option value="운영 서버"> </option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
<span className="text-red-500">*</span>
</label>
<select value={dailyRequestEstimate}
onChange={(e) => setDailyRequestEstimate(e.target.value)}
required
className="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
<option value=""></option>
<option value="100">100 </option>
<option value="500">100~500</option>
<option value="1000">500~1,000</option>
<option value="5000">1,000~5,000</option>
<option value="10000">5,000~10,000</option>
<option value="50000">10,000 </option>
</select>
</div>
</div>
</div>
<div className="bg-white rounded-lg shadow mb-6">
<div className="px-6 py-4 border-b">
<h2 className="text-lg font-semibold text-gray-900">
API <span className="text-sm font-normal text-gray-500">({selectedApiIds.size} )</span>
</h2>
</div>
<div className="divide-y divide-gray-200">
{services.map((service) => {
const apis = serviceApisMap[service.serviceId] || [];
const isExpanded = expandedServices.has(service.serviceId);
const selectedCount = apis.filter((a) => selectedApiIds.has(a.apiId)).length;
const allSelected = apis.length > 0 && apis.every((a) => selectedApiIds.has(a.apiId));
return (
<div key={service.serviceId}>
<div
className="px-6 py-3 flex items-center justify-between cursor-pointer hover:bg-gray-50"
onClick={() => handleToggleService(service.serviceId)}
>
<div className="flex items-center gap-3">
<span className="text-gray-400 text-sm">{isExpanded ? '\u25BC' : '\u25B6'}</span>
<span className="font-medium text-gray-900">{service.serviceName}</span>
{selectedCount > 0 && (
<span className="text-xs bg-blue-100 text-blue-800 px-2 py-0.5 rounded-full">
{selectedCount}/{apis.length}
</span>
)}
</div>
<span className="text-sm text-gray-500">{apis.length} API</span>
</div>
{isExpanded && (
<div className="px-6 pb-3">
{apis.length > 0 && (
<div className="mb-2 pl-6">
<label className="flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
<input
type="checkbox"
checked={allSelected}
onChange={() => handleToggleAllServiceApis(service.serviceId)}
className="rounded"
/>
</label>
</div>
)}
<div className="space-y-1 pl-6">
{apis.map((api) => (
<label
key={api.apiId}
className="flex items-center gap-2 py-1 cursor-pointer hover:bg-gray-50 rounded px-2"
>
<input
type="checkbox"
checked={selectedApiIds.has(api.apiId)}
onChange={() => handleToggleApi(api.apiId)}
className="rounded"
/>
<span
className={`inline-block px-2 py-0.5 rounded text-xs font-bold ${
METHOD_COLOR[api.apiMethod] || 'bg-gray-100 text-gray-800'
}`}
>
{api.apiMethod}
</span>
<span className="font-mono text-sm text-gray-700">{api.apiPath}</span>
<span className="text-sm text-gray-500">- {api.apiName}</span>
</label>
))}
{apis.length === 0 && (
<p className="text-sm text-gray-400 py-1"> API가 .</p>
)}
</div>
</div>
)}
</div>
);
})}
{services.length === 0 && (
<div className="px-6 py-8 text-center text-gray-400">
.
</div>
)}
</div>
</div>
<div className="flex justify-end">
<button
type="submit"
disabled={isSubmitting}
className="bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white px-6 py-2 rounded-lg text-sm font-medium"
>
{isSubmitting ? '신청 중...' : '신청하기'}
</button>
</div>
</form>
</div>
);
};
export default KeyRequestPage;