Skip to content

Commit

Permalink
applied a big fix to auth logic
Browse files Browse the repository at this point in the history
  • Loading branch information
parsa-asgari committed Apr 10, 2024
1 parent 55e511f commit ebad4e9
Show file tree
Hide file tree
Showing 13 changed files with 48 additions and 41 deletions.
4 changes: 2 additions & 2 deletions app/admin/access-control/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { UserRoles } from "@/app/admin/access-control/access-control"
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { cookies } from 'next/headers'
import { GetTranslation } from "@/components/translation-helper/ClientTranslations"

Expand All @@ -12,7 +12,7 @@ const TextDirection = process.env.TEXT_DIRECTION

export default async function SettingsAccountPage() {
const cookieStore = cookies()
const session = await auth({ cookieStore })
const session = await authUser()

// Language and Translation
var TranslationData = require(`@/translation/${process.env.BIZGPT_FRONTEND_LANGUAGE}.json`);
Expand Down
4 changes: 2 additions & 2 deletions app/admin/feedbacks/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FeedbacksAdmin } from "@/app/admin/feedbacks/feedbacks"
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { cookies } from 'next/headers'
import { GetTranslation } from "@/components/translation-helper/ClientTranslations"

Expand All @@ -12,7 +12,7 @@ const TextDirection = process.env.TEXT_DIRECTION

export default async function SettingsAccountPage() {
const cookieStore = cookies()
const session = await auth({ cookieStore })
const session = await authUser()

// Language and Translation
var TranslationData = require(`@/translation/${process.env.BIZGPT_FRONTEND_LANGUAGE}.json`);
Expand Down
6 changes: 3 additions & 3 deletions app/api/bookmarks/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'server-only'
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
import { cookies } from 'next/headers'
import { Database } from '@/lib/db_types'
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { NextResponse } from "next/server";

export const runtime = 'nodejs'
Expand All @@ -11,8 +11,8 @@ export async function POST(req: Request) {
const json = await req.json()
let mode = json.mode
const cookieStore = cookies()
const userId = (await auth({ cookieStore }))?.user.id
const userName = (await auth({ cookieStore }))?.user.email
const userId = (await authUser())?.user.id
const userName = (await authUser())?.user.email

if (mode?.replace('"','') == "supabase") {
const supabase = createRouteHandlerClient<Database>({
Expand Down
6 changes: 3 additions & 3 deletions app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
import { cookies } from 'next/headers'
import { Database } from '@/lib/db_types'

import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { nanoid } from '@/lib/utils'

export const maxDuration = 120
Expand All @@ -19,7 +19,7 @@ export async function POST(req: Request) {
})
const json = await req.json()
const { messages, previewToken } = json
const userId = (await auth({ cookieStore }))?.user.id
const userId = (await authUser())?.user.id

if (!userId) {
return new Response('Unauthorized', {
Expand All @@ -32,7 +32,7 @@ export async function POST(req: Request) {
}

const mode = process.env.PERSISTENCE_MODE
const userName = (await auth({ cookieStore }))?.user.email
const userName = (await authUser())?.user.email
const url = `${process.env.BizGPT_CLIENT_API_BASE_ADDRESS_SCHEME}://${process.env.BizGPT_CLIENT_API_BASE_ADDRESS}:${process.env.BizGPT_CLIENT_API_PORT}/${process.env.BizGT_CLIENT_API_MESSAGES_SUBMIT_PATH}`
const index = Math.round(json.messages.length / 2)
const payload = {
Expand Down
6 changes: 3 additions & 3 deletions app/api/feedbacks/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'server-only'
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
import { cookies } from 'next/headers'
import { Database } from '@/lib/db_types'
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { NextResponse } from "next/server";

export const runtime = 'nodejs'
Expand All @@ -11,8 +11,8 @@ export async function POST(req: Request) {
const json = await req.json()
let mode = json.mode
const cookieStore = cookies()
const userId = (await auth({ cookieStore }))?.user.id
const userName = (await auth({ cookieStore }))?.user.email
const userId = (await authUser())?.user.id
const userName = (await authUser())?.user.email

if (mode?.replace('"','') == "supabase") {
const supabase = createRouteHandlerClient<Database>({
Expand Down
4 changes: 2 additions & 2 deletions app/bookmarks/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-nocheck
import { nanoid } from '@/lib/utils'
import { Bookmarks } from '@/components/bookmarks'
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { cookies } from 'next/headers'
import { getChatSupabase, getChatLocal, getBookmarksLocal, getBookmarksSupabase, getFeedbacksLocal, getFeedbacksSupabase } from '@/app/actions'
import { type Chat } from '@/lib/types'
Expand Down Expand Up @@ -30,7 +30,7 @@ async function getBookmarkedMessages(chat: Chat, bookmarks: JSON){

export default async function BookmarksPage() {
const cookieStore = cookies()
const session = await auth({ cookieStore })
const session = await authUser()
let bookmarks = { 'bookmarks' : {}};
let feedbacks = { 'feedbacks' : {}};
let chat = { 'messages': {}}
Expand Down
6 changes: 3 additions & 3 deletions app/chat/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { type Metadata } from 'next'
import { notFound, redirect } from 'next/navigation'

import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { getChatSupabase, getChatLocal, getBookmarksLocal, getFeedbacksLocal } from '@/app/actions'
import { Chat } from '@/components/chat'
import { cookies } from 'next/headers'
Expand All @@ -21,7 +21,7 @@ export async function generateMetadata({
params
}: ChatPageProps): Promise<Metadata> {
const cookieStore = cookies()
const session = await auth({ cookieStore })
const session = await authUser()

if (!session?.user) {
return {}
Expand All @@ -35,7 +35,7 @@ export async function generateMetadata({

export default async function ChatPage({ params }: ChatPageProps) {
const cookieStore = cookies()
const session = await auth({ cookieStore })
const session = await authUser()

if (!session?.user) {
redirect(`/sign-in?next=/chat/${params.id}`)
Expand Down
4 changes: 2 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-nocheck
import { nanoid } from '@/lib/utils'
import { Chat } from '@/components/chat'
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { cookies } from 'next/headers'
import { getChatSupabase, getChatLocal, getBookmarksLocal, getBookmarksSupabase, getFeedbacksLocal, getFeedbacksSupabase } from '@/app/actions'

Expand All @@ -11,7 +11,7 @@ export const dynamic = 'force-dynamic';

export default async function IndexPage() {
const cookieStore = cookies()
const session = await auth({ cookieStore })
const session = await authUser()

let bookmarks = { 'bookmarks' : {}};
let feedbacks = { 'feedbacks' : {}};
Expand Down
4 changes: 2 additions & 2 deletions app/reset-password/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { LoginButton } from '@/components/login-button'
import { ResetPasswordForm } from '@/components/reset-password-form'
import { Separator } from '@/components/ui/separator'
Expand All @@ -7,7 +7,7 @@ import { redirect } from 'next/navigation'

export default async function ResetPassword() {
const cookieStore = cookies()
const session = await auth({ cookieStore })
const session = await authUser()
// redirect to home if user is already logged in
if (session?.user) {
redirect('/')
Expand Down
12 changes: 9 additions & 3 deletions app/sign-in/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { LoginButton } from '@/components/login-button'
import { LoginForm } from '@/components/login-form'
import { LoginFormSearchParams } from '@/components/login-form-searchparams'
Expand All @@ -13,8 +13,14 @@ export default async function SignInPage({
searchParams: { [key: string]: string | string[] | undefined }
}) {
const cookieStore = cookies()
// let session = await auth({ cookieStore })
let session = await auth({cookieStore})

let session
try{
session = await authUser()
}
catch{
undefined
}

// legacy code
// // // const user_id = searchParams?.user_id
Expand Down
15 changes: 5 additions & 10 deletions auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,30 @@ import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
import { createClient } from '@/utils/supabase/server'
import { cookies } from 'next/headers'

// Old auth function
export const auth = async ({
cookieStore
}: {
cookieStore: ReturnType<typeof cookies>
}) => {
// Create a Supabase client configured to use cookies
const supabase = createServerComponentClient({
cookies: () => cookieStore
})
const supabase = createClient()
const { data, error } = await supabase.auth.getSession()
if (error) throw error
return data.session
}

export const authUser = async ({
cookieStore
}: {
cookieStore: ReturnType<typeof cookies>
}) => {
export const authUser = async () => {
// Create a Supabase client configured to use cookies
// const supabase = createServerComponentClient({
// cookies: () => cookieStore
// })
const supabase = createClient()
const { data, error } = await supabase.auth.getSession()
const { data, error } = await supabase.auth.getUser()

// const supabase = createClient()
// const { data:data, error:error } = await supabase.auth.getUser()

if (error) throw error
return data.session
return data
}
10 changes: 8 additions & 2 deletions components/header.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react'
import Link from 'next/link'

import { auth } from '@/auth'
import { auth, authUser } from '@/auth'
import { getUserRole } from '@/app/actions'
import { Button, buttonVariants } from '@/components/ui/button'
import { Sidebar } from '@/components/sidebar'
Expand All @@ -19,7 +19,13 @@ import { LangDropDown } from './header-language-dropdown'

export async function Header() {
const cookieStore = cookies()
const session = await auth({ cookieStore })
let session;
try{
session = await authUser()
}
catch{
undefined
}
var user_role;
session?.user ? (user_role = await getUserRole(session?.user?.id)) : (user_role = undefined)
const BIZGPT_IFRAME_MODE = process.env.BIZGPT_IFRAME_MODE
Expand Down
8 changes: 4 additions & 4 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ export async function middleware(request: NextRequest) {
}
)
// console.log(await supabase.auth.getUser())
let {data: session} = await supabase.auth.getSession()
await supabase.auth.getUser()
let {data: session} = await supabase.auth.getUser()
await supabase.auth.getSession()
const cookieStore = cookies()

// OPTIONAL: this forces users to be logged in to use the chatbot.
Expand All @@ -113,7 +113,7 @@ export async function middleware(request: NextRequest) {
return response
}
if (
!session.session &&
!session.user &&
!request.url.includes('/sign-in') &&
!request.url.includes('/sign-up') &&
!request.url.includes('/reset-password')
Expand All @@ -124,7 +124,7 @@ export async function middleware(request: NextRequest) {
user_id ? redirectUrl.searchParams.set(`user_id`, user_id) : undefined
return NextResponse.redirect(redirectUrl)
}
else if (session.session && request.url.includes('/reset-password') && request.url.includes('/sign-up') && request.url.includes('/sign-in')){
else if (session.user && request.url.includes('/reset-password') && request.url.includes('/sign-up') && request.url.includes('/sign-in')){
const redirectUrl = request.nextUrl.clone()
redirectUrl.pathname = '/'
user_id ? redirectUrl.searchParams.set(`user_id`, user_id) : undefined
Expand Down

0 comments on commit ebad4e9

Please sign in to comment.