Skip to content

Commit

Permalink
fix: oauth first signup
Browse files Browse the repository at this point in the history
  • Loading branch information
rharkor committed Sep 14, 2023
1 parent e58df86 commit bab6312
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 35 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"lucide-react": "^0.276.0",
"negotiator": "^0.6.3",
"next": "^13.4.19",
"next-auth": "^4.22.5",
"next-auth": "^4.23.1",
"next-compose-plugins": "^2.2.1",
"next-themes": "^0.2.1",
"prisma": "^5.1.1",
Expand Down
6 changes: 4 additions & 2 deletions src/app/[lang]/(protected)/profile/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@ export default async function Profile({

return (
<main className="container flex flex-1 flex-col items-center justify-center p-6">
<div>
<div className="flex w-full max-w-max flex-col">
<Card className="relative z-10 m-auto max-w-full">
<CardHeader>
<CardTitle>{dictionary.profile}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">{dictionary.profilePage.serverSideData}</p>
<pre className="mt-2 overflow-auto rounded bg-muted p-2">{JSON.stringify(session, null, 2)}</pre>
<pre className="mt-2 max-w-[40rem] overflow-auto rounded bg-muted p-2">
{JSON.stringify(session, null, 2)}
</pre>
</CardContent>
<CardFooter>
<div className="ml-auto flex flex-row space-x-2">
Expand Down
19 changes: 18 additions & 1 deletion src/app/[lang]/(sys-auth)/providers.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
import { redirect } from "next/navigation"
import { getServerSession } from "next-auth"
import { getProviders } from "next-auth/react"
import GithubSignIn from "@/components/auth/github-sign-in"
import { nextAuthOptions } from "@/lib/auth"
import { TDictionary } from "@/lib/langs"

export default async function Providers({ dictionary }: { dictionary: TDictionary }) {
export default async function Providers({
dictionary,
searchParams,
}: {
dictionary: TDictionary
searchParams: { [key: string]: string | string[] | undefined }
}) {
const providers = await getProviders()
const session = await getServerSession(nextAuthOptions)

const callbackUrl = searchParams.callbackUrl ? searchParams.callbackUrl.toString() : undefined

//? If session and callbackUrl, redirect to callbackUrl
if (session && callbackUrl) {
redirect(callbackUrl)
}

return <>{providers?.github && <GithubSignIn provider={providers.github} dictionary={dictionary} />}</>
}
2 changes: 1 addition & 1 deletion src/app/[lang]/(sys-auth)/sign-in/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default async function SignInPage({
<span className="bg-background px-2 text-muted-foreground">{dictionary.auth.orContinueWith}</span>
</div>
</div>
<Providers dictionary={dictionary} />
<Providers dictionary={dictionary} searchParams={searchParams} />
</div>
<PrivacyAcceptance dictionary={dictionary} />
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/app/[lang]/(sys-auth)/sign-up/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default async function SignUpPage({
<span className="bg-background px-2 text-muted-foreground">{dictionary.auth.orContinueWith}</span>
</div>
</div>
<Providers dictionary={dictionary} />
<Providers dictionary={dictionary} searchParams={searchParams} />
</div>
<PrivacyAcceptance dictionary={dictionary} />
</div>
Expand Down
20 changes: 14 additions & 6 deletions src/components/auth/github-sign-in.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,27 @@ export default function GithubSignIn({
async function handleSignIn() {
setIsLoading(true)
try {
const sp = new URLSearchParams()
sp.set("redirectOnClient", authRoutes.redirectAfterSignIn)
// window.location.href = "?" + sp.toString()
const res = await signIn(provider.id, {
callbackUrl: `${window.location.origin}${authRoutes.redirectAfterSignIn}`,
})
logger.debug("SignIn result", res)

if (res?.error) {
if (res.error === "OAuthAccountNotLinked") {
} else {
throw new Error(dictionary.errors.unknownError)
if (res) {
logger.debug("SignIn result", res)
if (res.error) {
if (res.error === "OAuthAccountNotLinked") {
} else {
throw new Error(dictionary.errors.unknownError)
}
}

setIsLoading(false)
}
//? Do not setIsLoading(false) here because the user will be redirected to profile
} catch (error) {
setIsLoading(false)
logger.error(error)
if (error instanceof Error) {
toast({
Expand All @@ -48,7 +57,6 @@ export default function GithubSignIn({
})
}
}
setIsLoading(false)
}

return (
Expand Down
37 changes: 17 additions & 20 deletions src/lib/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,29 +154,26 @@ export const nextAuthOptions: NextAuthOptions & {
}

//* Verify that the session still exists
if (!token.uuid || typeof token.uuid !== "string") {
logger.debug("Missing token uuid")
return {} as Session
}

const loginSession = await prisma.session.findUnique({
where: {
sessionToken: token.uuid,
},
})
if (!loginSession) {
logger.debug("Session not found", token.uuid)
return {} as Session
} else {
//? Update session lastUsed
await prisma.session.update({
if (token.uuid) {
const loginSession = await prisma.session.findUnique({
where: {
id: loginSession.id,
},
data: {
lastUsedAt: new Date(),
sessionToken: token.uuid,
},
})
if (!loginSession) {
logger.debug("Session not found", token.uuid)
return {} as Session
} else {
//? Update session lastUsed
await prisma.session.update({
where: {
id: loginSession.id,
},
data: {
lastUsedAt: new Date(),
},
})
}
}

//* Fill session with user data
Expand Down
4 changes: 2 additions & 2 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,12 @@ export const getTimeBetween = (
}

// Function to ensure an url is relative to the current domain
export const ensureRelativeUrl = (url: string | undefined) => {
export const ensureRelativeUrl = <T extends string | undefined>(url: T) => {
if (url && url.startsWith("http")) {
const urlObject = new URL(url)
return urlObject.pathname
}
return url
return url as T
}

export const formatCouldNotMessage = async ({
Expand Down

0 comments on commit bab6312

Please sign in to comment.