()
| 18 | * Stores the user's last email, auth method, and optional org ID for faster returning user experience. |
| 19 | */ |
| 20 | export function useSignInHint(): { |
| 21 | hint: SignInHint | null; |
| 22 | isLoaded: boolean; |
| 23 | saveHint: (hint: Partial<SignInHint>) => void; |
| 24 | clearHint: () => void; |
| 25 | } { |
| 26 | const [hint, setHint] = useState<SignInHint | null>(null); |
| 27 | const [isLoaded, setIsLoaded] = useState(false); |
| 28 | |
| 29 | useEffect(() => { |
| 30 | const storedHint = safeLocalStorage.getItem(LOCAL_STORAGE_KEY); |
| 31 | if (storedHint) { |
| 32 | try { |
| 33 | const parsed = JSON.parse(storedHint) as SignInHint; |
| 34 | |
| 35 | // Validate the stored hint |
| 36 | // Email is optional (partial hint), but if present must be valid |
| 37 | const emailValid = |
| 38 | !parsed.lastEmail || emailSchema.safeParse({ email: parsed.lastEmail }).success; |
| 39 | const hasAuthMethod = |
| 40 | parsed.lastAuthMethod && VALID_AUTH_METHODS.includes(parsed.lastAuthMethod); |
| 41 | |
| 42 | if (emailValid && hasAuthMethod && parsed.lastLogin) { |
| 43 | setHint(parsed); |
| 44 | } else { |
| 45 | // Invalid hint, remove it |
| 46 | safeLocalStorage.removeItem(LOCAL_STORAGE_KEY); |
| 47 | } |
| 48 | } catch { |
| 49 | // Invalid JSON, remove it |
| 50 | safeLocalStorage.removeItem(LOCAL_STORAGE_KEY); |
| 51 | } |
| 52 | } |
| 53 | setIsLoaded(true); |
| 54 | }, []); |
| 55 | |
| 56 | const saveHint = useCallback((partialHint: Partial<SignInHint>) => { |
| 57 | // Validate email if provided |
| 58 | if (partialHint.lastEmail) { |
| 59 | const emailValid = emailSchema.safeParse({ email: partialHint.lastEmail }).success; |
| 60 | if (!emailValid) { |
| 61 | console.warn('[useSignInHint] Attempted to save invalid email, skipping'); |
| 62 | return; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // Get existing hint from localStorage to merge with |
| 67 | const storedHint = safeLocalStorage.getItem(LOCAL_STORAGE_KEY); |
| 68 | let existingHint: Partial<SignInHint> = {}; |
| 69 | |
| 70 | if (storedHint) { |
| 71 | try { |
| 72 | existingHint = JSON.parse(storedHint); |
| 73 | } catch { |
| 74 | // Invalid JSON, start fresh |
| 75 | } |
| 76 | } |
| 77 |
no test coverage detected