From 5fb21c085e0e3acd01ac7fb1e86ecb5a8fd59a85 Mon Sep 17 00:00:00 2001 From: Kang Ming Date: Mon, 6 Dec 2021 20:49:36 +0800 Subject: [PATCH] fix: update apiAuthenticate to use gotrue --- studio/lib/api/apiAuthenticate.ts | 57 +++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 15 deletions(-) diff --git a/studio/lib/api/apiAuthenticate.ts b/studio/lib/api/apiAuthenticate.ts index 721a1a68ce4..79730ccd789 100644 --- a/studio/lib/api/apiAuthenticate.ts +++ b/studio/lib/api/apiAuthenticate.ts @@ -4,6 +4,8 @@ import { readOnly } from './supabaseClient' import { SupaResponse, User } from 'types' import { auth0 } from './auth0' import { flattenNamespaceOnUser } from './apiHelpers' +import { config } from 'process' +import { getAuth0Id, getAuthUser, getIdentity, GOTRUE_ENABLED } from 'lib/gotrue' /** * Use this method on api routes to check if user is authenticated and having required permissions. @@ -32,7 +34,7 @@ export async function apiAuthenticate( try { // Check that they are logged in // If no error throw from getAccessToken. That's good, we can continue - await auth0.getAccessToken(req, res) + if (!(GOTRUE_ENABLED)) await auth0.getAccessToken(req, res) const user = await fetchUser(req, res) if (!user) { @@ -53,16 +55,41 @@ export async function apiAuthenticate( * user with only id prop or detail object. It depends on requireUserDetail config */ async function fetchUser(req: NextApiRequest, res: NextApiResponse): Promise { - const session = auth0.getSession(req, res) + let user_id_supabase = null + let user_id_auth0 = null + let gotrue_id = null + let email = null + if (GOTRUE_ENABLED) { + const token = req.headers.authorization + if (!token) { + return res.status(401).end('Unauthorized: missing access token') + } + let { user: gotrue_user, error: authError } = await getAuthUser(token) + if (authError) { + throw authError + } + if (gotrue_user !== null) { + gotrue_id = gotrue_user?.id + email = gotrue_user.email - if (!session) { - return null + let { identity, error } = getIdentity(gotrue_user) + if (error) throw error + if (identity?.provider !== undefined) { + user_id_auth0 = getAuth0Id(identity?.provider, identity?.id) + } + } + } else { + const session = auth0.getSession(req, res) + if (!session) { + return null + } + const { user: auth0_user } = session + const flattened = flattenNamespaceOnUser('https://supabase.io', auth0_user) + user_id_supabase = flattened.user_id_supabase + user_id_auth0 = flattened.user_id_auth0 + email = flattened.email } - const { user: auth0_user } = session - const flattened = flattenNamespaceOnUser('https://supabase.io', auth0_user) - const { user_id_supabase, user_id_auth0, email } = flattened - if (user_id_supabase) { return { id: user_id_supabase, @@ -70,15 +97,15 @@ async function fetchUser(req: NextApiRequest, res: NextApiResponse): Promise