From 48bb9d112106cf5b3cc1ee4403ac5aac84cb694e Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Wed, 13 Mar 2024 19:23:29 -0400 Subject: [PATCH] refactor: handle redirects from ?to after login, or when already logged in --- app/data/auth-provider.ts | 10 +++++++++- app/routes/login.tsx | 20 +++++++++++++++----- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/app/data/auth-provider.ts b/app/data/auth-provider.ts index 65f659d..39c798b 100644 --- a/app/data/auth-provider.ts +++ b/app/data/auth-provider.ts @@ -9,6 +9,7 @@ export type AuthFormRequest = { email: string; password: string; rememberMe: boolean; + redirectTo?: string; } export type RegisterFormRequest = { @@ -48,12 +49,19 @@ export class PortalAuthProvider implements RequiredAuthProvider { password: params.password, }) + let redirectTo:string | undefined; + if (ret) { cookies.set('jwt', this.sdk.account().jwtToken, { path: '/' }); + redirectTo = params.redirectTo; + if (!redirectTo) { + redirectTo = ret ? "/dashboard" : "/login"; + } } + return { success: ret, - redirectTo: ret ? "/dashboard" : undefined, + redirectTo, }; } diff --git a/app/routes/login.tsx b/app/routes/login.tsx index 2ceb5e4..9556d66 100644 --- a/app/routes/login.tsx +++ b/app/routes/login.tsx @@ -9,7 +9,7 @@ import lumeBgPng from "~/images/lume-bg-image.png?url" import {Field, FieldCheckbox} from "~/components/forms" import {getFormProps, useForm} from "@conform-to/react" import {getZodConstraint, parseWithZod} from "@conform-to/zod" -import {useGo, useIsAuthenticated, useLogin} from "@refinedev/core"; +import {useGo, useIsAuthenticated, useLogin, useParsed} from "@refinedev/core"; import {AuthFormRequest} from "~/data/auth-provider.js"; import {useEffect} from "react"; @@ -20,17 +20,26 @@ export const meta: MetaFunction = () => { ] } +type LoginParams = { + to: string; +} + export default function Login() { const location = useLocation() const {isLoading: isAuthLoading, data: authData} = useIsAuthenticated(); - const auth = useIsAuthenticated(); const hash = location.hash const go = useGo(); + const parsed = useParsed() useEffect(() => { if (!isAuthLoading) { if (authData?.authenticated) { - go({to: "/dashboard", type: "replace"}); + let to = "/dashboard"; + if(parsed.params?.to){ + to = parsed.params.to + } + + go({to, type: "push"}); } } }, [isAuthLoading, authData]); @@ -89,7 +98,7 @@ const LoginSchema = z.object({ const LoginForm = () => { const login = useLogin() - + const parsed = useParsed() const [form, fields] = useForm({ id: "login", constraint: getZodConstraint(LoginSchema), @@ -104,7 +113,8 @@ const LoginForm = () => { login.mutate({ email: data.email.toString(), password: data.password.toString(), - rememberMe: data.rememberMe.toString() === "on" + rememberMe: data.rememberMe.toString() === "on", + redirectTo: parsed.params?.to }); } })