https://supabase.com/ logo
#help
Title
# help
o

omar

06/15/2022, 10:01 AM
hey all, any supa auth experts?
n

Needle

06/15/2022, 10:01 AM
Hello @omar! This thread has been automatically created from your message in #843999948717555735 a few seconds ago. We have already mentioned the @User so that they can see your message and help you as soon as possible! 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.
o

Olyno

06/15/2022, 10:08 AM
Hi What's the issue you have? @omar
o

omar

06/15/2022, 10:09 AM
when I try signing in or up i get this error
im not sure hw to debug it
im following along with John's egghead course
using react context to share global state
here's my context code
Copy code
js
import { createContext, useState, useEffect, useContext } from 'react'
import { supabase } from '../utils/supabaseClient'
import { useRouter } from 'next/router'
import axios from 'axios'

const Context = createContext()

const Provider = ({ children }) => {
  let [isLoading, setIsLoading] = useState(true)
  let [session, setSession] = useState(null)
  const [user, setUser] = useState(supabase.auth.user())
  const router = useRouter()

  useEffect(() => {
    const getUserProfile = async () => {
      const sessionUser = supabase.auth.user()

      if(sessionUser) {
        const {data: profile} = await supabase
        .from('profile')
        .select('*')
        .eq('id', sessionUser.id)
        .single()

        setUser({
          ...sessionUser,
          ...profile,
        })

        setIsLoading(false)
      }
    }

    getUserProfile()

    supabase.auth.onAuthStateChange(() => {
      getUserProfile()
    })
  }, [])

  useEffect(() => {
    axios.post('/api/set-supabase-cookie', {
      event: user ? 'SIGNED_IN' : 'SIGNED_OUT',
      session: supabase.auth.session(),
    })
  }, [user])

  const login = async (email) => {
    await supabase.auth.signIn({email})
  }

  const logout = async () => {
    await supabase.auth.signOut()
    setUser(null)
    router.push('/')
  }

  const exposed = {
    user,
    login,
    logout,
    isLoading
  }

  return (
    <Context.Provider value={exposed}>
      {children}
    </Context.Provider>
  )
}

export const useUser = () => useContext(Context)

export default Provider
only magic link and sign up
here's the login and sign up code
Auth component
Copy code
js
import { supabase } from '../../utils/supabaseClient'
import AuthTabs from './auth-tabs'

export default function Auth({}) {
  async function handleOAuthLogin(email) {
    let { error } = await supabase.auth.signIn({ email })
    if (error) console.error('Error: ', error.message)
  }

  return (
    <div>
      <AuthTabs />
    </div>
  )
}
Auth directs to sign in
Copy code
js
import { useState } from 'react'
import { supabase } from '../../utils/supabaseClient'

export default function SignIn({}) {
  const [email, setEmail] = useState('')

  const handleSignIn = async (email) => {
    try {
      const { error, user } = await supabase.auth.signIn({ email })
      if (!error && !user) alert('Check your email for the login link!')
      if (error) console.error('Error returned:', error.message)
    } catch (error) {
      console.error('Error thrown:', error.message)
      alert(error.error_description || error)
    }
  }

  return (
    <div>
      <div>
        <div>
          <label>Email</label>
          <input
            type="text"
            name='email'
            placeholder="Your email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>

        <div>
          <a
            onClick={(e) => {
              e.preventDefault()
              handleSignIn(email)
            }}
            href={'/channels'}
            className="border border-navy bg-navy py-2 px-4 text-center font-bold text-snow"
          >
            Sign In
          </a>
        </div>
      </div>
    </div>
  )
}
or sign up component
Copy code
js
import { useState } from 'react'
import { supabase } from '../../utils/supabaseClient'

export default function SignUp({}) {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  const handleSignUp = async (email, password) => {
    try {
      const { error, user } = await supabase.auth.signUp(
        {
          email,
          password,
        }
      )
      if (!error) alert('Check your email for the login link!')
      if (error) {
        console.error(
          `Error Status: ${error.status}, Message: ${error.message}`
        )
        alert(`Error Message: ${error.message}`)
      }
    } catch (error) {
      console.error('Error thrown:', error.message)
      alert(error.error_description || error)
    }
  }

  return (
    <div>
      <div>
        <div>
          <label>Email</label>
          <input
            type="text"
            placeholder="Your email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <div>
          <label>Password</label>
          <input
            type="password"
            placeholder="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>

        <div>
          <a
            onClick={(e) => {
              e.preventDefault()
              handleSignUp(email, password)
            }}
            href={'/channels'}
            className=""
          >
            Sign up
          </a>
        </div>
      </div>
    </div>
  )
}
i have a supabase function to create a new profile triggering with new auth user
sorry for the long winded messages
any ideas?
g

garyaustin

06/15/2022, 1:59 PM
Not reading all your code, but what is your error, did I miss that? Also a common point of error is when first adding a trigger function on auth.users.
o

omar

06/15/2022, 2:11 PM
The title of the thread is the error
g

garyaustin

06/15/2022, 2:14 PM
Are there errors in the database/postgres logs? Is there an error code? It is likely going to be your trigger function.
o

omar

06/15/2022, 3:23 PM
here is the exact error with error code
POST https://provagxtnmrfxtldadcr.supabase.co/auth/v1/otp 500
Error returned: Database error saving new user
API Logs
g

garyaustin

06/15/2022, 3:28 PM
So a 500 error. This is likely your trigger function. Can you show it? Postgres logs
No your trigger function itself.
And there is likely an error in the Postgres logs versus the API logs.
o

omar

06/15/2022, 3:32 PM
How do you mean?
g

garyaustin

06/15/2022, 3:35 PM
Two things. First check your postgres (not API) logs right after you signup a user, there should be an actual database error. Second show your function code for create_new_profile_for_users. May need to see your profile table columns after that.
o

omar

06/15/2022, 3:36 PM
these are postgres logs
g

garyaustin

06/15/2022, 3:43 PM
The postgres log is the tab below the API logs. Did you select "security definer" for behavior when you created the function? Did you use the dashboard function UI or SQL editor to create it? Is your profile table id column type uuid and your email column type text?
o

omar

06/15/2022, 3:44 PM
Copy code
Event message
expected SASL response, got message type 0
Severity

FATAL

Postgres Username

postgres

Session ID

62a9fa43.eed2

Metadata
{
  "file": "/var/log/postgresql/postgresql.csv",
  "host": "db-provagxtnmrfxtldadcr",
  "parsed": [
    {
      "application_name": null,
      "backend_type": "client backend",
      "command_tag": "authentication",
      "connection_from": "185.7.214.104:47444",
      "context": null,
      "database_name": "bbbbbbb",
      "detail": null,
      "error_severity": "FATAL",
      "hint": null,
      "internal_query": null,
      "internal_query_pos": null,
      "leader_pid": null,
      "location": null,
      "process_id": 61138,
      "query": null,
      "query_id": 0,
      "query_pos": null,
      "session_id": "62a9fa43.eed2",
      "session_line_num": 2,
      "session_start_time": "2022-06-15 15:26:59 UTC",
      "sql_state_code": "08P01",
      "timestamp": "2022-06-15 15:26:59.246 UTC",
      "transaction_id": 0,
      "user_name": "postgres",
      "virtual_transaction_id": "11/36748"
    }
  ],
  "parsed_from": null,
  "project": "provagxtnmrfxtldadcr",
  "source_type": "file"
}
I did select
security definer
dashboard UI
g

garyaustin

06/15/2022, 3:45 PM
And trigger return type?
o

omar

06/15/2022, 3:46 PM
uuid
return type trigger
g

garyaustin

06/15/2022, 3:48 PM
Try deleting the trigger (not the function) and see if you can insert a user.
o

omar

06/15/2022, 3:48 PM
ok one sec
ok that worked
able to sign up
able to sign in
getting this error tho
Failed to load resource: the server responded with a status of 406 ()
g

garyaustin

06/15/2022, 3:54 PM
That could be RLS or something else, or something needing your profile table row, probably with a .single() in the call. But first thing is your trigger function has an issue somewhere.
This is my function:
Copy code
begin
  insert into public.users (uid, email)
  values (new.id, new.email);
  return new;
end;
It is security definer, return trigger. And email column is varchar.
o

omar

06/15/2022, 3:58 PM
ok i'll rewrite the trigger as you suggested
g

garyaustin

06/15/2022, 3:58 PM
NO
Mine is for a different table name (users instead of profile) and uid instead of id. Yours looks correct at least for the code.
o

omar

06/15/2022, 4:00 PM
ok so can i rewrite it as it was and see if it works?
g

garyaustin

06/15/2022, 4:00 PM
Yes, use a new name and double check security definer. Make sure id column is uuid and email column is varchar
o

omar

06/15/2022, 4:01 PM
ok
sorry this is for the trigger yes?
or the profile table?
g

garyaustin

06/15/2022, 4:04 PM
Can you show a pix of your profile table columns?
o

omar

06/15/2022, 4:04 PM
email is text in profile
g

garyaustin

06/15/2022, 4:05 PM
It should not matter, but change it to varchar
You are going to create a different named function with return type trigger and security definer. Then you will readd your trigger on auth.users using the new function name
o

omar

06/15/2022, 4:09 PM
ok ill try that
shall i keep the old one or delete it
g

garyaustin

06/15/2022, 4:10 PM
You can delete it after new one is working
o

omar

06/15/2022, 4:10 PM
ok
g

garyaustin

06/15/2022, 4:15 PM
Another thing to check would be that all the other columns are allow nullable, but that is default when creating a column.
o

omar

06/15/2022, 4:16 PM
orientation is row or statement?
g

garyaustin

06/15/2022, 4:17 PM
row
o

omar

06/15/2022, 4:19 PM
same error
shall i disable RLS ?
all columns are allow nullable
g

garyaustin

06/15/2022, 4:22 PM
It does not hurt as a test, but should not matter as function is security definer
o

omar

06/15/2022, 4:23 PM
i tried, didn't work
same error
g

garyaustin

06/15/2022, 4:24 PM
Try looking thru your postgres log again for a better error message. I'm out of ideas if you did all the steps we just talked about.
How did you create your profile table (sql, ui)?
o

omar

06/15/2022, 4:27 PM
UI
I got 2 errors in the logs
the first one
the 2nd
Copy code
Event message
current transaction is aborted, commands ignored until end of transaction block
Severity

ERROR

Postgres Username

supabase_auth_admin

Session ID

62a203b5.43dd

Metadata
{
  "file": "/var/log/postgresql/postgresql.csv",
  "host": "db-provagxtnmrfxtldadcr",
  "parsed": [
    {
      "application_name": null,
      "backend_type": "client backend",
      "command_tag": "DEALLOCATE",
      "connection_from": "10.109.104.183:37921",
      "context": null,
      "database_name": "postgres",
      "detail": null,
      "error_severity": "ERROR",
      "hint": null,
      "internal_query": null,
      "internal_query_pos": null,
      "leader_pid": null,
      "location": null,
      "process_id": 17373,
      "query": "deallocate \"pgx_281\"",
      "query_id": 0,
      "query_pos": null,
      "session_id": "62a203b5.43dd",
      "session_line_num": 1902,
      "session_start_time": "2022-06-09 14:29:09 UTC",
      "sql_state_code": "25P02",
      "timestamp": "2022-06-15 16:21:49.742 UTC",
      "transaction_id": 1751,
      "user_name": "supabase_auth_admin",
      "virtual_transaction_id": "10/0"
    }
  ],
  "parsed_from": null,
  "project": "provagxtnmrfxtldadcr",
  "source_type": "file"
}
g

garyaustin

06/15/2022, 4:30 PM
Do you have a function hook?
o

omar

06/15/2022, 4:31 PM
yes
for stripe
g

garyaustin

06/15/2022, 4:32 PM
Ok and that is running on your profile table?
o

omar

06/15/2022, 4:32 PM
yes
g

garyaustin

06/15/2022, 4:33 PM
The first error above was the clue that it was a function hook issue "permission denied for table http_request_queue" Hang on I've seen this somewhere is issues.
LOL, unfortunately... https://github.com/supabase/supabase/issues/4883 I'm not clear on the status of this issue. I would recommend you contact support and mention the http_request_queue error and link that issue. I'll glance at it, but not sure I want to try and walk you thru the fixes they attempted as don't want to do damage to the database structure.
Looks like running this in SQL editor is the recommend fix. https://github.com/supabase/supabase/issues/4883#issuecomment-1017955034 Has to do with a project being paused at some point, at least for that way of generating the error. When you create a user all triggers have to complete without error. When you insert on your profile table, that is causing a trigger for function hooks which at least for some instances has something missing in its setup.
o

omar

06/15/2022, 4:47 PM
hey Gary, you are a star man
thanks for taking the time to go through this with me
ill email support to try and get this resolved
thanks a million
g

garyaustin

06/15/2022, 4:50 PM
Sorry it tooks so long to chase it down. I've added a comment to the issue as this really is a messy random bug to have floating about... https://github.com/supabase/supabase/issues/4883#issuecomment-1156705942
o

omar

06/15/2022, 6:09 PM
hey man so i ran the suggested SQL
signing in works but now my api handler wont update the profile table with the stripe customer id
the handler code
Copy code
js
import initStripe from 'stripe'
import {supabase} from '../../utils/supabaseClient'

const handler = async (req, res) => {
  if(req.query.API_ROUTE_SECRET !== process.env.API_ROUTE_SECRET) {
    return res.status(401).send("You're not authorized to call this API endpoint")
  }
  console.log(req.body)

  const stripe = initStripe(process.env.STRIPE_SECRET_KEY)

  const customer = await stripe.customers.create({
    email: req.body.email
  })
  console.log({customer})

  await supabase.from('profile').update({
    stripe_customer: customer.id
  }).eq('id', req.body.id)

  res.send({ message: `stripe customer created: ${customer.id}`})
}

export default handler
g

garyaustin

06/15/2022, 6:13 PM
Probably an RLS issue on your profile table or you do not have keys set up correctly for your client.
o

omar

06/15/2022, 6:13 PM
i noticed also the code prior to me running the SQL, it was `req.body.record.email `&
id
but then
record
is undefined and i could only access without
record req.body.email
and
id
i disabled rls and tried
didnt work
the keys on client never changed
it was working before
g

garyaustin

06/15/2022, 6:16 PM
I don't see how that sql would impact other tables. How did this work before without a user in the profile table?
o

omar

06/15/2022, 6:19 PM
before i hit the bug, every time i signup, i create a profile record from auth users and also a stripe customer with stripe customer id updating the record on the profile row for that customer
g

garyaustin

06/15/2022, 6:30 PM
OK so you did not use the api handler above at all before?
o

omar

06/15/2022, 6:38 PM
im sure to be honest
thats the function hook i have
g

garyaustin

06/15/2022, 6:44 PM
Yes, but you say it was working, but you also say that you were putting the stripe id in by hand... which implies it was not being used or working before.
o

omar

06/15/2022, 7:36 PM
it worked, you were right the RLS got messed up somehow so it wasnt updating
thanks again
g

garyaustin

06/15/2022, 7:42 PM
@omar Great! If you have more issues please start a new thread as others probably won't look here.