79 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-05-26 18:37:36 -07:00
import { User } from "@/lib/types"
2024-11-17 12:35:56 -05:00
import { generateUniqueUsername } from "@/lib/username-generator"
2024-05-26 18:37:36 -07:00
import { currentUser } from "@clerk/nextjs"
import { redirect } from "next/navigation"
2024-04-17 21:24:57 -04:00
export default async function AppAuthLayout({
children,
}: {
2024-05-26 18:37:36 -07:00
children: React.ReactNode
2024-04-17 21:24:57 -04:00
}) {
2024-05-26 18:37:36 -07:00
const user = await currentUser()
2024-04-17 21:24:57 -04:00
if (!user) {
2024-05-26 18:37:36 -07:00
redirect("/")
2024-04-17 21:24:57 -04:00
}
const dbUser = await fetch(
2024-05-26 18:37:36 -07:00
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user?id=${user.id}`,
{
headers: {
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
},
}
)
const dbUserJSON = (await dbUser.json()) as User
2024-04-17 21:24:57 -04:00
2024-05-03 13:53:21 -07:00
if (!dbUserJSON.id) {
// Try to get GitHub username if available
const githubUsername = user.externalAccounts.find(
2024-11-17 12:35:56 -05:00
(account) => account.provider === "github"
)?.username
2024-11-17 12:35:56 -05:00
const username =
githubUsername ||
(await generateUniqueUsername(async (username) => {
// Check if username exists in database
const userCheck = await fetch(
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user/check-username?username=${username}`,
{
headers: {
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
},
}
)
const exists = await userCheck.json()
return exists.exists
}))
const res = await fetch(
2024-05-26 18:37:36 -07:00
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
2024-05-26 18:37:36 -07:00
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
},
body: JSON.stringify({
id: user.id,
name: user.firstName + " " + user.lastName,
email: user.emailAddresses[0].emailAddress,
username: username,
avatarUrl: user.imageUrl || null,
createdAt: new Date().toISOString(),
}),
}
2024-05-26 18:37:36 -07:00
)
if (!res.ok) {
2024-11-17 12:35:56 -05:00
const error = await res.text()
console.error("Failed to create user:", error)
} else {
2024-11-17 12:35:56 -05:00
const data = await res.json()
console.log("User created successfully:", data)
}
2024-04-17 22:55:02 -04:00
}
2024-04-17 21:24:57 -04:00
2024-05-26 18:37:36 -07:00
return <>{children}</>
2024-04-17 21:24:57 -04:00
}