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

Auth returning 406 Status

Open TheRealToxicDev opened this issue 2 years ago • 4 comments

Bug report

Describe the bug

Hello im not sure if i should open this issue here or on the actual Supabase Repo but When i attempt to authorize on my website using it returns the following errors:

New User
  • Failed to load resource: the server responded with a status of 406 ()
Existing User
  • GET https://zmsbaentcljnuhzjasbw.supabase.co/rest/v1/profiles?select=id%2Cusername%2Cavatar_url%2Cdisplay_name%2Cbio&id=eq.cf44bcb5-e511-4471-9de3-58a36408cf75 406 This error also return some additional info i will attach a screenshot below.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Click on 'Login'
  2. Choose a provider
  3. Wait for loading
  4. See error

Expected behavior

Upon login it should fetch info from the Supabase database such as username etc but for some reason it returns a 406 (For new users) or the error shown in the screenshot if the user already exists (Not their first time authorizing)

Screenshots

New User: Screenshot Existing User: Screenshot

System information

  • OS: Windows
  • Browser: chrome
  • Version of supabase-js: ^1.28.5
  • Version of Node.js: ^16.13.0

Additional context

I do have the Database configured and all the tables added but im thinking maybe i chose the incorrect column type is that possible to be the cause in this case? otherwise im not sure what the issue is here. Please let me know whatever info you need id be happy to provide it

This error is preventing the auth from being completed so any assistance in resolving it is greatly appreciated 😅

TheRealToxicDev avatar Apr 15 '22 05:04 TheRealToxicDev

Can you see if your issue is related to this? https://github.com/supabase/supabase/issues/2395

Did this issue pop up recently or has it been occurring from the start?

Additionally, it would be helpful if you could provide a minimal public GitHub repo that lets us reproduce the issue, otherwise it's a bit difficult to see what the problem is from the problem description.

soedirgo avatar Apr 18 '22 06:04 soedirgo

Can you see if your issue is related to this? supabase/supabase#2395

Did this issue pop up recently or has it been occurring from the start?

Additionally, it would be helpful if you could provide a minimal public GitHub repo that lets us reproduce the issue, otherwise it's a bit difficult to see what the problem is from the problem description.

Hey there that actually helped. login works now but i still get a error in the following

import { definitions } from "@/utils/generated";
import logger from "@/utils/logger";
import { supabase } from "@/utils/supabaseClient";
import { ErrorCode } from "@/utils/types";
import { AuthChangeEvent, Session } from "@supabase/gotrue-js";
import useLocalStorage from "hooks/useLocalStorage";
import { useRouter } from "next/dist/client/router";
import { createContext, useContext, useEffect, useState } from "react";

const AuthContext = createContext<{
  user: definitions["profiles"] | null;
  loading: boolean;
  error: ErrorCode | null;
  logout?: () => Promise<void>;
  setUser?: (value: definitions["profiles"]) => void;
}>({
  user: null,
  logout: undefined,
  loading: true,
  error: null,
});

const setCookies = async (event: AuthChangeEvent, session: Session | null) => {
  await fetch("/api/auth", {
    method: "POST",
    headers: new Headers({ "Content-Type": "application/json" }),
    credentials: "same-origin",
    body: JSON.stringify({ event, session }),
  });
};

const AuthProvider: React.FC<{}> = ({ children }) => {
  const [session, setSession] = useState<Session | null>(null);
  const [user, setUser] = useLocalStorage<definitions["profiles"] | null>(
    "currentUser",
    null
  );

  const removeUser = () => setUser(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<ErrorCode | null>(null);
  const router = useRouter();

  useEffect(() => {
    const session = supabase.auth.session();
    if (!session) {
      // no session found in localhost
      // clear data
      removeUser();
      setLoading(false);
    }
    setSession(session);

    const { data: authListener } = supabase.auth.onAuthStateChange(
      async (event, session) => {
        await setCookies(event, session);
        setSession(session);
      }
    );

    return () => {
      if (authListener) {
        authListener.unsubscribe();
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // user set
  useEffect(() => {
    const getProfile = async () => {
      try {
        setLoading(true);
        const currentUser = supabase.auth.user();
        if (currentUser) {
          await setCookies("SIGNED_IN", session);

          const { data, error, status } = await supabase
            .from<definitions["profiles"]>("profiles")
            .select(`id, username, avatar_url, display_name, bio`)
            .eq("id", currentUser.id);

          if (error && status !== 406) {
            throw error;
          }

          if (data) {
            logger.debug("Settings user: ", data);
            setError(null);
            setUser(data);
          }
        }
      } catch (error) {
        logger.debug(error);
      } finally {
        setLoading(false);
      }
    };

    if (session) {
      getProfile();
    }

    // eslint-disable-next-line
  }, [session]);

  useEffect(() => {
    if (user && user.username === null) {
      setError("NoUsername");
      if (router.route !== "/onboarding") {
        router.push("/onboarding");
      }
    }

    // eslint-disable-next-line
  }, [user]);

  const handleLogout = async () => {
    setLoading(true);
    // remove preview tokens
    fetch("/api/clearPreviewData");
    await supabase.auth.signOut();
    await router.push("/");
    removeUser();
    setError(null);
  };
  return (
    <AuthContext.Provider
      value={{ user, setUser, logout: handleLogout, loading, error }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  return useContext(AuthContext);
};

export default AuthProvider;

for the

if (data) {
            logger.debug("Settings user: ", data);
            setError(null);
            setUser(data);
          }
        }

on setUser(data) says that "id" is missing

TheRealToxicDev avatar Apr 18 '22 09:04 TheRealToxicDev

sorry in advance i am still kinda new to Supabase

TheRealToxicDev avatar Apr 18 '22 09:04 TheRealToxicDev

if i change it to setUser(currentUser) it seems to work but when attempting to register a new user it says profile doesnt exist

https://zmsbaentcljnuhzjasbw.supabase.co/rest/v1/profiles?id=eq.271d8cf5-afab-4514-824b-bc3162526c83 - returns a 404

TheRealToxicDev avatar Apr 18 '22 10:04 TheRealToxicDev

Hey @TheRealToxicDev, doesn't setUser just set the state? this seems like a problem with your useLocalStorage hook

It might be worth posting your question in the github discussions as well since this doesn't seem like an error with the client library. Will be closing this issue for now.

kangmingtay avatar Sep 30 '22 05:09 kangmingtay