summaryrefslogtreecommitdiff
path: root/lib/users/send-otp.ts
blob: c8cfb83d6b57c6252d27f1a92f21e66eeeb2a10a (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
"use server";

import { headers } from 'next/headers';
import { sendEmail } from '@/lib/mail/sendEmail';
import jwt from 'jsonwebtoken';
import { findUserByEmail, addNewOtp } from '@/lib/users/service';


export async function sendOtpAction(email: string, lng: string) {
  // Next.js의 headers() API로 헤더 정보를 얻을 수 있습니다.
  const headersList = await headers();

  // 호스트 정보 (request.nextUrl.host 대체)
  const host = headersList.get('host') || 'localhost:3000';

  // 사용자 조회
  const user = await findUserByEmail(email);

  if (!user) {
    // 서버 액션에서 에러 던지면, 클라이언트 컴포넌트에서 try-catch로 잡을 수 있습니다.
    throw new Error('User does not exist');
  }

  // OTP 및 만료 시간 생성
  const otp = Math.floor(100000 + Math.random() * 900000).toString();
  const expires = new Date(Date.now() + 10 * 60 * 1000); // 10분 후 만료
  const token = jwt.sign(
    {
      email,
      otp,
      exp: Math.floor(expires.getTime() / 1000),
    },
    process.env.JWT_SECRET!
  );

  // DB에 OTP 추가
  await addNewOtp(email, otp, new Date(), token, expires);

  // 이메일에서 사용할 URL 구성
  const verificationUrl = `http://${host}/ko/login?token=${token}`;

  // IP 정보로부터 지역 조회 (ip-api 사용)
  const ip = headersList.get('x-forwarded-for')?.split(',')[0]?.trim() || '';
  let location = '';
  try {
    const response = await fetch(`http://ip-api.com/json/${ip}?fields=country,city`);
    const data = await response.json();
    location = data.city && data.country ? `${data.city}, ${data.country}` : '';
  } catch (error) {
    // 위치 조회 실패 시 무시
  }

  // OTP 이메일 발송
  await sendEmail({
    to: email,
    subject: `${otp} - SHI eVCP Sign-in Verification`,
    template: 'otp',
    context: {
      name: user.name,
      otp,
      verificationUrl,
      location,
      language: lng,
    },
  });

  // 클라이언트로 반환할 수 있는 값
  return {
    success: true,
  };
}