|
| 1 | +import type { LoaderFunctionArgs } from "@remix-run/server-runtime"; |
| 2 | +import { redirect } from "remix-typedjson"; |
| 3 | +import { $replica } from "~/db.server"; |
| 4 | +import { clearImpersonation, redirectWithImpersonation } from "~/models/admin.server"; |
| 5 | +import { logger } from "~/services/logger.server"; |
| 6 | +import { requireUser } from "~/services/session.server"; |
| 7 | + |
| 8 | +export async function loader({ request, params }: LoaderFunctionArgs) { |
| 9 | + const user = await requireUser(request); |
| 10 | + if (!user.admin) { |
| 11 | + return redirect("/"); |
| 12 | + } |
| 13 | + |
| 14 | + const path = params["*"]; |
| 15 | + const organizationSlug = params.organizationSlug; |
| 16 | + |
| 17 | + logger.debug("Impersonating user", { path, organizationSlug }); |
| 18 | + |
| 19 | + if (!organizationSlug) { |
| 20 | + logger.debug("Exiting impersonation mode"); |
| 21 | + return clearImpersonation(request, "/admin"); |
| 22 | + } |
| 23 | + |
| 24 | + const org = await $replica.organization.findFirst({ |
| 25 | + where: { |
| 26 | + slug: organizationSlug, |
| 27 | + deletedAt: null, |
| 28 | + }, |
| 29 | + select: { |
| 30 | + members: { |
| 31 | + select: { |
| 32 | + user: { |
| 33 | + select: { |
| 34 | + id: true, |
| 35 | + confirmedBasicDetails: true, |
| 36 | + }, |
| 37 | + }, |
| 38 | + }, |
| 39 | + }, |
| 40 | + }, |
| 41 | + }); |
| 42 | + |
| 43 | + if (!org) { |
| 44 | + logger.debug("Organization not found", { organizationSlug }); |
| 45 | + return clearImpersonation(request, "/admin"); |
| 46 | + } |
| 47 | + |
| 48 | + const firstValidMember = org.members.find((m) => m.user.confirmedBasicDetails); |
| 49 | + |
| 50 | + if (!firstValidMember) { |
| 51 | + logger.debug("No valid members found", { organizationSlug }); |
| 52 | + return clearImpersonation(request, "/admin"); |
| 53 | + } |
| 54 | + |
| 55 | + return redirectWithImpersonation( |
| 56 | + request, |
| 57 | + firstValidMember.user.id, |
| 58 | + `/orgs/${organizationSlug}/${path}` |
| 59 | + ); |
| 60 | +} |
0 commit comments