summaryrefslogtreecommitdiff
path: root/lib/users/auth/verifyCredentails.ts
blob: 8cb3c43485f528bbabdcf163f6cb1dba1849c2c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
// lib/auth/verifyCredentials.ts
'use server'

import bcrypt from 'bcryptjs';
import crypto from 'crypto';
// (처리 불필요) 키 암호화를 위한 fs 모듈 사용, 형제 경로 사용하며 public 경로 아니므로 파일이 노출되지 않음.
import fs from 'fs';
import path from 'path';
import { eq, and, desc, gte, count } from 'drizzle-orm';
import db from '@/db/db';
import {
  users,
  passwords,
  passwordHistory,
  loginAttempts,
  securitySettings,
  mfaTokens,
  vendors
} from '@/db/schema';
import { headers } from 'next/headers';
import {  verifySmsToken } from './passwordUtil';

// 에러 타입 정의
export type AuthError =
  | 'INVALID_CREDENTIALS'
  | 'ACCOUNT_LOCKED'
  | 'PASSWORD_EXPIRED'
  | 'ACCOUNT_DISABLED'
  | 'RATE_LIMITED'
  | 'MFA_REQUIRED'
  | 'SYSTEM_ERROR';

export interface AuthResult {
  success: boolean;
  user?: {
    id: number;
    name: string;
    email: string;
    imageUrl?: string | null;
    companyId?: number | null;
    techCompanyId?: number | null;
    domain?: string | null;
  };
  error?: AuthError;
  requiresMfa?: boolean;
  mfaToken?: string; // MFA가 필요한 경우 임시 토큰
}

// 클라이언트 IP 가져오기
export async function getClientIP(): Promise<string> {
  const headersList = await headers();          // ✨ await!
  const forwarded = headersList.get('x-forwarded-for');
  const realIP = headersList.get('x-real-ip');

  if (forwarded) return forwarded.split(',')[0].trim();
  if (realIP) return realIP;
  return 'unknown';
}

// User-Agent 가져오기
export async function getUserAgent(): Promise<string> {
  const headersList = await headers();          // ✨ await!
  return headersList.get('user-agent') ?? 'unknown';
}


// 보안 설정 가져오기 (캐시 고려)
async function getSecuritySettings() {
  const settings = await db.select().from(securitySettings).limit(1);
  return settings[0] || {
    maxFailedAttempts: 5,
    lockoutDurationMinutes: 30,
    requireMfaForPartners: true,
    smsTokenExpiryMinutes: 5,
    maxSmsAttemptsPerDay: 10,
    passwordExpiryDays: 90,
  };
}

// Rate limiting 체크
async function checkRateLimit(email: string, ipAddress: string): Promise<boolean> {
  const now = new Date();
  const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);

  // 이메일별 시도 횟수 체크 (1시간 내 20회 제한)
  const emailAttempts = await db
    .select({ count: count() })
    .from(loginAttempts)
    .where(
      and(
        eq(loginAttempts.email, email),
        gte(loginAttempts.attemptedAt, oneHourAgo)
      )
    );

  if (emailAttempts[0]?.count >= 20) {
    return false;
  }

  // IP별 시도 횟수 체크 (1시간 내 50회 제한)
  const ipAttempts = await db
    .select({ count: count() })
    .from(loginAttempts)
    .where(
      and(
        eq(loginAttempts.ipAddress, ipAddress),
        gte(loginAttempts.attemptedAt, oneHourAgo)
      )
    );

  if (ipAttempts[0]?.count >= 50) {
    return false;
  }

  return true;
}

// 로그인 시도 기록
async function logLoginAttempt(
  username: string,
  userId: number | null,
  success: boolean,
  failureReason?: string
) {
  const ipAddress = getClientIP();
  const userAgent = getUserAgent();

  await db.insert(loginAttempts).values({
    email: username,
    userId,
    success,
    ipAddress,
    userAgent,
    failureReason,
    attemptedAt: new Date(),

  });
}

// 계정 잠금 체크 및 업데이트
async function checkAndUpdateLockout(userId: number, settings: any): Promise<boolean> {
  const user = await db
    .select({
      isLocked: users.isLocked,
      lockoutUntil: users.lockoutUntil,
      failedAttempts: users.failedLoginAttempts,
    })
    .from(users)
    .where(eq(users.id, userId))
    .limit(1);

  if (!user[0]) return true; // 사용자가 없으면 잠금 처리

  const now = new Date();

  // 잠금 해제 시간이 지났는지 확인
  if (user[0].lockoutUntil && user[0].lockoutUntil < now) {
    await db
      .update(users)
      .set({
        isLocked: false,
        lockoutUntil: null,
        failedLoginAttempts: 0,
      })
      .where(eq(users.id, userId));
    return false;
  }

  return user[0].isLocked;
}

// 실패한 로그인 시도 처리
async function handleFailedLogin(userId: number, settings: any) {
  const user = await db
    .select({
      failedAttempts: users.failedLoginAttempts,
    })
    .from(users)
    .where(eq(users.id, userId))
    .limit(1);

  if (!user[0]) return;

  const newFailedAttempts = user[0].failedAttempts + 1;
  const shouldLock = newFailedAttempts >= settings.maxFailedAttempts;

  const updateData: any = {
    failedLoginAttempts: newFailedAttempts,
  };

  if (shouldLock) {
    const lockoutUntil = new Date();
    lockoutUntil.setMinutes(lockoutUntil.getMinutes() + settings.lockoutDurationMinutes);

    updateData.isLocked = true;
    updateData.lockoutUntil = lockoutUntil;
  }

  await db
    .update(users)
    .set(updateData)
    .where(eq(users.id, userId));
}

// 성공한 로그인 처리
async function handleSuccessfulLogin(userId: number) {
  await db
    .update(users)
    .set({
      failedLoginAttempts: 0,
      lastLoginAt: new Date(),
      isLocked: false,
      lockoutUntil: null,
    })
    .where(eq(users.id, userId));
}

// 패스워드 만료 체크
async function checkPasswordExpiry(userId: number, settings: any): Promise<boolean> {
  if (!settings.passwordExpiryDays) return false;

  const password = await db
    .select({
      createdAt: passwords.createdAt,
      expiresAt: passwords.expiresAt,
    })
    .from(passwords)
    .where(
      and(
        eq(passwords.userId, userId),
        eq(passwords.isActive, true)
      )
    )
    .limit(1);

  if (!password[0]) return true; // 패스워드가 없으면 만료 처리

  const now = new Date();

  // 명시적 만료일이 있는 경우
  if (password[0].expiresAt && password[0].expiresAt < now) {
    return true;
  }

  // 생성일 기준 만료 체크
  const expiryDate = new Date(password[0].createdAt);
  expiryDate.setDate(expiryDate.getDate() + settings.passwordExpiryDays);

  return expiryDate < now;
}

// MFA 필요 여부 확인
function requiresMfa(domain: string, settings: any): boolean {
  return domain === 'partners' && settings.requireMfaForPartners;
}



// 메인 인증 함수
export async function verifyExternalCredentials(
  username: string,
  password: string
): Promise<AuthResult> {
  const ipAddress = getClientIP();

  try {
    // 1. Rate limiting 체크
    const rateLimitOk = await checkRateLimit(username, ipAddress);
    if (!rateLimitOk) {
      await logLoginAttempt(username, null, false, 'RATE_LIMITED');
      return { success: false, error: 'RATE_LIMITED' };
    }

    // 2. 보안 설정 가져오기
    const settings = await getSecuritySettings();

    // 3. 사용자 조회
    const userResult = await db
      .select({
        id: users.id,
        name: users.name,
        email: users.email,
        imageUrl: users.imageUrl,
        companyId: users.companyId,
        techCompanyId: users.techCompanyId,
        domain: users.domain,
        mfaEnabled: users.mfaEnabled,
        isActive: users.isActive, // 추가

      })
      .from(users)
      .where(
        and(
          eq(users.email, username),
          eq(users.isActive, true) // 활성 유저만
        )
      )
      .limit(1);



    if (!userResult[0]) {

      const deactivatedUser = await db
        .select({ id: users.id })
        .from(users)
        .where(eq(users.email, username))
        .limit(1);

      if (deactivatedUser[0]) {
        await logLoginAttempt(username, deactivatedUser[0].id, false, 'ACCOUNT_DEACTIVATED');
        return { success: false, error: 'ACCOUNT_DEACTIVATED' };
      }

      // 타이밍 공격 방지를 위해 가짜 해시 연산
      await bcrypt.compare(password, '$2a$12$fake.hash.to.prevent.timing.attacks');
      await logLoginAttempt(username, null, false, 'INVALID_CREDENTIALS');
      // 보안상 계정 존재 여부와 비밀번호 오류를 구분하지 않습니다
      return { success: false, error: 'INVALID_CREDENTIALS' };
    }

    const user = userResult[0];

    // 4. 계정 잠금 체크
    const isLocked = await checkAndUpdateLockout(user.id, settings);
    if (isLocked) {
      await logLoginAttempt(username, user.id, false, 'ACCOUNT_LOCKED');
      return { success: false, error: 'ACCOUNT_LOCKED' };
    }

    // 5. 패스워드 조회 및 검증
    const passwordResult = await db
      .select({
        passwordHash: passwords.passwordHash,
        salt: passwords.salt,
      })
      .from(passwords)
      .where(
        and(
          eq(passwords.userId, user.id),
          eq(passwords.isActive, true)
        )
      )
      .limit(1);

    if (!passwordResult[0]) {
      await logLoginAttempt(username, user.id, false, 'INVALID_CREDENTIALS');
      await handleFailedLogin(user.id, settings);
      return { success: false, error: 'INVALID_CREDENTIALS' };
    }

    // 6. 패스워드 검증
    const isValidPassword = await bcrypt.compare(
      password + passwordResult[0].salt,
      passwordResult[0].passwordHash
    );

    if (!isValidPassword) {
      await logLoginAttempt(username, user.id, false, 'INVALID_CREDENTIALS');
      await handleFailedLogin(user.id, settings);
      return { success: false, error: 'INVALID_CREDENTIALS' };
    }

    // 7. 패스워드 만료 체크
    const isPasswordExpired = await checkPasswordExpiry(user.id, settings);
    if (isPasswordExpired) {
      await logLoginAttempt(username, user.id, false, 'PASSWORD_EXPIRED');
      return { success: false, error: 'PASSWORD_EXPIRED' };
    }

    // 9. 성공 처리
    await handleSuccessfulLogin(user.id);
    await logLoginAttempt(username, user.id, true);

    return {
      success: true,
      user: {
        id: user.id,
        name: user.name,
        email: user.email,
        imageUrl: user.imageUrl,
        companyId: user.companyId,
        techCompanyId: user.techCompanyId,
        domain: user.domain,
      },
    };

  } catch (error) {
    console.error('Authentication error:', error);
    await logLoginAttempt(username, null, false, 'SYSTEM_ERROR');
    return { success: false, error: 'SYSTEM_ERROR' };
  }
}


export async function completeMfaAuthentication(
  userId: string,
  smsToken: string
): Promise<{ success: boolean; error?: string }> {
  try {
    // SMS 토큰 검증
    const result = await verifySmsToken(parseInt(userId), smsToken);

    if (result.success) {
      // MFA 성공 시 사용자의 마지막 로그인 시간 업데이트
      await db
        .update(users)
        .set({
          lastLoginAt: new Date(),
          failedLoginAttempts: 0,
        })
        .where(eq(users.id, parseInt(userId)));

      // 성공한 로그인 기록
      await logLoginAttempt(
        '', // 이미 1차 인증에서 기록되었으므로 빈 문자열
        parseInt(userId),
        true,
        'MFA_COMPLETED'
      );
    }

    return result;
  } catch (error) {
    console.error('MFA completion error:', error);
    return { success: false, error: '인증 처리 중 오류가 발생했습니다' };
  }
}

// RSA 암호화 함수
function encryptPasswordWithRSA(password: string): string {
  try {
    
    // 파일에서 RSA 공개키 읽기
    const keyPath = path.join(process.cwd(), 'lib/users/auth/public_key.pem');
    
    // 파일 존재 여부 확인
    if (!fs.existsSync(keyPath)) {
      throw new Error(`RSA 키 파일을 찾을 수 없습니다: ${keyPath}`);
    }

    const publicKey = fs.readFileSync(keyPath, 'utf8');

    // RSA 공개키로 암호화 (Java와 동일한 OAEP 패딩 사용)
    const encryptOptions = {
      key: publicKey,
      padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256',        // Java: SHA-256 (MGF1 해시도 동일 값 사용됨)
    };

    const encryptedBuffer = crypto.publicEncrypt(encryptOptions, Buffer.from(password, 'utf8'));

    // Base64로 인코딩하여 반환
    const base64Result = encryptedBuffer.toString('base64');

    return base64Result;
  } catch (error) {
    console.error('RSA 암호화 오류:', error);
    throw new Error('비밀번호 암호화에 실패했습니다.');
  }
}

// 서버 액션: 벤더 정보 조회
export async function getVendorByCode(vendorCode: string) {
  try {
    const vendor = await db
      .select()
      .from(vendors)
      .where(eq(vendors.vendorCode, vendorCode))
      .limit(1);

    return vendor[0] || null;
  } catch (error) {
    console.error('Database error:', error);
    return null;
  }
}

// 수정된 S-Gips 인증 함수
export async function verifySGipsCredentials(
  username: string,
  password: string
): Promise<{
  success: boolean;
  user?: {
    id: string;
    name: string;
    email: string;
    phone: string;
    companyId?: number;
    vendorInfo?: any; // 벤더 추가 정보
  };
  error?: string;
}> {
  try {

    const sgipsUrl = process.env.S_GIPS_URL || "http://qa.shi-api.com/evcp/Common/verifySgipsUser"

    // password를 RSA로 암호화
    const encryptedPassword = encryptPasswordWithRSA(password);

    // URLSearchParams를 사용하여 특수문자를 안전하게 인코딩
    const params = new URLSearchParams({
      Id: username,
      Passwd: encryptedPassword,
    });

    const requestUrl = `${sgipsUrl}?${params.toString()}`;

    const response = await fetch(requestUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.SHI_API_JWT_TOKEN}`,
      },
    });

    // 응답 본문을 한 번만 읽어서 재사용
    const responseText = await response.text();

    if (!response.ok && response.status == 401) {
      console.error('유효하지 않은 S-GIPS JWT 응답코드 발생 :', response.status);
      console.error('오류 응답 본문:', responseText);
      return { success: false, error: 'INVALID_CREDENTIALS' };
    }

    // 텍스트를 JSON으로 파싱
    let data;
    try {
      data = JSON.parse(responseText);
    } catch (e) {
      console.error('S-Gips Invalid JSON response:', e);
      throw new Error('S-Gips Invalid JSON response');
    }
    
    // 2. S-Gips API 응답 확인
    if (data.message === "success" && data.code === "0") {
      // 3. username의 앞 8자리로 vendorCode 추출
      const vendorCode = username.substring(0, 8);
      
      // 4. 데이터베이스에서 벤더 정보 조회
      const vendorInfo = await getVendorByCode(vendorCode);
      
      if (!vendorInfo) {
        return { 
          success: false, 
          error: 'VENDOR_NOT_FOUND' 
        };
      }

      // 5. 사용자 정보 구성
      return {
        success: true,
        user: {
          id: username, // 또는 vendorInfo.id를 사용
          name: vendorInfo.representativeName || vendorInfo.vendorName,
          email: vendorInfo.representativeEmail || vendorInfo.email || '',
          phone: vendorInfo.representativePhone || vendorInfo.phone || '',
          companyId: vendorInfo.id,
          vendorInfo: {
            vendorName: vendorInfo.vendorName,
            vendorCode: vendorInfo.vendorCode,
            status: vendorInfo.status,
            taxId: vendorInfo.taxId,
            address: vendorInfo.address,
            country: vendorInfo.country,
            website: vendorInfo.website,
            vendorTypeId: vendorInfo.vendorTypeId,
            businessSize: vendorInfo.businessSize,
            creditRating: vendorInfo.creditRating,
            cashFlowRating: vendorInfo.cashFlowRating,
          }
        },
      };
    }

    return { success: false, error: 'INVALID_CREDENTIALS' };

  } catch (error) {
    console.error('S-Gips API error:', error);
    return { success: false, error: 'SYSTEM_ERROR' };
  }
}


// S-Gips 사용자를 위한 통합 인증 함수
export async function authenticateWithSGips(
  username: string,
  password: string
): Promise<{
  success: boolean;
  user?: {
    id: number;
    name: string;
    email: string;
    imageUrl?: string | null;
    companyId?: number | null;
    techCompanyId?: number | null;
    domain?: string | null;
  };
  requiresMfa: boolean;
  mfaToken?: string;
  error?: string;
}> {
  try {
    // 1. S-Gips API로 인증
    const sgipsResult = await verifySGipsCredentials(username, password);

    if (!sgipsResult.success || !sgipsResult.user) {
      return {
        success: false,
        requiresMfa: false,
        error: sgipsResult.error || 'INVALID_CREDENTIALS',
      };
    }

    // 2. 로컬 DB에서 사용자 확인 또는 생성
    let localUser = await db
      .select()
      .from(users)
      .where(eq(users.email, sgipsResult.user.email))
      .limit(1);

    if (!localUser[0]) {
      // 사용자가 없으면 새로 생성 (S-Gips 사용자는 자동 생성)
      const newUser = await db
        .insert(users)
        .values({
          name: sgipsResult.user.name,
          email: sgipsResult.user.email,
          phone: sgipsResult.user.phone,
          companyId: sgipsResult.user.companyId,
          domain: 'partners', // S-Gips 사용자는 partners 도메인
          mfaEnabled: true, // S-Gips 사용자는 MFA 필수
        })
        .returning();

      localUser = newUser;
    }

    const user = localUser[0];

    return {
      success: true,
      user: {
        id: user.id,
        name: user.name,
        email: user.email,
        imageUrl: user.imageUrl,
        companyId: user.companyId,
        techCompanyId: user.techCompanyId,
        domain: user.domain,
      },
      requiresMfa: true,
      // mfaToken,
    };
  } catch (error) {
    console.error('S-Gips authentication error:', error);
    return {
      success: false,
      requiresMfa: false,
      error: 'SYSTEM_ERROR',
    };
  }
}