ashleyconnor / sveltekit-supabase-demo

Demo application using SvelteKit, Supabase and Cloudflare Workers
39 stars 4 forks source link

Redirect check if use is not logged in #3

Open silentworks opened 3 years ago

silentworks commented 3 years ago

There is a issue in this area and it seems more of an issue with how Svelte executes its code than anything else. If you should redirect directly back to the /todos page after logging in, you will be sent back to the /login screen because the session wouldn't have been set by then. This is a real hindrance to using server-side validation in Svelte Kit projects.

How to reproduce

Modify your login.svelte to pass the redirect url to redirectTo of the signIn function. Updated loginUser function below

async function loginUser() {
    loading = true;
    let redirect = $page.query.get('redirect') || '/';
    let { error } = await supabase.auth.signIn(
      {
        email,
        password
      },
      { redirectTo: `http://${$page.host}${redirect}` }
    );

    if (error) {
      loading = false;
      alert(error);
      return;
    }

    if (!password) {
      redirect = `${redirect}?magic_link=true`;
    }
    goto(redirect);
  }

Now visit /todos while not logged in and you should be redirected to the login page with a redirect query string, now when you log in with your credentials you will still be redirected back to the login page because the session is not set at the time the check happens in the load function.

AgarwalPragy commented 3 years ago

Is this any workaround for this? I'm trying to redirect the user away from the user-dashboard if they're not logged in, and the session isn't set in the load function :(

keybits commented 3 years ago

I haven't checked in detail, but does the approach presented in this video achieve what you're looking for? (Source for the code in the video)

mattiasinokuchi commented 2 years ago

Maybe replace() can be used as follows?