Email OTP

Email OTP 플러그인을 사용하면 사용자가 이메일 주소로 전송된 일회용 비밀번호(OTP)를 사용하여 로그인하거나, 이메일을 확인하거나, 비밀번호를 재설정할 수 있습니다.

설치

auth 설정에 플러그인 추가

emailOTP 플러그인을 auth 설정에 추가하고 sendVerificationOTP() 메서드를 구현합니다.

auth.ts
import { betterAuth } from "better-auth"
import { emailOTP } from "better-auth/plugins"

export const auth = betterAuth({
    // ... 기타 설정 옵션
    plugins: [
        emailOTP({ 
            async sendVerificationOTP({ email, otp, type }) { 
                if (type === "sign-in") { 
                    // 로그인용 OTP 전송
                } else if (type === "email-verification") { 
                    // 이메일 확인용 OTP 전송
                } else { 
                    // 비밀번호 재설정용 OTP 전송
                } 
            }, 
        }) 
    ]
})

클라이언트 플러그인 추가

auth-client.ts
import { createAuthClient } from "better-auth/client"
import { emailOTPClient } from "better-auth/client/plugins"

export const authClient = createAuthClient({
    plugins: [
        emailOTPClient()
    ]
})

사용법

OTP 전송

사용자의 이메일 주소로 OTP를 전송하려면 sendVerificationOtp() 메서드를 사용합니다.

POST
/email-otp/send-verification-otp
const { data, error } = await authClient.emailOtp.sendVerificationOtp({    email: "user@example.com", // required    type: "sign-in", // required});
PropDescriptionType
email
OTP를 전송할 이메일 주소
string
type
OTP 유형. sign-in, email-verification 또는 forget-password
"email-verification" | "sign-in" | "forget-password"

OTP 확인 (선택사항)

OTP가 유효한지 확인하려면 checkVerificationOtp() 메서드를 사용합니다.

POST
/email-otp/check-verification-otp
const { data, error } = await authClient.emailOtp.checkVerificationOtp({    email: "user@example.com", // required    type: "sign-in", // required    otp: "123456", // required});
PropDescriptionType
email
OTP를 전송할 이메일 주소
string
type
OTP 유형. sign-in, email-verification 또는 forget-password
"email-verification" | "sign-in" | "forget-password"
otp
이메일로 전송된 OTP
string

OTP로 로그인

OTP로 로그인하려면 sendVerificationOtp() 메서드를 사용하여 사용자의 이메일 주소로 "sign-in" OTP를 전송합니다.

POST
/email-otp/send-verification-otp
const { data, error } = await authClient.emailOtp.sendVerificationOtp({    email: "user@example.com", // required    type: "sign-in", // required});
PropDescriptionType
email
OTP를 전송할 이메일 주소
string
type
OTP 유형
"sign-in"

사용자가 OTP를 제공하면 signIn.emailOtp() 메서드를 사용하여 사용자를 로그인시킬 수 있습니다.

POST
/sign-in/email-otp
const { data, error } = await authClient.signIn.emailOtp({    email: "user@example.com", // required    otp: "123456", // required});
PropDescriptionType
email
로그인할 이메일 주소
string
otp
이메일로 전송된 OTP
string

사용자가 등록되지 않은 경우 자동으로 등록됩니다. 이를 방지하려면 옵션에서 disableSignUptrue로 전달할 수 있습니다.

OTP로 이메일 확인

OTP로 사용자의 이메일 주소를 확인하려면 sendVerificationOtp() 메서드를 사용하여 사용자의 이메일 주소로 "email-verification" OTP를 전송합니다.

POST
/email-otp/send-verification-otp
const { data, error } = await authClient.emailOtp.sendVerificationOtp({    email: "user@example.com", // required    type: "email-verification", // required});
PropDescriptionType
email
OTP를 전송할 이메일 주소
string
type
OTP 유형
"email-verification"

사용자가 OTP를 제공하면 verifyEmail() 메서드를 사용하여 이메일 확인을 완료합니다.

POST
/email-otp/verify-email
const { data, error } = await authClient.emailOtp.verifyEmail({    email: "user@example.com", // required    otp: "123456", // required});
PropDescriptionType
email
확인할 이메일 주소
string
otp
확인할 OTP
string

OTP로 비밀번호 재설정

OTP로 사용자의 비밀번호를 재설정하려면 forgetPassword.emailOTP() 메서드를 사용하여 사용자의 이메일 주소로 "forget-password" OTP를 전송합니다.

POST
/forget-password/email-otp
const { data, error } = await authClient.forgetPassword.emailOtp({    email: "user@example.com", // required});
PropDescriptionType
email
OTP를 전송할 이메일 주소
string

사용자가 OTP를 제공하면 checkVerificationOtp() 메서드를 사용하여 유효성을 확인합니다(선택사항).

POST
/email-otp/check-verification-otp
const { data, error } = await authClient.emailOtp.checkVerificationOtp({    email: "user@example.com", // required    type: "forget-password", // required    otp: "123456", // required});
PropDescriptionType
email
OTP를 전송할 이메일 주소
string
type
OTP 유형
"forget-password"
otp
이메일로 전송된 OTP
string

그런 다음 resetPassword() 메서드를 사용하여 사용자의 비밀번호를 재설정합니다.

POST
/email-otp/reset-password
const { data, error } = await authClient.emailOtp.resetPassword({    email: "user@example.com", // required    otp: "123456", // required    password: "new-secure-password", // required});
PropDescriptionType
email
비밀번호를 재설정할 이메일 주소
string
otp
이메일로 전송된 OTP
string
password
새 비밀번호
string

기본 이메일 확인 재정의

기본 이메일 확인을 재정의하려면 옵션에서 overrideDefaultEmailVerification: true를 전달합니다. 이렇게 하면 이메일 확인이 트리거될 때마다 시스템이 기본 확인 링크 대신 이메일 OTP를 사용합니다. 즉, 사용자가 링크를 클릭하는 대신 OTP를 사용하여 이메일을 확인합니다.

auth.ts
import { betterAuth } from "better-auth";

export const auth = betterAuth({
  plugins: [
    emailOTP({
      overrideDefaultEmailVerification: true, 
      async sendVerificationOTP({ email, otp, type }) {
        // OTP를 사용자의 이메일 주소로 전송하는 sendVerificationOTP 메서드를 구현합니다
      },
    }),
  ],
});

옵션

  • sendVerificationOTP: 사용자의 이메일 주소로 OTP를 전송하는 함수입니다. 함수는 다음 속성을 가진 객체를 받습니다:

    • email: 사용자의 이메일 주소
    • otp: 전송할 OTP
    • type: 전송할 OTP 유형. "sign-in", "email-verification" 또는 "forget-password"일 수 있습니다
  • otpLength: OTP의 길이입니다. 기본값은 6입니다.

  • expiresIn: OTP의 만료 시간(초)입니다. 기본값은 300초입니다.

auth.ts
import { betterAuth } from "better-auth"

export const auth = betterAuth({
    plugins: [
        emailOTP({
            otpLength: 8,
            expiresIn: 600
        })
    ]
})
  • sendVerificationOnSignUp: 사용자가 가입할 때 OTP를 전송할지 여부를 결정하는 부울 값입니다. 기본값은 false입니다.

  • disableSignUp: 사용자가 등록되지 않은 경우 자동 가입을 방지할지 여부를 결정하는 부울 값입니다. 기본값은 false입니다.

  • generateOTP: OTP를 생성하는 함수입니다. 기본값은 무작위 6자리 숫자입니다.

  • allowedAttempts: OTP 확인에 허용되는 최대 시도 횟수입니다. 기본값은 3입니다. 이 제한을 초과하면 OTP가 무효화되고 사용자는 새 OTP를 요청해야 합니다.

auth.ts
import { betterAuth } from "better-auth"

export const auth = betterAuth({
    plugins: [
        emailOTP({
            allowedAttempts: 5, // OTP를 무효화하기 전에 5번의 시도 허용
            expiresIn: 300
        })
    ]
})

최대 시도 횟수를 초과하면 verifyOTP, signIn.emailOtp, verifyEmailresetPassword 메서드가 TOO_MANY_ATTEMPTS 코드와 함께 오류를 반환합니다.

  • storeOTP: 데이터베이스에 OTP를 저장하는 방법으로, encrypted, hashed 또는 plain 텍스트 중 하나입니다. 기본값은 plain 텍스트입니다.

참고: 이것은 사용자에게 전송되는 OTP에는 영향을 미치지 않으며 데이터베이스에 저장되는 OTP에만 영향을 미칩니다.

또는 사용자 정의 암호화 또는 해시 함수를 전달하여 데이터베이스에 OTP를 저장할 수 있습니다.

사용자 정의 암호화

auth.ts
emailOTP({
    storeOTP: {
        encrypt: async (otp) => {
            return myCustomEncryptor(otp);
        },
        decrypt: async (otp) => {
            return myCustomDecryptor(otp);
        },
    }
})

사용자 정의 해시

auth.ts
emailOTP({
    storeOTP: {
        hash: async (otp) => {
            return myCustomHasher(otp);
        },
    }
})

On this page