during my login process I'm only using supabase.au...
# help
i
during my login process I'm only using supabase.auth.setAuth(token); from a jwt token endpoint response but this isn't firing off an supabase.auth.onAuthStateChange event How can I refactor this to get it to work properly?
n
Hello @Invader! This thread has been automatically created from your message in #843999948717555735 a ``few seconds ago``. Pinging @User so that they see this as well! Want to unsubscribe from this thread? Right-click the thread in Discord (or use the ... menu) and select Leave Thread to unsubscribe from future updates. Want to change the title? Use the
/title
command! We have solved your problem? Click the button below to archive it.
i
@User ❤️
How I'm basically getting a JWT from my route
Copy code
jsx
      response = await fetch("/api/auth/wallet", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          walletAddr,
          nonce,
          signature,
        }),
      });

      const { user, token } = await response.json();
      supabase.auth.setAuth(token);
And my API route itself
Copy code
jsx

const walletApi = async (req: any, res: any) => {
    try {
        ...
        // variables stuff above
        let { data: user, error }: any = await supabase
            .from("users")
            .select("*")
            .eq('walletAddr', signerAddr)
            .eq('nonce', nonce)
        
        const token = jwt.sign(
            {
                aud: "authenticated",
                exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7),
                sub: user.id,
                user_metadata: {
                    id: user.id,
                },
                role: "authenticated"
            },
            jwtSecret as string
        );

        res.status(200).json({ user, token })
    } catch (err: any) {
        res.status(400).json({ error: err.message });
    }
}

export default walletApi
g
All setAuth does is set the token for future requests from the supabase client to the database.
n
Invader (2022-04-12)
i
@garyaustin yeah - but the thing is
I'm using a custom authentication method that isn't really email/password
it's web3 wallet signing but I still have user details I could fetch
but I'm trying to check for the user's existance in UseEffect to basically secure routes
Copy code
jsx
 useEffect(() => {
    supabase.auth.onAuthStateChange(async (event, session) => {
      console.log("Running an auth state change");
      let newUser = supabase.auth.user();
      if (newUser) {
        await fetch("/api/auth/set", {
          method: "POST",
          headers: new Headers({ "Content-Type": "application/json" }),
          credentials: "same-origin",
          body: JSON.stringify({ event, session }),
        });
      }
      setUser(supabase.auth.user() || undefined);
    });
  });
basically
/api/auth/set
is what sets the cookie after
Copy code
ts
import { NextApiRequest, NextApiResponse } from "next";
import supabase from "lib/pSupabase";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  await supabase.auth.api.setAuthCookie(req, res);
}
Should I just be setting the auth cookie in the same place I originally get the token from back as a response?
I'm not really doing real authentication with passwords - their signing a crypto message to verify they are that user through the token
Copy code
if (data.length > 0) {
    console.log("Updating nonce");
    let data = await supabase
      .from("users")
      .update({ nonce })
      .match({ walletAddr });
    console.log(data);
  } else if (data.length === 0) {
    console.log("Inserting nonce");
    let data = await supabase.from("users").insert({ walletAddr, nonce });
  }

  res.status(200).json({ nonce });
I'm even manually inserting them into the DB - do I need to change this to a signup/ scheme to work?
g
I'm not using React anymore, or server side code. So not much help, Many people are turning to this https://github.com/supabase-community/supabase-auth-helpers for server side stuff. Looking thru that may help if no one else comes along shortly here. I'm a bit confused what your token consists of as it is mainly used by the database for RLS enforcement with users that have gone thru auth.
i
yeah basically the token is useful only for making calls matching that users cryptographic address on the database
but theres no real password - but the users are given an identifier in the database
ill check it out

https://www.youtube.com/watch?v=tVyQZ0CiMWI

I followed this tutorial
g
So you have the auth.users table populated?
i
yep
g
That is your own table. Not auth.users() which would be used by gotrue
i
ohh
yeah I followed the guy in the video
is gotrue compatible with custom provider methods?
cause if not I think thats why he did it
g
People have come up with methods to for sure, which is possible on serverside. Just not sure auth user calls are going to do much in your code if gotrue was not involved in setting up users.
i
so in this case if I'm not using
auth.users
and my own custom tables - theres no point in using any of the supabase auth functions right?
like setauthcookie etc
found this
nobody reviewed his PR it seems
and theres no way for me to build my own version of gotrue with his modifications I gues
g
That did not make this round for some reason. He works closely with Supabase though.
i
is he around here?
I would love to ask him about it
g
check in the gotrue section