feat: add from redirect for auth (#18)

* feat: add from redirect for auth

* fix: add missing import
This commit is contained in:
Andrew Ellis 2022-11-15 00:12:01 -07:00 committed by GitHub
parent fc9a1ab8df
commit 8f13cb8195
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 2 deletions

View file

@ -1,6 +1,7 @@
"use client"
import * as React from "react"
import { useSearchParams } from "next/navigation"
import { signIn } from "next-auth/react"
import * as z from "zod"
import { useForm } from "react-hook-form"
@ -24,6 +25,7 @@ export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
resolver: zodResolver(userAuthSchema),
})
const [isLoading, setIsLoading] = React.useState<boolean>(false)
const searchParams = useSearchParams();
async function onSubmit(data: FormData) {
setIsLoading(true)
@ -31,7 +33,7 @@ export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
const signInResult = await signIn("email", {
email: data.email.toLowerCase(),
redirect: false,
callbackUrl: `${window.location.origin}/dashboard`,
callbackUrl: searchParams.get("from") || "/dashboard",
})
setIsLoading(false)

View file

@ -19,7 +19,14 @@ export default withAuth(
}
if (!isAuth) {
return NextResponse.redirect(new URL("/login", req.url))
let from = req.nextUrl.pathname;
if (req.nextUrl.search) {
from += req.nextUrl.search;
}
return NextResponse.redirect(
new URL(`/login?from=${encodeURIComponent(from)}`, req.url)
);
}
},
{