Last Login Method
last login method 플러그인은 사용자가 사용한 가장 최근의 인증 방법(이메일, OAuth 제공자 등)을 추적합니다. 이를 통해 로그인 페이지에서 "마지막으로 Google로 로그인했습니다"와 같은 유용한 표시를 하거나 사용자 선호도에 따라 특정 로그인 방법의 우선순위를 지정할 수 있습니다.
설치
auth 설정에 플러그인 추가
import { betterAuth } from "better-auth"
import { lastLoginMethod } from "better-auth/plugins"
export const auth = betterAuth({
// ... 기타 설정 옵션
plugins: [
lastLoginMethod()
]
})auth 클라이언트에 클라이언트 플러그인 추가
import { createAuthClient } from "better-auth/client"
import { lastLoginMethodClient } from "better-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [
lastLoginMethodClient()
]
})사용법
플러그인이 설치되면 사용자가 사용한 마지막 인증 방법을 자동으로 추적합니다. 그런 다음 애플리케이션에서 이 정보를 검색하고 표시할 수 있습니다.
마지막으로 사용한 방법 가져오기
클라이언트 플러그인은 마지막 로그인 방법으로 작업할 수 있는 여러 메서드를 제공합니다:
import { authClient } from "@/lib/auth-client"
// 마지막으로 사용한 로그인 방법 가져오기
const lastMethod = authClient.getLastUsedLoginMethod()
console.log(lastMethod) // "google", "email", "github" 등
// 특정 방법이 마지막으로 사용되었는지 확인
const wasGoogle = authClient.isLastUsedLoginMethod("google")
// 저장된 방법 지우기
authClient.clearLastUsedLoginMethod()UI 통합 예제
플러그인을 사용하여 로그인 페이지를 향상시키는 방법은 다음과 같습니다:
import { authClient } from "@/lib/auth-client"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
export function SignInPage() {
const lastMethod = authClient.getLastUsedLoginMethod()
return (
<div className="space-y-4">
<h1>로그인</h1>
{/* 이메일 로그인 */}
<div className="relative">
<Button
onClick={() => authClient.signIn.email({...})}
variant={lastMethod === "email" ? "default" : "outline"}
className="w-full"
>
이메일로 로그인
{lastMethod === "email" && (
<Badge className="ml-2">마지막 사용</Badge>
)}
</Button>
</div>
{/* OAuth 제공자 */}
<div className="relative">
<Button
onClick={() => authClient.signIn.social({ provider: "google" })}
variant={lastMethod === "google" ? "default" : "outline"}
className="w-full"
>
Google로 계속하기
{lastMethod === "google" && (
<Badge className="ml-2">마지막 사용</Badge>
)}
</Button>
</div>
<div className="relative">
<Button
onClick={() => authClient.signIn.social({ provider: "github" })}
variant={lastMethod === "github" ? "default" : "outline"}
className="w-full"
>
GitHub로 계속하기
{lastMethod === "github" && (
<Badge className="ml-2">마지막 사용</Badge>
)}
</Button>
</div>
</div>
)
}데이터베이스 지속성
기본적으로 마지막 로그인 방법은 쿠키에만 저장됩니다. 더 지속적인 추적과 분석을 위해 데이터베이스 저장을 활성화할 수 있습니다.
데이터베이스 저장 활성화
플러그인 구성에서 storeInDatabase를 true로 설정합니다:
import { betterAuth } from "better-auth"
import { lastLoginMethod } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
lastLoginMethod({
storeInDatabase: true
})
]
})데이터베이스 마이그레이션 실행
플러그인은 사용자 테이블에 lastLoginMethod 필드를 자동으로 추가합니다. 마이그레이션을 실행하여 변경 사항을 적용합니다:
npx @better-auth/cli migratenpx @better-auth/cli generate데이터베이스 필드 액세스
데이터베이스 저장이 활성화되면 lastLoginMethod 필드가 사용자 객체에서 사용 가능해집니다:
import { auth } from "@/lib/auth"
// 서버 측 액세스
const session = await auth.api.getSession({ headers })
console.log(session?.user.lastLoginMethod) // "google", "email" 등
// 세션을 통한 클라이언트 측 액세스
const { data: session } = authClient.useSession()
console.log(session?.user.lastLoginMethod)데이터베이스 스키마
storeInDatabase가 활성화되면 플러그인은 user 테이블에 다음 필드를 추가합니다:
테이블: user
| Field Name | Type | Key | Description |
|---|---|---|---|
| lastLoginMethod | string | 사용자가 사용한 마지막 인증 방법 |
사용자 정의 스키마 구성
데이터베이스 필드 이름을 사용자 정의할 수 있습니다:
import { betterAuth } from "better-auth"
import { lastLoginMethod } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
lastLoginMethod({
storeInDatabase: true,
schema: {
user: {
lastLoginMethod: "last_auth_method" // 사용자 정의 필드 이름
}
}
})
]
})구성 옵션
last login method 플러그인은 다음 옵션을 허용합니다:
서버 옵션
import { betterAuth } from "better-auth"
import { lastLoginMethod } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
lastLoginMethod({
// 쿠키 구성
cookieName: "better-auth.last_used_login_method", // 기본값: "better-auth.last_used_login_method"
maxAge: 60 * 60 * 24 * 30, // 기본값: 30일(초 단위)
// 데이터베이스 지속성
storeInDatabase: false, // 기본값: false
// 사용자 정의 메서드 해석
customResolveMethod: (ctx) => {
// 로그인 방법을 결정하는 사용자 정의 로직
if (ctx.path === "/oauth/callback/custom-provider") {
return "custom-provider"
}
// 기본 해석을 사용하려면 null 반환
return null
},
// 스키마 사용자 정의 (storeInDatabase가 true일 때)
schema: {
user: {
lastLoginMethod: "custom_field_name"
}
}
})
]
})cookieName: string
- 마지막 로그인 방법을 저장하는 데 사용되는 쿠키 이름
- 기본값:
"better-auth.last_used_login_method" - 참고: 이 쿠키는 UI 기능을 위한 클라이언트 측 JavaScript 액세스를 허용하기 위해
httpOnly: false입니다
maxAge: number
- 쿠키 만료 시간(초)
- 기본값:
2592000(30일)
storeInDatabase: boolean
- 마지막 로그인 방법을 데이터베이스에 저장할지 여부
- 기본값:
false - 활성화되면 사용자 테이블에
lastLoginMethod필드를 추가합니다
customResolveMethod: (ctx: GenericEndpointContext) => string | null
- 요청 컨텍스트에서 로그인 방법을 결정하는 사용자 정의 함수
- 기본 해석 로직을 사용하려면
null반환 - 사용자 정의 OAuth 제공자 또는 인증 플로우에 유용합니다
schema: object
storeInDatabase가 활성화되었을 때 데이터베이스 필드 이름 사용자 정의lastLoginMethod필드를 사용자 정의 열 이름에 매핑할 수 있습니다
클라이언트 옵션
import { createAuthClient } from "better-auth/client"
import { lastLoginMethodClient } from "better-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [
lastLoginMethodClient({
cookieName: "better-auth.last_used_login_method" // 기본값: "better-auth.last_used_login_method"
})
]
})cookieName: string
- 마지막 로그인 방법을 읽을 쿠키 이름
- 서버 측
cookieName구성과 일치해야 합니다 - 기본값:
"better-auth.last_used_login_method"
기본 메서드 해석
기본적으로 플러그인은 다음 인증 방법을 추적합니다:
- 이메일 인증:
"email" - OAuth 제공자: 제공자 ID (예:
"google","github","discord") - OAuth2 콜백: URL 경로의 제공자 ID
- 가입 방법: 로그인 방법과 동일하게 추적됩니다
플러그인은 다음 엔드포인트에서 방법을 자동으로 감지합니다:
/callback/:id- 제공자 ID를 가진 OAuth 콜백/oauth2/callback/:id- 제공자 ID를 가진 OAuth2 콜백/sign-in/email- 이메일 로그인/sign-up/email- 이메일 가입
교차 도메인 지원
플러그인은 Better Auth의 중앙 집중식 쿠키 시스템에서 쿠키 설정을 자동으로 상속받습니다. 이는 마지막 로그인 방법이 다음과 같은 경우에 지속되지 않는 문제를 해결합니다:
- 교차 서브도메인 설정:
auth.example.com→app.example.com - 교차 출처 설정:
api.company.com→app.different.com
Better Auth 구성에서 crossSubDomainCookies 또는 crossOriginCookies를 활성화하면 플러그인은 세션 쿠키와 동일한 도메인, 보안 및 sameSite 설정을 자동으로 사용하여 애플리케이션 전체에서 일관된 동작을 보장합니다.
고급 예제
사용자 정의 제공자 추적
사용자 정의 OAuth 제공자 또는 인증 방법이 있는 경우 customResolveMethod 옵션을 사용할 수 있습니다:
import { betterAuth } from "better-auth"
import { lastLoginMethod } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
lastLoginMethod({
customResolveMethod: (ctx) => {
// 사용자 정의 SAML 제공자 추적
if (ctx.path === "/saml/callback") {
return "saml"
}
// 매직 링크 인증 추적
if (ctx.path === "/magic-link/verify") {
return "magic-link"
}
// 전화 인증 추적
if (ctx.path === "/sign-in/phone") {
return "phone"
}
// 기본 로직을 사용하려면 null 반환
return null
}
})
]
})