refactor(WEB): Server Action 공통화 및 보안 강화

- executeServerAction 공통 유틸 도입으로 actions.ts 대폭 간소화 (50+개 파일)
- sanitize 유틸 추가 (XSS 방지)
- middleware CSP 헤더 추가 및 Open Redirect 방지
- 프록시 라우트 로깅 개발환경 한정으로 변경
- 프로덕션 불필요 console.log 제거

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
유병철
2026-02-09 16:14:06 +09:00
parent d014227e9c
commit 55e0791e16
85 changed files with 7211 additions and 17638 deletions

View File

@@ -16,9 +16,9 @@
'use server';
import { executeServerAction } from '@/lib/api/execute-server-action';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { cookies } from 'next/headers';
import { serverFetch, getServerApiHeaders } from '@/lib/api/fetch-wrapper';
import type { Employee, EmployeeFormData, EmployeeStats } from './types';
import { transformApiToFrontend, transformFrontendToApi, type EmployeeApiData } from './utils';
@@ -40,332 +40,138 @@ interface PaginatedResponse<T> {
last_page: number;
}
const API_URL = process.env.NEXT_PUBLIC_API_URL;
// ============================================
// API 함수
// ============================================
/**
* 직원 목록 조회
*/
export async function getEmployees(params?: {
page?: number;
per_page?: number;
q?: string;
status?: string;
department_id?: string;
has_account?: boolean;
sort_by?: string;
sort_dir?: 'asc' | 'desc';
page?: number; per_page?: number; q?: string; status?: string;
department_id?: string; has_account?: boolean;
sort_by?: string; sort_dir?: 'asc' | 'desc';
}): Promise<{ data: Employee[]; total: number; lastPage: number; __authError?: boolean }> {
try {
const searchParams = new URLSearchParams();
const searchParams = new URLSearchParams();
if (params?.page) searchParams.set('page', String(params.page));
if (params?.per_page) searchParams.set('per_page', String(params.per_page));
if (params?.q) searchParams.set('q', params.q);
if (params?.status && params.status !== 'all') searchParams.set('status', params.status);
if (params?.department_id) searchParams.set('department_id', params.department_id);
if (params?.has_account !== undefined) searchParams.set('has_account', String(params.has_account));
if (params?.sort_by) searchParams.set('sort_by', params.sort_by);
if (params?.sort_dir) searchParams.set('sort_dir', params.sort_dir);
if (params?.page) searchParams.set('page', String(params.page));
if (params?.per_page) searchParams.set('per_page', String(params.per_page));
if (params?.q) searchParams.set('q', params.q);
if (params?.status && params.status !== 'all') {
searchParams.set('status', params.status);
}
if (params?.department_id) searchParams.set('department_id', params.department_id);
if (params?.has_account !== undefined) {
searchParams.set('has_account', String(params.has_account));
}
if (params?.sort_by) searchParams.set('sort_by', params.sort_by);
if (params?.sort_dir) searchParams.set('sort_dir', params.sort_dir);
const result = await executeServerAction<PaginatedResponse<EmployeeApiData>>({
url: `${API_URL}/api/v1/employees?${searchParams.toString()}`,
errorMessage: '직원 목록 조회에 실패했습니다.',
});
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees?${searchParams.toString()}`;
if (result.__authError) return { data: [], total: 0, lastPage: 1, __authError: true };
if (!result.success || !result.data?.data) return { data: [], total: 0, lastPage: 1 };
const { response, error } = await serverFetch(url, { method: 'GET' });
// 🚨 401 인증 에러 → 클라이언트에서 로그인 페이지로 리다이렉트
if (error?.__authError) {
return { data: [], total: 0, lastPage: 1, __authError: true };
}
if (!response || !response.ok) {
console.error('[EmployeeActions] GET list error:', response?.status);
return { data: [], total: 0, lastPage: 1 };
}
const result: ApiResponse<PaginatedResponse<EmployeeApiData>> = await response.json();
if (!result.success || !result.data?.data) {
console.warn('[EmployeeActions] No data in response');
return { data: [], total: 0, lastPage: 1 };
}
return {
data: result.data.data.map(transformApiToFrontend),
total: result.data.total,
lastPage: result.data.last_page,
};
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] getEmployees error:', error);
return { data: [], total: 0, lastPage: 1 };
}
return {
data: result.data.data.map(transformApiToFrontend),
total: result.data.total,
lastPage: result.data.last_page,
};
}
/**
* 직원 상세 조회
*/
export async function getEmployeeById(id: string): Promise<Employee | null | { __authError: true }> {
try {
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/${id}`;
const { response, error } = await serverFetch(url, { method: 'GET' });
const result = await executeServerAction({
url: `${API_URL}/api/v1/employees/${id}`,
transform: (data: EmployeeApiData) => transformApiToFrontend(data),
errorMessage: '직원 조회에 실패했습니다.',
});
// 🚨 401 인증 에러
if (error?.__authError) {
return { __authError: true };
}
if (!response || !response.ok) {
console.error('[EmployeeActions] GET employee error:', response?.status);
return null;
}
const result: ApiResponse<EmployeeApiData> = await response.json();
if (!result.success || !result.data) {
return null;
}
return transformApiToFrontend(result.data);
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] getEmployeeById error:', error);
return null;
}
if (result.__authError) return { __authError: true };
return result.success ? result.data || null : null;
}
/**
* 직원 등록
*/
export async function createEmployee(
data: EmployeeFormData
): Promise<{
success: boolean;
data?: Employee;
error?: string;
errors?: Record<string, string[]>;
status?: number;
__authError?: boolean;
success: boolean; data?: Employee; error?: string;
errors?: Record<string, string[]>; status?: number; __authError?: boolean;
}> {
try {
const apiData = transformFrontendToApi(data);
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees`;
const apiData = transformFrontendToApi(data);
const result = await executeServerAction({
url: `${API_URL}/api/v1/employees`,
method: 'POST',
body: apiData,
transform: (d: EmployeeApiData) => transformApiToFrontend(d),
errorMessage: '직원 등록에 실패했습니다.',
});
console.log('[EmployeeActions] POST employee request:', apiData);
const { response, error } = await serverFetch(url, {
method: 'POST',
body: JSON.stringify(apiData),
});
// 🚨 401 인증 에러
if (error?.__authError) {
return { success: false, __authError: true };
}
if (!response) {
return { success: false, error: error?.message || '서버 오류가 발생했습니다.' };
}
const result = await response.json();
console.log('[EmployeeActions] POST employee response:', result);
if (!response.ok || !result.success) {
return {
success: false,
error: result.message || '직원 등록에 실패했습니다.',
errors: result.error?.details, // validation errors: error.details 구조
status: result.error?.code || response.status,
};
}
return {
success: true,
data: transformApiToFrontend(result.data),
};
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] createEmployee error:', error);
return {
success: false,
error: '서버 오류가 발생했습니다.',
};
}
if (result.__authError) return { success: false, __authError: true };
return { success: result.success, data: result.data, error: result.error };
}
/**
* 직원 수정
*/
export async function updateEmployee(
id: string,
data: EmployeeFormData
): Promise<{ success: boolean; data?: Employee; error?: string; __authError?: boolean }> {
try {
const apiData = transformFrontendToApi(data);
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/${id}`;
const apiData = transformFrontendToApi(data);
const result = await executeServerAction({
url: `${API_URL}/api/v1/employees/${id}`,
method: 'PATCH',
body: apiData,
transform: (d: EmployeeApiData) => transformApiToFrontend(d),
errorMessage: '직원 수정에 실패했습니다.',
});
console.log('[EmployeeActions] PATCH employee request:', apiData);
const { response, error } = await serverFetch(url, {
method: 'PATCH',
body: JSON.stringify(apiData),
});
// 🚨 401 인증 에러
if (error?.__authError) {
return { success: false, __authError: true };
}
if (!response) {
return { success: false, error: error?.message || '서버 오류가 발생했습니다.' };
}
const result = await response.json();
console.log('[EmployeeActions] PATCH employee response:', result);
if (!response.ok || !result.success) {
return {
success: false,
error: result.message || '직원 수정에 실패했습니다.',
};
}
return {
success: true,
data: transformApiToFrontend(result.data),
};
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] updateEmployee error:', error);
return {
success: false,
error: '서버 오류가 발생했습니다.',
};
}
if (result.__authError) return { success: false, __authError: true };
return { success: result.success, data: result.data, error: result.error };
}
/**
* 직원 삭제 (퇴직 처리)
*/
export async function deleteEmployee(id: string): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
try {
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/${id}`;
const { response, error } = await serverFetch(url, { method: 'DELETE' });
const result = await executeServerAction({
url: `${API_URL}/api/v1/employees/${id}`,
method: 'DELETE',
errorMessage: '직원 삭제에 실패했습니다.',
});
// 🚨 401 인증 에러
if (error?.__authError) {
return { success: false, __authError: true };
}
if (!response) {
return { success: false, error: error?.message || '서버 오류가 발생했습니다.' };
}
const result = await response.json();
console.log('[EmployeeActions] DELETE employee response:', result);
if (!response.ok || !result.success) {
return {
success: false,
error: result.message || '직원 삭제에 실패했습니다.',
};
}
return { success: true };
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] deleteEmployee error:', error);
return {
success: false,
error: '서버 오류가 발생했습니다.',
};
}
if (result.__authError) return { success: false, __authError: true };
return { success: result.success, error: result.error };
}
/**
* 직원 일괄 삭제
*/
export async function deleteEmployees(ids: string[]): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
try {
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/bulk-delete`;
const { response, error } = await serverFetch(url, {
method: 'POST',
body: JSON.stringify({ ids: ids.map(id => parseInt(id, 10)) }),
});
const result = await executeServerAction({
url: `${API_URL}/api/v1/employees/bulk-delete`,
method: 'POST',
body: { ids: ids.map(id => parseInt(id, 10)) },
errorMessage: '직원 일괄 삭제에 실패했습니다.',
});
// 🚨 401 인증 에러
if (error?.__authError) {
return { success: false, __authError: true };
}
if (!response) {
return { success: false, error: error?.message || '서버 오류가 발생했습니다.' };
}
const result = await response.json();
console.log('[EmployeeActions] BULK DELETE employee response:', result);
if (!response.ok || !result.success) {
return {
success: false,
error: result.message || '직원 일괄 삭제에 실패했습니다.',
};
}
return { success: true };
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] deleteEmployees error:', error);
return {
success: false,
error: '서버 오류가 발생했습니다.',
};
}
if (result.__authError) return { success: false, __authError: true };
return { success: result.success, error: result.error };
}
interface EmployeeStatsApiData {
active_count: number;
leave_count: number;
resigned_count: number;
average_tenure: number;
}
/**
* 직원 통계 조회
*/
export async function getEmployeeStats(): Promise<EmployeeStats | null | { __authError: true }> {
try {
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/stats`;
const { response, error } = await serverFetch(url, { method: 'GET' });
const result = await executeServerAction<EmployeeStatsApiData>({
url: `${API_URL}/api/v1/employees/stats`,
errorMessage: '직원 통계 조회에 실패했습니다.',
});
// 🚨 401 인증 에러
if (error?.__authError) {
return { __authError: true };
}
if (result.__authError) return { __authError: true };
if (!result.success || !result.data) return null;
if (!response || !response.ok) {
console.error('[EmployeeActions] GET stats error:', response?.status);
return null;
}
const result = await response.json();
if (!result.success || !result.data) {
return null;
}
return {
activeCount: result.data.active_count ?? 0,
leaveCount: result.data.leave_count ?? 0,
resignedCount: result.data.resigned_count ?? 0,
averageTenure: result.data.average_tenure ?? 0,
};
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] getEmployeeStats error:', error);
return null;
}
return {
activeCount: result.data.active_count ?? 0,
leaveCount: result.data.leave_count ?? 0,
resignedCount: result.data.resigned_count ?? 0,
averageTenure: result.data.average_tenure ?? 0,
};
}
// ============================================
// 직급/직책 조회 (positions)
// 직급/직책 조회 (native fetch - keep as-is)
// ============================================
export interface PositionItem {
@@ -377,47 +183,19 @@ export interface PositionItem {
is_active: boolean;
}
/**
* 직급/직책 목록 조회
* @param type 'rank' (직급) | 'title' (직책) | undefined (전체)
*/
export async function getPositions(type?: 'rank' | 'title'): Promise<PositionItem[]> {
try {
const headers = await getServerApiHeaders();
const searchParams = new URLSearchParams();
if (type) {
searchParams.set('type', type);
}
const searchParams = new URLSearchParams();
if (type) searchParams.set('type', type);
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/positions?${searchParams.toString()}`;
const response = await fetch(url, {
method: 'GET',
headers,
cache: 'no-store',
});
if (!response.ok) {
console.error('[EmployeeActions] GET positions error:', response.status);
return [];
}
const result: ApiResponse<PositionItem[]> = await response.json();
if (!result.success || !result.data) {
return [];
}
return result.data;
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] getPositions error:', error);
return [];
}
const result = await executeServerAction<PositionItem[]>({
url: `${API_URL}/api/v1/positions?${searchParams.toString()}`,
errorMessage: '직급/직책 조회에 실패했습니다.',
});
return result.data || [];
}
// ============================================
// 부서 조회 (departments)
// 부서 조회 (native fetch - keep as-is)
// ============================================
export interface DepartmentItem {
@@ -428,45 +206,17 @@ export interface DepartmentItem {
is_active: boolean;
}
/**
* 부서 목록 조회
*/
export async function getDepartments(): Promise<DepartmentItem[]> {
try {
const headers = await getServerApiHeaders();
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/departments`,
{
method: 'GET',
headers,
cache: 'no-store',
}
);
if (!response.ok) {
console.error('[EmployeeActions] GET departments error:', response.status);
return [];
}
const result = await response.json();
if (!result.success || !result.data) {
return [];
}
// 페이지네이션 응답 또는 배열 직접 반환 모두 처리
const departments = Array.isArray(result.data) ? result.data : result.data.data || [];
return departments;
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] getDepartments error:', error);
return [];
}
const result = await executeServerAction<DepartmentItem[] | { data: DepartmentItem[] }>({
url: `${API_URL}/api/v1/departments`,
errorMessage: '부서 조회에 실패했습니다.',
});
if (!result.data) return [];
return Array.isArray(result.data) ? result.data : result.data.data || [];
}
// ============================================
// 파일 업로드
// 파일 업로드 (native fetch - keep as-is)
// ============================================
export async function uploadProfileImage(inputFormData: FormData): Promise<{
@@ -479,16 +229,12 @@ export async function uploadProfileImage(inputFormData: FormData): Promise<{
const cookieStore = await cookies();
const token = cookieStore.get('access_token')?.value;
// 토큰 없으면 인증 에러
if (!token) {
return { success: false, __authError: true };
}
if (!token) return { success: false, __authError: true };
// 디렉토리 정보 추가
inputFormData.append('directory', 'employees/profiles');
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/files/upload`,
`${API_URL}/api/v1/files/upload`,
{
method: 'POST',
headers: {
@@ -499,29 +245,15 @@ export async function uploadProfileImage(inputFormData: FormData): Promise<{
}
);
// 🚨 401 인증 에러
if (response.status === 401) {
return { success: false, __authError: true };
}
if (!response.ok) {
return { success: false, error: `파일 업로드 실패: ${response.status}` };
}
if (response.status === 401) return { success: false, __authError: true };
if (!response.ok) return { success: false, error: `파일 업로드 실패: ${response.status}` };
const result = await response.json();
if (!result.success) return { success: false, error: result.message || '파일 업로드에 실패했습니다.' };
if (!result.success) {
return { success: false, error: result.message || '파일 업로드에 실패했습니다.' };
}
// 업로드된 파일 경로 추출 (API 응답: file_path 필드)
const uploadedPath = result.data?.file_path || result.data?.path || result.data?.url;
if (!uploadedPath) return { success: false, error: '업로드된 파일 경로를 가져올 수 없습니다.' };
if (!uploadedPath) {
return { success: false, error: '업로드된 파일 경로를 가져올 수 없습니다.' };
}
// /storage/tenants/ 경로로 변환 (tenant disk 파일 접근 경로)
const storagePath = uploadedPath.startsWith('/storage/')
? uploadedPath
: `/storage/tenants/${uploadedPath}`;
@@ -529,13 +261,12 @@ export async function uploadProfileImage(inputFormData: FormData): Promise<{
return {
success: true,
data: {
url: `${process.env.NEXT_PUBLIC_API_URL}${storagePath}`,
url: `${API_URL}${storagePath}`,
path: uploadedPath,
},
};
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[EmployeeActions] uploadProfileImage error:', error);
return { success: false, error: '서버 오류가 발생했습니다.' };
}
}
}