diff --git a/demo/nextjs/app/(auth)/sign-in/loading.tsx b/demo/nextjs/app/(auth)/sign-in/loading.tsx deleted file mode 100644 index 1d7bdef0..00000000 --- a/demo/nextjs/app/(auth)/sign-in/loading.tsx +++ /dev/null @@ -1,16 +0,0 @@ -export default function Loading() { - return ( -
-
-
-
-
-
-
-
-
-
-
-
- ); -} diff --git a/demo/nextjs/components/sign-in.tsx b/demo/nextjs/components/sign-in.tsx index a96c6458..d7352cf5 100644 --- a/demo/nextjs/components/sign-in.tsx +++ b/demo/nextjs/components/sign-in.tsx @@ -14,7 +14,7 @@ import { Label } from "@/components/ui/label"; import { Checkbox } from "@/components/ui/checkbox"; import { useState, useTransition } from "react"; import { Loader2 } from "lucide-react"; -import { signIn } from "@/lib/auth-client"; +import { client, signIn } from "@/lib/auth-client"; import Link from "next/link"; import { cn } from "@/lib/utils"; import { useRouter, useSearchParams } from "next/navigation"; @@ -29,6 +29,12 @@ export default function SignIn() { const router = useRouter(); const params = useSearchParams(); + const LastUsedIndicator = () => ( + + Last Used + + ); + return ( @@ -83,7 +89,7 @@ export default function SignIn() {
diff --git a/demo/nextjs/lib/auth-client.ts b/demo/nextjs/lib/auth-client.ts index 48fe5af7..2c73ce34 100644 --- a/demo/nextjs/lib/auth-client.ts +++ b/demo/nextjs/lib/auth-client.ts @@ -9,6 +9,7 @@ import { oidcClient, genericOAuthClient, deviceAuthorizationClient, + lastLoginMethodClient, } from "better-auth/client/plugins"; import { toast } from "sonner"; import { stripeClient } from "@better-auth/stripe/client"; @@ -36,6 +37,7 @@ export const client = createAuthClient({ subscription: true, }), deviceAuthorizationClient(), + lastLoginMethodClient(), ], fetchOptions: { onError(e) { diff --git a/demo/nextjs/lib/auth.ts b/demo/nextjs/lib/auth.ts index 31deac9a..f740894b 100644 --- a/demo/nextjs/lib/auth.ts +++ b/demo/nextjs/lib/auth.ts @@ -10,6 +10,7 @@ import { openAPI, customSession, deviceAuthorization, + lastLoginMethod, } from "better-auth/plugins"; import { reactInvitationEmail } from "./email/invitation"; import { LibsqlDialect } from "@libsql/kysely-libsql"; @@ -223,6 +224,7 @@ export const auth = betterAuth({ expiresIn: "3min", interval: "5s", }), + lastLoginMethod(), ], trustedOrigins: ["exp://"], advanced: { diff --git a/docs/components/sidebar-content.tsx b/docs/components/sidebar-content.tsx index 843db280..1fc9144f 100644 --- a/docs/components/sidebar-content.tsx +++ b/docs/components/sidebar-content.tsx @@ -1704,6 +1704,24 @@ C0.7,239.6,62.1,0.5,62.2,0.4c0,0,54,13.8,119.9,30.8S302.1,62,302.2,62c0.2,0,0.2, href: "/docs/plugins/have-i-been-pwned", icon: () =>

';--

, }, + { + title: "Last Login Method", + href: "/docs/plugins/last-login-method", + icon: () => ( + + + + ), + isNew: true, + }, { title: "Multi Session", icon: () => ( diff --git a/docs/content/docs/plugins/last-login-method.mdx b/docs/content/docs/plugins/last-login-method.mdx new file mode 100644 index 00000000..49f2890d --- /dev/null +++ b/docs/content/docs/plugins/last-login-method.mdx @@ -0,0 +1,354 @@ +--- +title: Last Login Method +description: Track and display the last authentication method used by users +--- + +The last login method plugin tracks the most recent authentication method used by users (email, OAuth providers, etc.). This enables you to display helpful indicators on login pages, such as "Last signed in with Google" or prioritize certain login methods based on user preferences. + +## Installation + + + + ### Add the plugin to your auth config + + ```ts title="auth.ts" + import { betterAuth } from "better-auth" + import { lastLoginMethod } from "better-auth/plugins" // [!code highlight] + + export const auth = betterAuth({ + // ... other config options + plugins: [ + lastLoginMethod() // [!code highlight] + ] + }) + ``` + + + ### Add the client plugin to your auth client + + ```ts title="auth-client.ts" + import { createAuthClient } from "better-auth/client" + import { lastLoginMethodClient } from "better-auth/client/plugins" // [!code highlight] + + export const authClient = createAuthClient({ + plugins: [ + lastLoginMethodClient() // [!code highlight] + ] + }) + ``` + + + +## Usage + +Once installed, the plugin automatically tracks the last authentication method used by users. You can then retrieve and display this information in your application. + +### Getting the Last Used Method + +The client plugin provides several methods to work with the last login method: + +```ts title="app.tsx" +import { authClient } from "@/lib/auth-client" + +// Get the last used login method +const lastMethod = authClient.getLastUsedLoginMethod() +console.log(lastMethod) // "google", "email", "github", etc. + +// Check if a specific method was last used +const wasGoogle = authClient.isLastUsedLoginMethod("google") + +// Clear the stored method +authClient.clearLastUsedLoginMethod() +``` + +### UI Integration Example + +Here's how to use the plugin to enhance your login page: + +```tsx title="sign-in.tsx" +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 ( +
+

Sign In

+ + {/* Email sign in */} +
+ +
+ + {/* OAuth providers */} +
+ +
+ +
+ +
+
+ ) +} +``` + +## Database Persistence + +By default, the last login method is stored only in cookies. For more persistent tracking and analytics, you can enable database storage. + + + + ### Enable database storage + + Set `storeInDatabase` to `true` in your plugin configuration: + + ```ts title="auth.ts" + import { betterAuth } from "better-auth" + import { lastLoginMethod } from "better-auth/plugins" + + export const auth = betterAuth({ + plugins: [ + lastLoginMethod({ + storeInDatabase: true // [!code highlight] + }) + ] + }) + ``` + + + ### Run database migration + + The plugin will automatically add a `lastLoginMethod` field to your user table. Run the migration to apply the changes: + + + + ```bash + npx @better-auth/cli migrate + ``` + + + ```bash + npx @better-auth/cli generate + ``` + + + + + ### Access database field + + When database storage is enabled, the `lastLoginMethod` field becomes available in user objects: + + ```ts title="user-profile.tsx" + import { auth } from "@/lib/auth" + + // Server-side access + const session = await auth.api.getSession({ headers }) + console.log(session?.user.lastLoginMethod) // "google", "email", etc. + + // Client-side access via session + const { data: session } = authClient.useSession() + console.log(session?.user.lastLoginMethod) + ``` + + + +### Database Schema + +When `storeInDatabase` is enabled, the plugin adds the following field to the `user` table: + +Table: `user` + + + +### Custom Schema Configuration + +You can customize the database field name: + +```ts title="auth.ts" +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" // Custom field name + } + } + }) + ] +}) +``` + +## Configuration Options + +The last login method plugin accepts the following options: + +### Server Options + +```ts title="auth.ts" +import { betterAuth } from "better-auth" +import { lastLoginMethod } from "better-auth/plugins" + +export const auth = betterAuth({ + plugins: [ + lastLoginMethod({ + // Cookie configuration + cookieName: "last_used_login_method", // Default: "last_used_login_method" + maxAge: 60 * 60 * 24 * 30, // Default: 30 days in seconds + + // Database persistence + storeInDatabase: false, // Default: false + + // Custom method resolution + customResolveMethod: (ctx) => { + // Custom logic to determine the login method + if (ctx.path === "/oauth/callback/custom-provider") { + return "custom-provider" + } + // Return null to use default resolution + return null + }, + + // Schema customization (when storeInDatabase is true) + schema: { + user: { + lastLoginMethod: "custom_field_name" + } + } + }) + ] +}) +``` + +**cookieName**: `string` +- The name of the cookie used to store the last login method +- Default: `"last_used_login_method"` + +**maxAge**: `number` +- Cookie expiration time in seconds +- Default: `2592000` (30 days) + +**storeInDatabase**: `boolean` +- Whether to store the last login method in the database +- Default: `false` +- When enabled, adds a `lastLoginMethod` field to the user table + +**customResolveMethod**: `(ctx: GenericEndpointContext) => string | null` +- Custom function to determine the login method from the request context +- Return `null` to use the default resolution logic +- Useful for custom OAuth providers or authentication flows + +**schema**: `object` +- Customize database field names when `storeInDatabase` is enabled +- Allows mapping the `lastLoginMethod` field to a custom column name + +### Client Options + +```ts title="auth-client.ts" +import { createAuthClient } from "better-auth/client" +import { lastLoginMethodClient } from "better-auth/client/plugins" + +export const authClient = createAuthClient({ + plugins: [ + lastLoginMethodClient({ + cookieName: "last_used_login_method" // Default: "last_used_login_method" + }) + ] +}) +``` + +**cookieName**: `string` +- The name of the cookie to read the last login method from +- Must match the server-side `cookieName` configuration +- Default: `"last_used_login_method"` + +### Default Method Resolution + +By default, the plugin tracks these authentication methods: + +- **Email authentication**: `"email"` +- **OAuth providers**: Provider ID (e.g., `"google"`, `"github"`, `"discord"`) +- **OAuth2 callbacks**: Provider ID from URL path +- **Sign up methods**: Tracked the same as sign in methods + +The plugin automatically detects the method from these endpoints: +- `/callback/:id` - OAuth callback with provider ID +- `/oauth2/callback/:id` - OAuth2 callback with provider ID +- `/sign-in/email` - Email sign in +- `/sign-up/email` - Email sign up + +## Advanced Examples + +### Custom Provider Tracking + +If you have custom OAuth providers or authentication methods, you can use the `customResolveMethod` option: + +```ts title="auth.ts" +import { betterAuth } from "better-auth" +import { lastLoginMethod } from "better-auth/plugins" + +export const auth = betterAuth({ + plugins: [ + lastLoginMethod({ + customResolveMethod: (ctx) => { + // Track custom SAML provider + if (ctx.path === "/saml/callback") { + return "saml" + } + + // Track magic link authentication + if (ctx.path === "/verify-magic-link") { + return "magic-link" + } + + // Track phone authentication + if (ctx.path === "/sign-in/phone") { + return "phone" + } + + // Return null to use default logic + return null + } + }) + ] +}) +``` + + diff --git a/packages/better-auth/src/client/plugins/index.ts b/packages/better-auth/src/client/plugins/index.ts index a4a4f212..9c625be6 100644 --- a/packages/better-auth/src/client/plugins/index.ts +++ b/packages/better-auth/src/client/plugins/index.ts @@ -21,3 +21,4 @@ export * from "../../plugins/one-time-token/client"; export * from "../../plugins/siwe/client"; export * from "../../plugins/device-authorization/client"; export type * from "@simplewebauthn/server"; +export * from "../../plugins/last-login-method/client"; diff --git a/packages/better-auth/src/plugins/index.ts b/packages/better-auth/src/plugins/index.ts index a580b140..a8777b2b 100644 --- a/packages/better-auth/src/plugins/index.ts +++ b/packages/better-auth/src/plugins/index.ts @@ -25,3 +25,4 @@ export * from "./one-time-token"; export * from "./mcp"; export * from "./siwe"; export * from "./device-authorization"; +export * from "./last-login-method"; diff --git a/packages/better-auth/src/plugins/last-login-method/client.ts b/packages/better-auth/src/plugins/last-login-method/client.ts new file mode 100644 index 00000000..89e17fe4 --- /dev/null +++ b/packages/better-auth/src/plugins/last-login-method/client.ts @@ -0,0 +1,66 @@ +import type { BetterAuthClientPlugin } from "../../types"; + +/** + * Configuration for the client-side last login method plugin + */ +export interface LastLoginMethodClientConfig { + /** + * Name of the cookie to read the last login method from + * @default "last_used_login_method" + */ + cookieName?: string; +} + +function getCookieValue(name: string): string | null { + if (typeof document === "undefined") { + return null; + } + + const cookie = document.cookie + .split("; ") + .find((row) => row.startsWith(`${name}=`)); + + return cookie ? cookie.split("=")[1] : null; +} + +/** + * Client-side plugin to retrieve the last used login method + */ +export const lastLoginMethodClient = ( + config: LastLoginMethodClientConfig = {}, +) => { + const cookieName = config.cookieName || "last_used_login_method"; + + return { + id: "last-login-method-client", + getActions() { + return { + /** + * Get the last used login method from cookies + * @returns The last used login method or null if not found + */ + getLastUsedLoginMethod: (): string | null => { + return getCookieValue(cookieName); + }, + /** + * Clear the last used login method cookie + * This sets the cookie with an expiration date in the past + */ + clearLastUsedLoginMethod: (): void => { + if (typeof document !== "undefined") { + document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`; + } + }, + /** + * Check if a specific login method was the last used + * @param method The method to check + * @returns True if the method was the last used, false otherwise + */ + isLastUsedLoginMethod: (method: string): boolean => { + const lastMethod = getCookieValue(cookieName); + return lastMethod === method; + }, + }; + }, + } satisfies BetterAuthClientPlugin; +}; diff --git a/packages/better-auth/src/plugins/last-login-method/index.ts b/packages/better-auth/src/plugins/last-login-method/index.ts new file mode 100644 index 00000000..bb9253d1 --- /dev/null +++ b/packages/better-auth/src/plugins/last-login-method/index.ts @@ -0,0 +1,139 @@ +import { createAuthMiddleware, type BetterAuthPlugin } from ".."; +import type { GenericEndpointContext } from "../../types"; + +/** + * Configuration for tracking different authentication methods + */ +export interface LastLoginMethodOptions { + /** + * Name of the cookie to store the last login method + * @default "last_used_login_method" + */ + cookieName?: string; + /** + * Cookie expiration time in seconds + * @default 2592000 (30 days) + */ + maxAge?: number; + /** + * Custom method to resolve the last login method + * @param ctx - The context from the hook + * @returns The last login method + */ + customResolveMethod?: (ctx: GenericEndpointContext) => string | null; + /** + * Store the last login method in the database. This will create a new field in the user table. + * @default false + */ + storeInDatabase?: boolean; + /** + * Custom schema for the plugin + * @default undefined + */ + schema?: { + user?: { + lastLoginMethod?: string; + }; + }; +} + +/** + * Plugin to track the last used login method + */ +export const lastLoginMethod = ( + userConfig?: O, +) => { + const paths = [ + "/callback/:id", + "/oauth2/callback/:id", + "/sign-in/email", + "/sign-up/email", + ]; + const config = { + cookieName: "last_used_login_method", + maxAge: 60 * 60 * 24 * 30, + customResolveMethod: (ctx) => { + if (paths.includes(ctx.path)) { + return ctx.params?.id ? ctx.params.id : ctx.path.split("/").pop(); + } + return null; + }, + ...userConfig, + } satisfies LastLoginMethodOptions; + + return { + id: "last-login-method", + init(ctx) { + return { + options: { + databaseHooks: { + user: { + create: { + async before(user, context) { + if (!config.storeInDatabase) return; + if (!context) return; + const lastUsedLoginMethod = + config.customResolveMethod(context); + if (lastUsedLoginMethod) { + return { + data: { + ...user, + lastLoginMethod: lastUsedLoginMethod, + }, + }; + } + }, + }, + }, + }, + }, + }; + }, + hooks: { + after: [ + { + matcher() { + return true; + }, + handler: createAuthMiddleware(async (ctx) => { + const lastUsedLoginMethod = config.customResolveMethod(ctx); + lastUsedLoginMethod && + ctx.setCookie(config.cookieName, lastUsedLoginMethod, { + maxAge: config.maxAge, + secure: false, + httpOnly: false, + path: "/", + }); + }), + }, + ], + }, + schema: (config.storeInDatabase + ? { + user: { + fields: { + lastLoginMethod: { + type: "string", + input: false, + required: false, + fieldName: + config.schema?.user?.lastLoginMethod || "lastLoginMethod", + }, + }, + }, + } + : undefined) as O["storeInDatabase"] extends true + ? { + user: { + fields: { + lastLoginMethod: { + type: "string"; + required: false; + input: false; + }; + }; + }; + } + : undefined, + } satisfies BetterAuthPlugin; +}; diff --git a/packages/better-auth/src/plugins/last-login-method/last-login-method.test.ts b/packages/better-auth/src/plugins/last-login-method/last-login-method.test.ts new file mode 100644 index 00000000..b05ea832 --- /dev/null +++ b/packages/better-auth/src/plugins/last-login-method/last-login-method.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import { getTestInstance } from "../../test-utils/test-instance"; +import { lastLoginMethod } from "."; +import { lastLoginMethodClient } from "./client"; +import { parseCookies } from "../../cookies"; + +describe("lastLoginMethod", async () => { + const { client, cookieSetter, testUser } = await getTestInstance( + { + plugins: [lastLoginMethod()], + }, + { + clientOptions: { + plugins: [lastLoginMethodClient()], + }, + }, + ); + + it("should set the last login method cookie", async () => { + const headers = new Headers(); + await client.signIn.email( + { + email: testUser.email, + password: testUser.password, + }, + { + onSuccess(context) { + cookieSetter(headers)(context); + }, + }, + ); + const cookies = parseCookies(headers.get("cookie") || ""); + expect(cookies.get("last_used_login_method")).toBe("email"); + }); + + it("should set the last login method in the database", async () => { + const { client, auth } = await getTestInstance({ + plugins: [lastLoginMethod({ storeInDatabase: true })], + }); + const data = await client.signIn.email( + { + email: testUser.email, + password: testUser.password, + }, + { throw: true }, + ); + const session = await auth.api.getSession({ + headers: new Headers({ + authorization: `Bearer ${data.token}`, + }), + }); + expect(session?.user.lastLoginMethod).toBe("email"); + }); +});