summaryrefslogtreecommitdiff
path: root/lib/email-whitelist/service.ts
diff options
context:
space:
mode:
Diffstat (limited to 'lib/email-whitelist/service.ts')
-rw-r--r--lib/email-whitelist/service.ts577
1 files changed, 577 insertions, 0 deletions
diff --git a/lib/email-whitelist/service.ts b/lib/email-whitelist/service.ts
new file mode 100644
index 00000000..d7e968b0
--- /dev/null
+++ b/lib/email-whitelist/service.ts
@@ -0,0 +1,577 @@
+'use server';
+
+/* IMPORT */
+import { and, asc, count, desc, eq, ilike, or, sql, type SQL, type InferSelectModel, inArray } from 'drizzle-orm';
+import { authOptions } from '@/app/api/auth/[...nextauth]/route';
+import db from '@/db/db';
+import { getServerSession } from 'next-auth';
+import { type Filter } from '@/types/table';
+import {
+ emailWhitelist,
+} from '@/db/schema/emailWhitelist';
+import { users } from '@/db/schema/users';
+import { revalidatePath } from 'next/cache';
+
+// ----------------------------------------------------------------------------------------------------
+
+/* TYPES */
+export type EmailWhitelist = InferSelectModel<typeof emailWhitelist> & {
+ createdByName?: string;
+ updatedByName?: string;
+ type?: 'domain' | 'email'; // 표시용 타입
+ displayValue?: string; // 표시할 값 (domain 또는 email)
+}
+
+// ===========================================
+// Helper Functions
+// ===========================================
+
+/**
+ * 이메일 유효성 검증
+ */
+function validateEmail(email: string): { isValid: boolean; error?: string } {
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+ if (!emailRegex.test(email)) {
+ return { isValid: false, error: '올바른 이메일 형식이 아닙니다.' };
+ }
+
+ // 길이 제한
+ if (email.length > 255) {
+ return { isValid: false, error: '이메일은 255자를 초과할 수 없습니다.' };
+ }
+
+ return { isValid: true };
+}
+
+/**
+ * 도메인 유효성 검증
+ */
+function validateDomain(domain: string): { isValid: boolean; error?: string } {
+ // 도메인 검증: 최소 하나의 .이 있어야 하고, TLD가 있어야 함
+ // 예: company.com, sub.company.com, company.co.kr
+ const domainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
+
+ if (!domainRegex.test(domain)) {
+ return { isValid: false, error: '올바른 도메인 형식이 아닙니다. 최소 1개의 TLD가 필요합니다.' };
+ }
+
+ // 길이 제한
+ if (domain.length > 255) {
+ return { isValid: false, error: '도메인은 255자를 초과할 수 없습니다.' };
+ }
+
+ return { isValid: true };
+}
+
+/**
+ * 입력값이 이메일인지 도메인인지 판별
+ */
+function determineType(value: string): 'email' | 'domain' {
+ return value.includes('@') ? 'email' : 'domain';
+}
+
+/**
+ * 화이트리스트 항목 중복 검증
+ */
+async function checkWhitelistExists(value: string, type: 'email' | 'domain', excludeId?: number): Promise<boolean> {
+ let whereCondition;
+
+ if (type === 'email') {
+ whereCondition = eq(emailWhitelist.email, value);
+ } else {
+ whereCondition = eq(emailWhitelist.domain, value);
+ }
+
+ const existing = await db
+ .select({ id: emailWhitelist.id })
+ .from(emailWhitelist)
+ .where(whereCondition)
+ .limit(1);
+
+ if (existing.length === 0) return false;
+ if (excludeId && existing[0].id === excludeId) return false;
+
+ return true;
+}
+
+// ===========================================
+// CRUD Operations
+// ===========================================
+
+/**
+ * 이메일 화이트리스트 목록 조회
+ */
+export async function getEmailWhitelistList({
+ page = 1,
+ perPage = 10,
+ search,
+ sort = 'createdAt.desc',
+ filters,
+}: {
+ page?: number;
+ perPage?: number;
+ search?: string;
+ sort?: string;
+ filters?: Filter<EmailWhitelist>[];
+} = {}) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session?.user?.id) {
+ throw new Error('인증이 필요합니다.');
+ }
+
+ const offset = (page - 1) * perPage;
+
+ // 정렬 처리
+ let orderBy: SQL<unknown>;
+ const [sortField, sortOrder] = sort.split('.');
+
+ // 계산된 필드에 대한 정렬 매핑
+ const sortFieldMapping: Record<string, string> = {
+ 'displayValue': 'domain', // displayValue는 domain 우선으로 정렬
+ 'createdByName': 'createdAt', // 이름 정렬 대신 생성일로 정렬
+ 'updatedByName': 'updatedAt', // 이름 정렬 대신 수정일로 정렬
+ };
+
+ const actualSortField = sortFieldMapping[sortField] || sortField;
+
+ if (actualSortField === 'domain') {
+ orderBy = sortOrder === 'desc' ? desc(emailWhitelist.domain) : asc(emailWhitelist.domain);
+ } else if (actualSortField === 'email') {
+ orderBy = sortOrder === 'desc' ? desc(emailWhitelist.email) : asc(emailWhitelist.email);
+ } else if (actualSortField === 'description') {
+ orderBy = sortOrder === 'desc' ? desc(emailWhitelist.description) : asc(emailWhitelist.description);
+ } else if (actualSortField === 'createdAt') {
+ orderBy = sortOrder === 'desc' ? desc(emailWhitelist.createdAt) : asc(emailWhitelist.createdAt);
+ } else if (actualSortField === 'updatedAt') {
+ orderBy = sortOrder === 'desc' ? desc(emailWhitelist.updatedAt) : asc(emailWhitelist.updatedAt);
+ } else {
+ orderBy = desc(emailWhitelist.createdAt);
+ }
+
+ // 필터 조건들
+ const filterConditions: SQL<unknown>[] = [];
+
+ // 검색 필터
+ if (search) {
+ const searchCondition = or(
+ ilike(emailWhitelist.domain, `%${search}%`),
+ ilike(emailWhitelist.email, `%${search}%`),
+ ilike(emailWhitelist.description, `%${search}%`)
+ ) as SQL<unknown>;
+ filterConditions.push(searchCondition);
+ }
+
+ // 고급 필터
+ if (filters && filters.length > 0) {
+ for (const filter of filters) {
+ const { id, value, operator = 'iLike' } = filter;
+
+ // string[] 타입은 지원하지 않음 (select 필터용)
+ if (!value || typeof value !== 'string') continue;
+
+ let condition: SQL<unknown> | undefined;
+
+ switch (id) {
+ case 'displayValue':
+ // displayValue는 domain이나 email 중 하나를 포함하므로 둘 다 검색
+ if (operator === 'iLike') {
+ condition = or(
+ ilike(emailWhitelist.domain, `%${value}%`),
+ ilike(emailWhitelist.email, `%${value}%`)
+ );
+ } else if (operator === 'eq') {
+ condition = or(
+ eq(emailWhitelist.domain, value),
+ eq(emailWhitelist.email, value)
+ );
+ }
+ break;
+ case 'domain':
+ if (operator === 'iLike') {
+ condition = ilike(emailWhitelist.domain, `%${value}%`);
+ } else if (operator === 'eq') {
+ condition = eq(emailWhitelist.domain, value);
+ }
+ break;
+ case 'email':
+ if (operator === 'iLike') {
+ condition = ilike(emailWhitelist.email, `%${value}%`);
+ } else if (operator === 'eq') {
+ condition = eq(emailWhitelist.email, value);
+ }
+ break;
+ case 'description':
+ if (operator === 'iLike') {
+ condition = ilike(emailWhitelist.description, `%${value}%`);
+ } else if (operator === 'eq') {
+ condition = eq(emailWhitelist.description, value);
+ }
+ break;
+ case 'createdAt':
+ if (operator === 'gte' && value) {
+ condition = sql`${emailWhitelist.createdAt} >= ${value}`;
+ } else if (operator === 'lte' && value) {
+ condition = sql`${emailWhitelist.createdAt} <= ${value}`;
+ }
+ break;
+ case 'updatedAt':
+ if (operator === 'gte' && value) {
+ condition = sql`${emailWhitelist.updatedAt} >= ${value}`;
+ } else if (operator === 'lte' && value) {
+ condition = sql`${emailWhitelist.updatedAt} <= ${value}`;
+ }
+ break;
+ }
+
+ if (condition) {
+ filterConditions.push(condition);
+ }
+ }
+ }
+
+ // 데이터 조회 (기본 데이터)
+ const query = db
+ .select()
+ .from(emailWhitelist)
+
+ if (filterConditions.length > 0) {
+ query.where(and(...filterConditions))
+ }
+
+ const rawData = await query
+ .orderBy(orderBy)
+ .limit(perPage)
+ .offset(offset);
+
+ // 사용자 ID들 수집
+ const userIds = new Set<number>();
+ rawData.forEach(item => {
+ if (item.createdBy) userIds.add(item.createdBy);
+ if (item.updatedBy) userIds.add(item.updatedBy);
+ });
+
+ // 사용자 정보 조회
+ const userMap = new Map<number, string>();
+ if (userIds.size > 0) {
+ const userData = await db
+ .select({ id: users.id, name: users.name })
+ .from(users)
+ .where(inArray(users.id, Array.from(userIds)));
+
+ userData.forEach(user => {
+ userMap.set(user.id, user.name);
+ });
+ }
+
+ // 데이터에 사용자 이름과 타입 정보 추가
+ const data: EmailWhitelist[] = rawData.map(item => {
+ const displayValue = item.email || item.domain || '';
+ const type = displayValue.includes('@') ? 'email' : 'domain';
+
+ return {
+ ...item,
+ createdByName: item.createdBy ? userMap.get(item.createdBy) : undefined,
+ updatedByName: item.updatedBy ? userMap.get(item.updatedBy) : undefined,
+ type,
+ displayValue,
+ };
+ });
+
+ // 전체 개수 조회
+ const countQuery = db
+ .select({ count: count() })
+ .from(emailWhitelist)
+
+ if (filterConditions.length > 0) {
+ countQuery.where(and(...filterConditions))
+ }
+
+ const totalResult = await countQuery;
+
+ const total = totalResult[0].count;
+ const pageCount = Math.ceil(total / perPage);
+
+ return {
+ data,
+ pageCount,
+ total,
+ };
+ } catch (error) {
+ throw new Error(error instanceof Error ? error.message : '목록 조회에 실패했습니다.');
+ }
+}
+
+/**
+ * 이메일 화이트리스트 생성
+ */
+export async function createEmailWhitelistAction(data: {
+ value: string; // 이메일 주소 또는 도메인
+ description?: string;
+}) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session?.user?.id) {
+ return {
+ success: false,
+ error: '인증이 필요합니다.'
+ };
+ }
+
+ const type = determineType(data.value);
+
+ // 유효성 검증
+ let validation;
+ if (type === 'email') {
+ validation = validateEmail(data.value);
+ } else {
+ validation = validateDomain(data.value);
+ }
+
+ if (!validation.isValid) {
+ return {
+ success: false,
+ error: validation.error
+ };
+ }
+
+ // 중복 검증
+ const exists = await checkWhitelistExists(data.value.toLowerCase(), type);
+ if (exists) {
+ return {
+ success: false,
+ error: type === 'email' ? '이미 등록된 이메일입니다.' : '이미 등록된 도메인입니다.'
+ };
+ }
+
+ // 생성
+ const insertData: {
+ description?: string;
+ createdBy: number;
+ updatedBy: number;
+ domain?: string | null;
+ email?: string | null;
+ } = {
+ description: data.description,
+ createdBy: Number(session.user.id),
+ updatedBy: Number(session.user.id),
+ domain: null,
+ email: null,
+ };
+
+ if (type === 'email') {
+ insertData.email = data.value.toLowerCase();
+ } else {
+ insertData.domain = data.value.toLowerCase();
+ }
+
+ const [result] = await db
+ .insert(emailWhitelist)
+ .values(insertData)
+ .returning();
+
+ revalidatePath('/evcp/system/whitelist');
+
+ return {
+ success: true,
+ data: result
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : '생성에 실패했습니다.'
+ };
+ }
+}
+
+/**
+ * 이메일 화이트리스트 수정
+ */
+export async function updateEmailWhitelistAction(data: {
+ id: number;
+ value: string; // 이메일 주소 또는 도메인
+ description?: string;
+}) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session?.user?.id) {
+ return {
+ success: false,
+ error: '인증이 필요합니다.'
+ };
+ }
+
+ const type = determineType(data.value);
+
+ // 유효성 검증
+ let validation;
+ if (type === 'email') {
+ validation = validateEmail(data.value);
+ } else {
+ validation = validateDomain(data.value);
+ }
+
+ if (!validation.isValid) {
+ return {
+ success: false,
+ error: validation.error
+ };
+ }
+
+ // 중복 검증
+ const exists = await checkWhitelistExists(data.value.toLowerCase(), type, data.id);
+ if (exists) {
+ return {
+ success: false,
+ error: type === 'email' ? '이미 등록된 이메일입니다.' : '이미 등록된 도메인입니다.'
+ };
+ }
+
+ // 수정
+ const updateData: {
+ description?: string;
+ updatedBy: number;
+ updatedAt: ReturnType<typeof sql>;
+ domain: string | null;
+ email: string | null;
+ } = {
+ description: data.description,
+ updatedBy: Number(session.user.id),
+ updatedAt: sql`NOW()`,
+ domain: null,
+ email: null,
+ };
+
+ if (type === 'email') {
+ updateData.email = data.value.toLowerCase();
+ } else {
+ updateData.domain = data.value.toLowerCase();
+ }
+
+ const [result] = await db
+ .update(emailWhitelist)
+ .set(updateData)
+ .where(eq(emailWhitelist.id, data.id))
+ .returning();
+
+ if (!result) {
+ return {
+ success: false,
+ error: '수정할 데이터를 찾을 수 없습니다.'
+ };
+ }
+
+ revalidatePath('/evcp/system/whitelist');
+
+ return {
+ success: true,
+ data: result
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : '수정에 실패했습니다.'
+ };
+ }
+}
+
+/**
+ * 이메일 화이트리스트 삭제
+ */
+export async function deleteEmailWhitelistAction(ids: number[]) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session?.user?.id) {
+ return {
+ success: false,
+ error: '인증이 필요합니다.'
+ };
+ }
+
+ // 삭제
+ await db
+ .delete(emailWhitelist)
+ .where(inArray(emailWhitelist.id, ids));
+
+ revalidatePath('/evcp/system/whitelist');
+
+ return {
+ success: true
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : '삭제에 실패했습니다.'
+ };
+ }
+}
+
+/**
+ * 단일 이메일 화이트리스트 조회
+ */
+export async function getEmailWhitelistById(id: number) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session?.user?.id) {
+ throw new Error('인증이 필요합니다.');
+ }
+
+ const [result] = await db
+ .select()
+ .from(emailWhitelist)
+ .where(eq(emailWhitelist.id, id))
+ .limit(1);
+
+ if (!result) {
+ throw new Error('데이터를 찾을 수 없습니다.');
+ }
+
+ return result;
+ } catch (error) {
+ throw new Error(error instanceof Error ? error.message : '조회에 실패했습니다.');
+ }
+}
+
+/**
+ * 이메일 주소가 화이트리스트에 등록되어 있는지 확인
+ * @param email - 확인할 이메일 주소
+ * @returns 화이트리스트에 등록되어 있으면 true, 아니면 false
+ */
+export async function isEmailWhitelisted(email: string): Promise<boolean> {
+ try {
+ if (!email) return false;
+
+ const normalizedEmail = email.toLowerCase().trim();
+
+ // 이메일에서 도메인 추출
+ const emailParts = normalizedEmail.split('@');
+ if (emailParts.length !== 2) return false;
+
+ const domain = emailParts[1];
+
+ // 1. 개별 이메일이 화이트리스트에 있는지 확인
+ const exactEmailMatch = await db
+ .select({ id: emailWhitelist.id })
+ .from(emailWhitelist)
+ .where(eq(emailWhitelist.email, normalizedEmail))
+ .limit(1);
+
+ if (exactEmailMatch.length > 0) {
+ return true;
+ }
+
+ // 2. 도메인이 화이트리스트에 있는지 확인
+ const domainMatch = await db
+ .select({ id: emailWhitelist.id })
+ .from(emailWhitelist)
+ .where(eq(emailWhitelist.domain, domain))
+ .limit(1);
+
+ return domainMatch.length > 0;
+ } catch (error) {
+ console.error('화이트리스트 확인 중 오류:', error);
+ // 오류 발생 시 안전하게 false 반환 (기본 SMS 인증 사용)
+ return false;
+ }
+}