summaryrefslogtreecommitdiff
path: root/lib/users/session/helper.ts
blob: 4c5113405357edc8e2cc9cd83cda1452f4ff1382 (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
import { authenticateWithSGips, verifyExternalCredentials } from "../auth/verifyCredentails";
import { SessionRepository } from "./repository";
import { isEmailWhitelisted } from "@/lib/email-whitelist/service";

// lib/session/helpers.ts - NextAuth 헬퍼 함수들 개선
export const authHelpers = {
    // 1차 인증 검증 및 임시 키 생성 (DB 버전)
    async performFirstAuth(username: string, password: string, provider: 'email' | 'sgips') {
      console.log('performFirstAuth started:', { username, provider })

      try {
        let authResult;

        if (provider === 'sgips') {
          authResult = await authenticateWithSGips(username, password)
        } else {
          authResult = await verifyExternalCredentials(username, password)
        }

        if (!authResult.success) {
          return { success: false, error: authResult.error || 'INVALID_CREDENTIALS' }
        }

        // S-GIPS의 경우 otpUsers 배열 반환
        if (provider === 'sgips' && authResult.otpUsers) {
          console.log('S-GIPS auth successful with otpUsers:', authResult.otpUsers.length)

          return {
            success: true,
            otpUsers: authResult.otpUsers
          }
        }

        // 일반 사용자의 경우 기존 로직
        if (!authResult.user) {
          return { success: false, error: 'INVALID_CREDENTIALS' }
        }

        // 화이트리스트 체크하여 MFA 타입 결정
        const isWhitelisted = await isEmailWhitelisted(authResult.user.email);
        const mfaType = isWhitelisted ? 'email' : 'sms';

        console.log('Whitelist check:', {
          email: authResult.user.email,
          isWhitelisted,
          mfaType
        });

        // DB에 임시 인증 세션 생성
        const expiresAt = new Date(Date.now() + (10 * 60 * 1000)) // 10분 후 만료
        const tempAuthKey = await SessionRepository.createTempAuthSession({
          userId: authResult.user.id,
          email: authResult.user.email,
          authMethod: provider,
          expiresAt
        })

        console.log('Temp auth stored in DB:', {
          tempAuthKey,
          userId: authResult.user.id,
          email: authResult.user.email,
          authMethod: provider,
          mfaType,
          expiresAt
        })

        return {
          success: true,
          tempAuthKey,
          userId: authResult.user.id,
          email: authResult.user.email,
          mfaType, // 'email' 또는 'sms'
          userName: authResult.user.name, // Email OTP 전송 시 필요
        }
      } catch (error) {
        console.error('First auth error:', error)
        return { success: false, error: 'SYSTEM_ERROR' }
      }
    },
  
    // 임시 인증 정보 조회 (DB 버전)
    async getTempAuth(tempAuthKey: string) {
      return await SessionRepository.getTempAuthSession(tempAuthKey)
    },
  
    // 임시 인증 정보 삭제 (DB 버전)
    async clearTempAuth(tempAuthKey: string) {
      await SessionRepository.markTempAuthSessionAsUsed(tempAuthKey)
    },

    // 선택된 S-GIPS 사용자에 대한 임시 인증 세션 생성
    async createTempAuthForSelectedUser(selectedUser: {
      userId: number;
      email: string;
      name: string;
    }) {
      console.log('Creating temp auth for selected S-GIPS user:', selectedUser)

      try {
        const expiresAt = new Date(Date.now() + (10 * 60 * 1000)) // 10분 후 만료
        const tempAuthKey = await SessionRepository.createTempAuthSession({
          userId: selectedUser.userId,
          email: selectedUser.email,
          authMethod: 'sgips',
          expiresAt
        })

        console.log('Temp auth created for selected user:', {
          tempAuthKey,
          userId: selectedUser.userId,
          email: selectedUser.email,
          expiresAt
        })

        return {
          success: true,
          tempAuthKey,
          userId: selectedUser.userId,
          email: selectedUser.email
        }
      } catch (error) {
        console.error('Error creating temp auth for selected user:', error)
        return { success: false, error: 'SYSTEM_ERROR' }
      }
    }
  }