feat(app): improve clerk auth

This commit is contained in:
Lars Hampe 2024-11-12 16:15:33 +01:00
parent 154df360ac
commit 5ae746346f
3 changed files with 47 additions and 9 deletions

View File

@ -8,7 +8,11 @@ import {
Separator,
SidebarTrigger,
} from '@boring.tools/ui'
import { useAuth } from '@clerk/clerk-react'
import { Link } from '@tanstack/react-router'
import { useEffect } from 'react'
import { useUser } from '../hooks/useUser'
type Breadcrumbs = {
name: string
@ -19,6 +23,15 @@ export const PageWrapper = ({
children,
breadcrumbs,
}: { children: React.ReactNode; breadcrumbs?: Breadcrumbs[] }) => {
const { error } = useUser()
const { signOut } = useAuth()
useEffect(() => {
if (error) {
signOut()
}
}, [error, signOut])
return (
<>
<header className="flex h-16 shrink-0 items-center gap-2">

View File

@ -0,0 +1,21 @@
import type { UserOutput } from '@boring.tools/schema'
import { useAuth } from '@clerk/clerk-react'
import { useQuery } from '@tanstack/react-query'
import type { z } from 'zod'
import { queryFetch } from '../utils/queryFetch'
type User = z.infer<typeof UserOutput>
export const useUser = () => {
const { getToken } = useAuth()
return useQuery({
queryKey: ['user'],
queryFn: async (): Promise<Readonly<User>> =>
await queryFetch({
path: 'user',
method: 'get',
token: await getToken(),
}),
retry: false,
})
}

View File

@ -12,13 +12,17 @@ const url = import.meta.env.PROD
: 'http://localhost:3000'
export const queryFetch = async ({ path, method, data, token }: Fetch) => {
const response = await axios({
method,
url: `${url}/v1/${path}`,
data,
headers: {
Authorization: `Bearer ${token}`,
},
})
return response.data
try {
const response = await axios({
method,
url: `${url}/v1/${path}`,
data,
headers: {
Authorization: `Bearer ${token}`,
},
})
return response.data
} catch (error) {
throw new Error('Somethind went wrong.')
}
}