From a78fe111c2eeb1133d052b09a898410fc5d91edd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yusuf=20Akg=C3=BCl?= <s86116@bht-berlin.de> Date: Tue, 6 Jun 2023 22:56:18 +0200 Subject: [PATCH] fix github signup --- components/user-auth-form.tsx | 10 +++--- lib/auth.ts | 61 ++++++++++++++++------------------- 2 files changed, 34 insertions(+), 37 deletions(-) diff --git a/components/user-auth-form.tsx b/components/user-auth-form.tsx index cb42f07..f956d48 100644 --- a/components/user-auth-form.tsx +++ b/components/user-auth-form.tsx @@ -111,6 +111,11 @@ export function UserAuthForm({ type, className, ...props }: UserAuthFormProps) { } } + async function onGitHub() { + setIsGitHubLoading(true) + await signIn("github", { callbackUrl: searchParams?.get("from") || "/home" }) + } + return ( <div className={cn("grid gap-6", className)} {...props}> <form onSubmit={handleSubmit(onSubmit)}> @@ -221,10 +226,7 @@ export function UserAuthForm({ type, className, ...props }: UserAuthFormProps) { <Button variant="outline" type="button" - onClick={() => { - setIsGitHubLoading(true) - signIn("github", { callbackUrl: searchParams?.get("from") || "/home" }) - }} + onClick={onGitHub} disabled={isLoading || isGitHubLoading} > {isGitHubLoading ? ( diff --git a/lib/auth.ts b/lib/auth.ts index 9a459b6..b1696bb 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -65,39 +65,6 @@ export const authOptions: NextAuthOptions = { ], secret: env.NEXTAUTH_SECRET, callbacks: { - async signIn({ user, account }) { - if (account?.provider === 'github') { - const { name, email } = user; - if (!name || !email) { - return false; - } - - let username = await normalize(name.toLowerCase().replace(/\s/g, '')); - - let isUnique = false; - while (!isUnique) { - const existingUserName = await db.user.findFirst({ - where: { - username, - NOT: { email }, - }, - }) - - if (existingUserName) { - username = `${username}${Math.floor(Math.random() * 1000)}` - } else { - isUnique = true; - } - } - - await db.user.update({ - where: { email }, - data: { username }, - }); - } - - return true; - }, async session({ token, session }) { if (token) { session.user.id = token.id @@ -123,6 +90,34 @@ export const authOptions: NextAuthOptions = { return token } + if (!dbUser.username) { + let username = await normalize(dbUser.name?.toLowerCase().replace(/\s/g, '')); + const email = dbUser.email?.toLowerCase(); + + let isUnique = false; + while (!isUnique) { + const existingUserName = await db.user.findFirst({ + where: { + username, + NOT: { email }, + }, + }); + + if (existingUserName) { + username = `${username}${Math.floor(Math.random() * 1000)}`; + } else { + isUnique = true; + } + } + + dbUser.username = username; + + await db.user.update({ + where: { email }, + data: { username }, + }); + } + return { id: dbUser.id, name: dbUser.name, -- GitLab