Stabilize mobile auth session handling
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
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();
|
||||
}
|
||||
Reference in New Issue
Block a user