Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/dashboard/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dashboard — Linkify</title>
<meta name="description" content="Linkify dashboard." />
<meta name="referrer" content="no-referrer" />
</head>
<body>
<div id="root"></div>
Expand Down
4 changes: 3 additions & 1 deletion apps/dashboard/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Routes, Route } from "react-router-dom"
import AuthCallback from "@/pages/AuthCallback"

export default function App() {
return (
<Routes>
<Route path="/" element={<h1>Dashboard</h1>} />
<Route path="/auth/callback" element={<AuthCallback />} />
<Route path="*" element={<h1>Dashboard</h1>} />
</Routes>
)
}
19 changes: 15 additions & 4 deletions apps/dashboard/src/hooks/use-auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
useCallback,
type ReactNode,
} from "react"
import { useNavigate } from "react-router-dom"
import { useNavigate, useLocation } from "react-router-dom"
import type { Session, User } from "@supabase/supabase-js"
import { supabase } from "@/lib/supabase"
import { fetchMe } from "@/lib/api"
Expand All @@ -26,8 +26,11 @@ const APP_URL = import.meta.env.VITE_APP_URL ?? "http://localhost:5173"

const AuthContext = createContext<AuthContextValue | undefined>(undefined)

const PUBLIC_PATHS = ["/auth/callback"]

export function AuthProvider({ children }: { children: ReactNode }) {
const navigate = useNavigate()
const location = useLocation()
const [state, setState] = useState<AuthState>({
user: null,
session: null,
Expand All @@ -45,9 +48,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, [])

const redirectToLogin = useCallback(() => {
const currentPath = window.location.pathname + window.location.search
window.location.href = `${APP_URL}/login?redirectTo=${encodeURIComponent(currentPath)}`
}, [])
const currentPath = location.pathname + location.search
window.location.replace(`${APP_URL}/login?redirectTo=${encodeURIComponent(currentPath)}`)
}, [location.pathname, location.search])

useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
Expand Down Expand Up @@ -83,6 +86,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, [fetchProfile])

useEffect(() => {
if (state.isLoading) return
if (state.session) return
if (PUBLIC_PATHS.includes(location.pathname)) return

redirectToLogin()
}, [state.isLoading, state.session, location.pathname, redirectToLogin])

const signOut = useCallback(async () => {
await supabase.auth.signOut()
setState({
Expand Down
69 changes: 69 additions & 0 deletions apps/dashboard/src/pages/AuthCallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { supabase } from "@/lib/supabase"

export default function AuthCallback() {
const navigate = useNavigate()
const [error, setError] = useState<string | null>(null)

useEffect(() => {
async function handleCallback() {
const hash = window.location.hash.slice(1)
if (!hash) {
setError("No authentication data received")
return
}

const params = new URLSearchParams(hash)
const accessToken = params.get("access_token")
const refreshToken = params.get("refresh_token")
const redirectTo = params.get("redirectTo") || "/overview"

if (!accessToken || !refreshToken) {
setError("Invalid authentication data")
return
}

window.location.hash = ""

const { error: setSessionError } = await supabase.auth.setSession({
access_token: accessToken,
refresh_token: refreshToken,
})

if (setSessionError) {
setError(setSessionError.message)
return
}

navigate(redirectTo, { replace: true })
}

handleCallback()
}, [navigate])

if (error) {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-4 px-6">
<div className="rounded-[10px] border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
{error}
</div>
<a
href="/login"
className="text-sm font-medium text-foreground hover:underline"
>
Back to sign in
</a>
</div>
)
}

return (
<div className="flex min-h-screen flex-col items-center justify-center gap-4 px-6">
<span className="h-6 w-6 animate-spin rounded-full border-2 border-foreground border-t-transparent" />
<p className="text-sm text-muted-foreground">
Signing you in...
</p>
</div>
)
}
43 changes: 37 additions & 6 deletions apps/web/src/hooks/use-auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { useNavigate } from "react-router-dom"
import type { Session, User } from "@supabase/supabase-js"
import { supabase } from "@/lib/supabase"
import { fetchMe } from "@/lib/api"
import { DASHBOARD_URL } from "@/lib/config"

interface AuthState {
user: User | null
Expand All @@ -32,6 +33,21 @@ interface AuthContextValue extends AuthState {

const AuthContext = createContext<AuthContextValue | undefined>(undefined)

function getRedirectTo(): string | null {
const params = new URLSearchParams(window.location.search)
return params.get("redirectTo")
}

function relaySessionToDashboard() {
supabase.auth.getSession().then(({ data: { session } }) => {
if (!session) return
const { access_token, refresh_token } = session
const redirectTo = getRedirectTo() || "/overview"
const hash = `#access_token=${encodeURIComponent(access_token)}&refresh_token=${encodeURIComponent(refresh_token)}&redirectTo=${encodeURIComponent(redirectTo)}`
window.location.replace(`${DASHBOARD_URL}/auth/callback${hash}`)
})
}

export function AuthProvider({ children }: { children: ReactNode }) {
const navigate = useNavigate()
const [state, setState] = useState<AuthState>({
Expand Down Expand Up @@ -97,19 +113,27 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return { error: "Please verify your email before signing in. Check your inbox." }
}

navigate("/")
const redirectTo = getRedirectTo()
if (redirectTo) {
relaySessionToDashboard()
} else {
navigate("/")
}
return { error: null }
},
[navigate]
)

const signUp = useCallback(
async (email: string, password: string) => {
const redirectTo = getRedirectTo()
const { error, data } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: `${window.location.origin}/auth/callback`,
emailRedirectTo: redirectTo
? `${window.location.origin}/auth/callback?redirectTo=${encodeURIComponent(redirectTo)}`
: `${window.location.origin}/auth/callback`,
},
})
if (error) return { error: error.message, needsEmailVerification: false }
Expand All @@ -119,7 +143,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
data.session === null

if (!needsEmailVerification && data.session) {
navigate("/")
if (redirectTo) {
relaySessionToDashboard()
} else {
navigate("/")
}
}

return { error: null, needsEmailVerification }
Expand All @@ -140,11 +168,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const signInWithProvider = useCallback(
async (provider: "google" | "github") => {
try {
const redirectTo = getRedirectTo()
const callbackUrl = redirectTo
? `${window.location.origin}/auth/callback?redirectTo=${encodeURIComponent(redirectTo)}`
: `${window.location.origin}/auth/callback`

const { error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
options: { redirectTo: callbackUrl },
})
if (error) return { error: error.message }
} catch {
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export const APP_URL = import.meta.env.VITE_APP_URL ?? "http://localhost:5173"
export const DASHBOARD_URL = import.meta.env.VITE_DASHBOARD_URL ?? "http://localhost:5174"
11 changes: 10 additions & 1 deletion apps/web/src/pages/AuthCallback.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { supabase } from "@/lib/supabase"
import { DASHBOARD_URL } from "@/lib/config"

export default function AuthCallback() {
const navigate = useNavigate()
Expand All @@ -12,6 +13,7 @@ export default function AuthCallback() {
const code = params.get("code")
const errorParam = params.get("error")
const errorDescription = params.get("error_description")
const redirectTo = params.get("redirectTo")

if (errorParam) {
setError(errorDescription ?? "Authentication failed")
Expand All @@ -28,8 +30,15 @@ export default function AuthCallback() {
}

const { data: { session } } = await supabase.auth.getSession()

if (session) {
navigate("/", { replace: true })
if (redirectTo) {
const { access_token, refresh_token } = session
const hash = `#access_token=${encodeURIComponent(access_token)}&refresh_token=${encodeURIComponent(refresh_token)}&redirectTo=${encodeURIComponent(redirectTo)}`
window.location.replace(`${DASHBOARD_URL}/auth/callback${hash}`)
} else {
navigate("/", { replace: true })
}
}
}

Expand Down
Loading