61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import type { createAuthClient } from "better-auth/react";
|
|
|
|
import { authStoragePrefix } from "@/lib/accounts";
|
|
import {
|
|
clearAuthStorage,
|
|
GUEST_AUTH_STORAGE_PREFIX,
|
|
prepareForAdditionalSignIn,
|
|
} from "@/lib/auth-storage";
|
|
|
|
type AuthClient = ReturnType<typeof createAuthClient>;
|
|
|
|
type PerformAuthResetInput = {
|
|
authClient: AuthClient;
|
|
clearActiveAccount: () => Promise<void>;
|
|
activeAccountId?: string | null;
|
|
refetchSession?: () => Promise<unknown>;
|
|
};
|
|
|
|
/** Sign out, wipe local auth storage, and return to guest mode for a clean sign-in screen. */
|
|
export async function performAuthReset({
|
|
authClient,
|
|
clearActiveAccount,
|
|
activeAccountId,
|
|
refetchSession,
|
|
}: PerformAuthResetInput): Promise<void> {
|
|
const accountPrefix = activeAccountId ? authStoragePrefix(activeAccountId) : null;
|
|
|
|
try {
|
|
await authClient.signOut();
|
|
} catch {
|
|
// Continue clearing local state even when the server session is already gone.
|
|
}
|
|
|
|
if (accountPrefix) {
|
|
await clearAuthStorage(accountPrefix);
|
|
}
|
|
await clearAuthStorage(GUEST_AUTH_STORAGE_PREFIX);
|
|
await clearActiveAccount();
|
|
await refetchSession?.();
|
|
}
|
|
|
|
/**
|
|
* When the auth stack is shown, discard stale SecureStore sessions so sign-in starts clean.
|
|
* Expired account sessions switch back to guest storage; orphaned guest copies are cleared.
|
|
*/
|
|
export async function prepareAuthScreenSession(
|
|
authClient: AuthClient,
|
|
activeAccountId: string | null,
|
|
clearActiveAccount: () => Promise<void>,
|
|
): Promise<void> {
|
|
const session = await authClient.getSession();
|
|
if (session.data?.user) return;
|
|
|
|
if (activeAccountId) {
|
|
await clearAuthStorage(authStoragePrefix(activeAccountId));
|
|
await clearActiveAccount();
|
|
}
|
|
|
|
await prepareForAdditionalSignIn();
|
|
}
|