samuelgozi / firebase-auth-lite

A lightweight firebase auth alternative for the browser
MIT License
119 stars 19 forks source link

Correct way to know if the library actually checked login state ? #82

Open Jonarod opened 1 year ago

Jonarod commented 1 year ago

In a Single Page Application context, routes must be protected before being flashed to end-user. To guard private routes, one then needs to first show a loading page while we WAIT for some isLoggedIn status to resolve, and then decide if the user can actually access to the page or not. So, something like this:

// using Svelte
{#if $isLoggedIn}
   <PrivateStuff />
{:else}
   <PublicStuff />
{/if}

So far so good. The thing is, when a user manually refreshes his browser (hitting F5 for example), this $isLoggedIn variable always starts as false UNTIL the Auth system is actually loaded. So we need to first be sure that the Auth system, in this case firebase-auth-lite has actually been given the time to load and look for any user. So, something like this:

// using Svelte
{#if $isLoadingAuthInfos}
   <Spinner>Wait while loading Auth Infos...</Spinner>
{:else}
    {#if $isLoggedIn}
       <PrivateStuff />
    {:else}
       <PublicStuff />
    {/if}
{/if}

Now, with this logic in mind, I quite struggle to implement it using firebase-auth-lite. In fact, I am not sure if I understand correctly the nature of the auth.listen() function, so please forgive me if I have incorrect assumptions, but this is what I have been trying so far:

auth.listen((user) => {
    if(user){
        $isLoggedIn.set(true)
    }
    $isLoadingAuthInfos.set(false)
})

In my mind, $isLoadingAuthInfos.set(true) should always be called, even if no user was found, right?!

As of version 0.8.9, the auth.listen(cb) callback is never fired if no user was found.

So what would be the correct way to know if firebase-auth-lite actually FINISHED to check for any logging? Hopefully I have not missed something but it looks to me that there is no way to be informed that firebase-auth-lite TRIED to look for some user and failed to found one.

Anyways, thank you for the library !

Jonarod commented 1 year ago

From the source code, I can see that the emit() function is the one responsible for actually triggering all callback function from auth.listen(cb). So for now, I am using this:

auth.listen((user) => {
    if(user){
        $isLoggedIn.set(true)
    }
    $isLoadingAuthInfos.set(false)
})

auth.emit()

Note the last auth.emit() I added. But it seems to me more like a "hacky" way of doing it. What do you think ?