From cdaafec4e6a0afb3314a090069ea2ad3f7eda484 Mon Sep 17 00:00:00 2001 From: m5r Date: Sun, 15 May 2022 18:33:19 +0200 Subject: [PATCH] redirect on `requireLoggedIn()` --- app/utils/auth.server.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/app/utils/auth.server.ts b/app/utils/auth.server.ts index 01522b0..b941a35 100644 --- a/app/utils/auth.server.ts +++ b/app/utils/auth.server.ts @@ -1,4 +1,4 @@ -import { type Session, redirect } from "@remix-run/node"; +import { redirect, type Session } from "@remix-run/node"; import type { FormStrategyVerifyParams } from "remix-auth-form"; import SecurePassword from "secure-password"; import type { MembershipRole, Organization, User } from "@prisma/client"; @@ -9,7 +9,9 @@ import authenticator from "./authenticator.server"; import { AuthenticationError } from "./errors"; import { commitSession, destroySession, getSession } from "./session.server"; -export type SessionOrganization = Pick & { role: MembershipRole }; +export type SessionOrganization = Pick & { + role: MembershipRole; +}; export type SessionUser = Omit & { organizations: SessionOrganization[]; }; @@ -134,8 +136,11 @@ export async function requireLoggedOut(request: Request) { export async function requireLoggedIn(request: Request) { const user = await authenticator.isAuthenticated(request); + const signInUrl = new URL("/sign-in"); + const redirectTo = buildRedirectTo(new URL(request.url)); + signInUrl.searchParams.set("redirectTo", redirectTo); if (!user) { - throw redirect("/sign-in", { + throw redirect(signInUrl.toString(), { headers: { "Set-Cookie": await destroySession(await getSession(request)) }, }); } @@ -143,6 +148,16 @@ export async function requireLoggedIn(request: Request) { return user; } +function buildRedirectTo(url: URL): string { + let redirectTo = url.pathname; + const searchParams = url.searchParams.toString(); + if (searchParams.length > 0) { + redirectTo += `?${searchParams}`; + } + + return encodeURIComponent(redirectTo); +} + export async function refreshSessionData(request: Request) { const { id } = await requireLoggedIn(request); const user = await db.user.findUnique({