Skip to content

An AI-powered search engine with a generative UI

feat: add supabase password-based auth block

Yoshiki Miura7d98b843ef68
diff --git a/.env.local.example b/.env.local.example
index 72df1c88..f67a93de 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -91,4 +91,9 @@ TAVILY_API_KEY=[YOUR_TAVILY_API_KEY] # Get your API key at: https://app.tavily.
#------------------------------------------------------------------------------
# NEXT_PUBLIC_ENABLE_SHARE=true # Enable sharing of chat conversations
# SERPER_API_KEY=[YOUR_SERPER_API_KEY] # Enable video search capability
-# JINA_API_KEY=[YOUR_JINA_API_KEY] # Alternative to Tavily for retrieve tool
\ No newline at end of file
+# JINA_API_KEY=[YOUR_JINA_API_KEY] # Alternative to Tavily for retrieve tool
+
+
+# Supabase
+# NEXT_PUBLIC_SUPABASE_URL=""
+# NEXT_PUBLIC_SUPABASE_ANON_KEY=""
\ No newline at end of file
diff --git a/app/auth/confirm/route.ts b/app/auth/confirm/route.ts
new file mode 100644
index 00000000..3161cf0a
--- /dev/null
+++ b/app/auth/confirm/route.ts
@@ -0,0 +1,30 @@
+import { createClient } from '@/lib/supabase/server'
+import { type EmailOtpType } from '@supabase/supabase-js'
+import { redirect } from 'next/navigation'
+import { type NextRequest } from 'next/server'
+
+export async function GET(request: NextRequest) {
+ const { searchParams } = new URL(request.url)
+ const token_hash = searchParams.get('token_hash')
+ const type = searchParams.get('type') as EmailOtpType | null
+ const next = searchParams.get('next') ?? '/'
+
+ if (token_hash && type) {
+ const supabase = await createClient()
+
+ const { error } = await supabase.auth.verifyOtp({
+ type,
+ token_hash,
+ })
+ if (!error) {
+ // redirect user to specified redirect URL or root of app
+ redirect(next)
+ } else {
+ // redirect the user to an error page with some instructions
+ redirect(`/auth/error?error=${error?.message}`)
+ }
+ }
+
+ // redirect the user to an error page with some instructions
+ redirect(`/auth/error?error=No token hash or type`)
+}
diff --git a/app/auth/error/page.tsx b/app/auth/error/page.tsx
new file mode 100644
index 00000000..b7937219
--- /dev/null
+++ b/app/auth/error/page.tsx
@@ -0,0 +1,26 @@
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+
+export default async function Page({ searchParams }: { searchParams: Promise<{ error: string }> }) {
+ const params = await searchParams
+
+ return (
+ <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
+ <div className="w-full max-w-sm">
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-2xl">Sorry, something went wrong.</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {params?.error ? (
+ <p className="text-sm text-muted-foreground">Code error: {params.error}</p>
+ ) : (
+ <p className="text-sm text-muted-foreground">An unspecified error occurred.</p>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/app/auth/forgot-password/page.tsx b/app/auth/forgot-password/page.tsx
new file mode 100644
index 00000000..c2568ca2
--- /dev/null
+++ b/app/auth/forgot-password/page.tsx
@@ -0,0 +1,11 @@
+import { ForgotPasswordForm } from '@/components/forgot-password-form'
+
+export default function Page() {
+ return (
+ <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
+ <div className="w-full max-w-sm">
+ <ForgotPasswordForm />
+ </div>
+ </div>
+ )
+}
diff --git a/app/auth/login/page.tsx b/app/auth/login/page.tsx
new file mode 100644
index 00000000..3ac37e2c
--- /dev/null
+++ b/app/auth/login/page.tsx
@@ -0,0 +1,11 @@
+import { LoginForm } from '@/components/login-form'
+
+export default function Page() {
+ return (
+ <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
+ <div className="w-full max-w-sm">
+ <LoginForm />
+ </div>
+ </div>
+ )
+}
diff --git a/app/auth/sign-up-success/page.tsx b/app/auth/sign-up-success/page.tsx
new file mode 100644
index 00000000..f2672f6d
--- /dev/null
+++ b/app/auth/sign-up-success/page.tsx
@@ -0,0 +1,30 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '@/components/ui/card'
+
+export default function Page() {
+ return (
+ <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
+ <div className="w-full max-w-sm">
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-2xl">Thank you for signing up!</CardTitle>
+ <CardDescription>Check your email to confirm</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <p className="text-sm text-muted-foreground">
+ You&apos;ve successfully signed up. Please check your email to confirm your account
+ before signing in.
+ </p>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/app/auth/sign-up/page.tsx b/app/auth/sign-up/page.tsx
new file mode 100644
index 00000000..9662667e
--- /dev/null
+++ b/app/auth/sign-up/page.tsx
@@ -0,0 +1,11 @@
+import { SignUpForm } from '@/components/sign-up-form'
+
+export default function Page() {
+ return (
+ <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
+ <div className="w-full max-w-sm">
+ <SignUpForm />
+ </div>
+ </div>
+ )
+}
diff --git a/app/auth/update-password/page.tsx b/app/auth/update-password/page.tsx
new file mode 100644
index 00000000..96a68390
--- /dev/null
+++ b/app/auth/update-password/page.tsx
@@ -0,0 +1,11 @@
+import { UpdatePasswordForm } from '@/components/update-password-form'
+
+export default function Page() {
+ return (
+ <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
+ <div className="w-full max-w-sm">
+ <UpdatePasswordForm />
+ </div>
+ </div>
+ )
+}
diff --git a/app/protected/page.tsx b/app/protected/page.tsx
new file mode 100644
index 00000000..47d5206c
--- /dev/null
+++ b/app/protected/page.tsx
@@ -0,0 +1,22 @@
+import { redirect } from 'next/navigation'
+
+import { LogoutButton } from '@/components/logout-button'
+import { createClient } from '@/lib/supabase/server'
+
+export default async function ProtectedPage() {
+ const supabase = await createClient()
+
+ const { data, error } = await supabase.auth.getUser()
+ if (error || !data?.user) {
+ redirect('/auth/login')
+ }
+
+ return (
+ <div className="flex h-svh w-full items-center justify-center gap-2">
+ <p>
+ Hello <span>{data.user.email}</span>
+ </p>
+ <LogoutButton />
+ </div>
+ )
+}
diff --git a/bun.lockb b/bun.lockb
index 19863f21..b591207b 100755
Binary files a/bun.lockb and b/bun.lockb differ
diff --git a/components/forgot-password-form.tsx b/components/forgot-password-form.tsx
new file mode 100644
index 00000000..cd256b7b
--- /dev/null
+++ b/components/forgot-password-form.tsx
@@ -0,0 +1,98 @@
+'use client'
+
+import { cn } from '@/lib/utils/index'
+import { createClient } from '@/lib/supabase/client'
+import { Button } from '@/components/ui/button'
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '@/components/ui/card'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import Link from 'next/link'
+import { useState } from 'react'
+
+export function ForgotPasswordForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {
+ const [email, setEmail] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [success, setSuccess] = useState(false)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const handleForgotPassword = async (e: React.FormEvent) => {
+ e.preventDefault()
+ const supabase = createClient()
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ // The url which will be included in the email. This URL needs to be configured in your redirect URLs in the Supabase dashboard at https://supabase.com/dashboard/project/_/auth/url-configuration
+ const { error } = await supabase.auth.resetPasswordForEmail(email, {
+ redirectTo: `${window.location.origin}/auth/update-password`,
+ })
+ if (error) throw error
+ setSuccess(true)
+ } catch (error: unknown) {
+ setError(error instanceof Error ? error.message : 'An error occurred')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <div className={cn('flex flex-col gap-6', className)} {...props}>
+ {success ? (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-2xl">Check Your Email</CardTitle>
+ <CardDescription>Password reset instructions sent</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <p className="text-sm text-muted-foreground">
+ If you registered using your email and password, you will receive a password reset
+ email.
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-2xl">Reset Your Password</CardTitle>
+ <CardDescription>
+ Type in your email and we&apos;ll send you a link to reset your password
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form onSubmit={handleForgotPassword}>
+ <div className="flex flex-col gap-6">
+ <div className="grid gap-2">
+ <Label htmlFor="email">Email</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder="[email protected]"
+ required
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ />
+ </div>
+ {error && <p className="text-sm text-red-500">{error}</p>}
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? 'Sending...' : 'Send reset email'}
+ </Button>
+ </div>
+ <div className="mt-4 text-center text-sm">
+ Already have an account?{' '}
+ <Link href="/auth/login" className="underline underline-offset-4">
+ Login
+ </Link>
+ </div>
+ </form>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ )
+}
diff --git a/components/login-form.tsx b/components/login-form.tsx
new file mode 100644
index 00000000..6f5dfbbc
--- /dev/null
+++ b/components/login-form.tsx
@@ -0,0 +1,102 @@
+'use client'
+
+import { cn } from '@/lib/utils/index'
+import { createClient } from '@/lib/supabase/client'
+import { Button } from '@/components/ui/button'
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '@/components/ui/card'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import Link from 'next/link'
+import { useRouter } from 'next/navigation'
+import { useState } from 'react'
+
+export function LoginForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {
+ const [email, setEmail] = useState('')
+ const [password, setPassword] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+ const router = useRouter()
+
+ const handleLogin = async (e: React.FormEvent) => {
+ e.preventDefault()
+ const supabase = createClient()
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const { error } = await supabase.auth.signInWithPassword({
+ email,
+ password,
+ })
+ if (error) throw error
+ // Update this route to redirect to an authenticated route. The user already has an active session.
+ router.push('/protected')
+ } catch (error: unknown) {
+ setError(error instanceof Error ? error.message : 'An error occurred')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <div className={cn('flex flex-col gap-6', className)} {...props}>
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-2xl">Login</CardTitle>
+ <CardDescription>Enter your email below to login to your account</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form onSubmit={handleLogin}>
+ <div className="flex flex-col gap-6">
+ <div className="grid gap-2">
+ <Label htmlFor="email">Email</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder="[email protected]"
+ required
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ />
+ </div>
+ <div className="grid gap-2">
+ <div className="flex items-center">
+ <Label htmlFor="password">Password</Label>
+ <Link
+ href="/auth/forgot-password"
+ className="ml-auto inline-block text-sm underline-offset-4 hover:underline"
+ >
+ Forgot your password?
+ </Link>
+ </div>
+ <Input
+ id="password"
+ type="password"
+ required
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </div>
+ {error && <p className="text-sm text-red-500">{error}</p>}
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? 'Logging in...' : 'Login'}
+ </Button>
+ </div>
+ <div className="mt-4 text-center text-sm">
+ Don&apos;t have an account?{' '}
+ <Link href="/auth/sign-up" className="underline underline-offset-4">
+ Sign up
+ </Link>
+ </div>
+ </form>
+ </CardContent>
+ </Card>
+ </div>
+ )
+}
diff --git a/components/logout-button.tsx b/components/logout-button.tsx
new file mode 100644
index 00000000..bff50cec
--- /dev/null
+++ b/components/logout-button.tsx
@@ -0,0 +1,17 @@
+'use client'
+
+import { createClient } from '@/lib/supabase/client'
+import { Button } from '@/components/ui/button'
+import { useRouter } from 'next/navigation'
+
+export function LogoutButton() {
+ const router = useRouter()
+
+ const logout = async () => {
+ const supabase = createClient()
+ await supabase.auth.signOut()
+ router.push('/auth/login')
+ }
+
+ return <Button onClick={logout}>Logout</Button>
+}
diff --git a/components/sign-up-form.tsx b/components/sign-up-form.tsx
new file mode 100644
index 00000000..cce47b99
--- /dev/null
+++ b/components/sign-up-form.tsx
@@ -0,0 +1,117 @@
+'use client'
+
+import { cn } from '@/lib/utils/index'
+import { createClient } from '@/lib/supabase/client'
+import { Button } from '@/components/ui/button'
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '@/components/ui/card'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import Link from 'next/link'
+import { useRouter } from 'next/navigation'
+import { useState } from 'react'
+
+export function SignUpForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {
+ const [email, setEmail] = useState('')
+ const [password, setPassword] = useState('')
+ const [repeatPassword, setRepeatPassword] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+ const router = useRouter()
+
+ const handleSignUp = async (e: React.FormEvent) => {
+ e.preventDefault()
+ const supabase = createClient()
+ setIsLoading(true)
+ setError(null)
+
+ if (password !== repeatPassword) {
+ setError('Passwords do not match')
+ setIsLoading(false)
+ return
+ }
+
+ try {
+ const { error } = await supabase.auth.signUp({
+ email,
+ password,
+ options: {
+ emailRedirectTo: `${window.location.origin}/protected`,
+ },
+ })
+ if (error) throw error
+ router.push('/auth/sign-up-success')
+ } catch (error: unknown) {
+ setError(error instanceof Error ? error.message : 'An error occurred')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <div className={cn('flex flex-col gap-6', className)} {...props}>
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-2xl">Sign up</CardTitle>
+ <CardDescription>Create a new account</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form onSubmit={handleSignUp}>
+ <div className="flex flex-col gap-6">
+ <div className="grid gap-2">
+ <Label htmlFor="email">Email</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder="[email protected]"
+ required
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ />
+ </div>
+ <div className="grid gap-2">
+ <div className="flex items-center">
+ <Label htmlFor="password">Password</Label>
+ </div>
+ <Input
+ id="password"
+ type="password"
+ required
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </div>
+ <div className="grid gap-2">
+ <div className="flex items-center">
+ <Label htmlFor="repeat-password">Repeat Password</Label>
+ </div>
+ <Input
+ id="repeat-password"
+ type="password"
+ required
+ value={repeatPassword}
+ onChange={(e) => setRepeatPassword(e.target.value)}
+ />
+ </div>
+ {error && <p className="text-sm text-red-500">{error}</p>}
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? 'Creating an account...' : 'Sign up'}
+ </Button>
+ </div>
+ <div className="mt-4 text-center text-sm">
+ Already have an account?{' '}
+ <Link href="/auth/login" className="underline underline-offset-4">
+ Login
+ </Link>
+ </div>
+ </form>
+ </CardContent>
+ </Card>
+ </div>
+ )
+}
diff --git a/components/ui/card.tsx b/components/ui/card.tsx
index 4902b398..f9a373cc 100644
--- a/components/ui/card.tsx
+++ b/components/ui/card.tsx
@@ -1,6 +1,6 @@
import * as React from 'react'
-import { cn } from '@/lib/utils'
+import { cn } from '@/lib/utils/index'
const Card = React.forwardRef<
HTMLDivElement,
diff --git a/components/ui/label.tsx b/components/ui/label.tsx
index 340513e6..5f2488bd 100644
--- a/components/ui/label.tsx
+++ b/components/ui/label.tsx
@@ -4,7 +4,7 @@ import * as React from 'react'
import * as LabelPrimitive from '@radix-ui/react-label'
import { cva, type VariantProps } from 'class-variance-authority'
-import { cn } from '@/lib/utils'
+import { cn } from '@/lib/utils/index'
const labelVariants = cva(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
diff --git a/components/update-password-form.tsx b/components/update-password-form.tsx
new file mode 100644
index 00000000..fab8fc32
--- /dev/null
+++ b/components/update-password-form.tsx
@@ -0,0 +1,73 @@
+'use client'
+
+import { cn } from '@/lib/utils/index'
+import { createClient } from '@/lib/supabase/client'
+import { Button } from '@/components/ui/button'
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '@/components/ui/card'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { useRouter } from 'next/navigation'
+import { useState } from 'react'
+
+export function UpdatePasswordForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {
+ const [password, setPassword] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+ const router = useRouter()
+
+ const handleForgotPassword = async (e: React.FormEvent) => {
+ e.preventDefault()
+ const supabase = createClient()
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const { error } = await supabase.auth.updateUser({ password })
+ if (error) throw error
+ // Update this route to redirect to an authenticated route. The user already has an active session.
+ router.push('/protected')
+ } catch (error: unknown) {
+ setError(error instanceof Error ? error.message : 'An error occurred')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <div className={cn('flex flex-col gap-6', className)} {...props}>
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-2xl">Reset Your Password</CardTitle>
+ <CardDescription>Please enter your new password below.</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form onSubmit={handleForgotPassword}>
+ <div className="flex flex-col gap-6">
+ <div className="grid gap-2">
+ <Label htmlFor="password">New password</Label>
+ <Input
+ id="password"
+ type="password"
+ placeholder="New password"
+ required
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </div>
+ {error && <p className="text-sm text-red-500">{error}</p>}
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? 'Saving...' : 'Save new password'}
+ </Button>
+ </div>
+ </form>
+ </CardContent>
+ </Card>
+ </div>
+ )
+}
diff --git a/middleware.ts b/middleware.ts
index e50a76c5..afe29b60 100644
--- a/middleware.ts
+++ b/middleware.ts
@@ -1,26 +1,19 @@
-import type { NextRequest } from 'next/server'
-import { NextResponse } from 'next/server'
+import { updateSession } from '@/lib/supabase/middleware'
+import { type NextRequest } from 'next/server'
-export function middleware(request: NextRequest) {
- // Create a response
- const response = NextResponse.next()
-
- // Get the protocol from X-Forwarded-Proto header or request protocol
- const protocol =
- request.headers.get('x-forwarded-proto') || request.nextUrl.protocol
-
- // Get the host from X-Forwarded-Host header or request host
- const host =
- request.headers.get('x-forwarded-host') || request.headers.get('host') || ''
-
- // Construct the base URL - ensure protocol has :// format
- const baseUrl = `${protocol}${protocol.endsWith(':') ? '//' : '://'}${host}`
-
- // Add request information to response headers
- response.headers.set('x-url', request.url)
- response.headers.set('x-host', host)
- response.headers.set('x-protocol', protocol)
- response.headers.set('x-base-url', baseUrl)
+export async function middleware(request: NextRequest) {
+ return await updateSession(request)
+}
- return response
+export const config = {
+ matcher: [
+ /*
+ * Match all request paths except for the ones starting with:
+ * - _next/static (static files)
+ * - _next/image (image optimization files)
+ * - favicon.ico (favicon file)
+ * Feel free to modify this pattern to include more paths.
+ */
+ '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
+ ],
}
diff --git a/package.json b/package.json
index 9bf5a013..41cc7115 100644
--- a/package.json
+++ b/package.json
@@ -24,12 +24,12 @@
"@radix-ui/react-collapsible": "^1.0.3",
"@radix-ui/react-dialog": "^1.1.11",
"@radix-ui/react-dropdown-menu": "^2.0.6",
- "@radix-ui/react-label": "^2.0.2",
+ "@radix-ui/react-label": "^2.1.6",
"@radix-ui/react-popover": "^1.1.5",
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-separator": "^1.1.4",
"@radix-ui/react-slider": "^1.1.2",
- "@radix-ui/react-slot": "^1.2.0",
+ "@radix-ui/react-slot": "^1.2.2",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-toggle": "^1.1.1",
"@radix-ui/react-tooltip": "^1.2.4",