auth-js icon indicating copy to clipboard operation
auth-js copied to clipboard

Improve client side docs for authentication

Open ghostdevv opened this issue 4 years ago • 0 comments

Improve documentation

Link

https://supabase.io/docs/guides/auth/auth-apple

and other external provider pages

Describe the problem

Currently when using external ouath2 providers, you can't use the following code:

const { user, session, error } = await supabase.auth.signIn({
  provider: 'discord'
})

The reason being that when you call this function the user is redirected to the provider to sign in, which exits the function call and when you are returned to the page, unless supabase runs on page load the authtoken in the url isn't caught.

My solution to this was to have a listener on supabase.auth.onAuthStateChange which runs on every page, and allows me to have a switch statement like the following to reflect the state change:

    supabase.auth.onAuthStateChange((event, session) => {
        const data = session?.user;
        switch (event) {
            case 'SIGNED_IN':
                $user = {
                    id: data.user_metadata.provider_id,
                    supabaseId: data.id,
                    username: data.user_metadata.full_name,
                    avatarUrl: data.user_metadata.avatar_url,
                    email: data.email,
                };
                break;
            case 'SIGNED_OUT':
                $user = null;
                break;
        }
    });

Describe the improvement

Either the js client should improve to open a popup for external providers allowing for you to actually await the return of the session, or the need for what I said above should be added in the documentation. I noticed quite a few people in the discord faced a similar problem and this took me quite a while to figure out a good solution. And even this solution isn't perfect, I had to update it yesterday as it just stopped working in particular cases. I had to add a callback page witch ran supabase.auth.getSessionFromUrl(); to update the authStateChange function.

ghostdevv avatar Oct 05 '21 09:10 ghostdevv