Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+30
-164
@@ -1,168 +1,34 @@
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { UserWithDetails, getUserByEmail, getUserByEmailWithDetails } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
type LoaderData = {
|
||||
user: UserWithDetails;
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const user = await getUserByEmailWithDetails(params.user!);
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
user,
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const user = await getUserByEmail(params.user);
|
||||
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "set-user-roles") {
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
let setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
setRoles = setRoles.filter((v, i, a) => a.findIndex((t) => t.role.id === v.role.id) === i);
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const countAdmins = await db.adminUser.count();
|
||||
if (!isAdmin && countAdmins === 1) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveLastAdmin") }, { status: 400 });
|
||||
}
|
||||
const hasSuperAdmin = setRoles.some((r) => r.role.name === DefaultAdminRoles.SuperAdmin);
|
||||
if (user.id === userInfo.userId && !hasSuperAdmin) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveOwnSuperAdmin") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
// return Response.json({ success: t("shared.updated") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>(data.user.roles?.filter((f) => f.role.type === "admin").map((r) => r.role.id));
|
||||
|
||||
function hasSomeAdminRoles() {
|
||||
return data.adminRoles.some((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
function hasAllAdminRoles() {
|
||||
return data.adminRoles.every((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="set-user-roles" hidden readOnly />
|
||||
{selectedRoles?.map((role, idx) => {
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="border-border flex items-center justify-between space-x-2 border-b pb-2">
|
||||
<div className="text-foreground/80 text-lg font-medium">{t("models.role.plural")}</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonSecondary disabled={!hasSomeAdminRoles()} onClick={() => setSelectedRoles([])}>
|
||||
{t("shared.clear")}
|
||||
</ButtonSecondary>
|
||||
|
||||
<ButtonSecondary disabled={hasAllAdminRoles()} onClick={() => setSelectedRoles(data.adminRoles.map((r) => r.id))}>
|
||||
{t("shared.selectAll")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-1 rounded-md shadow-2xs">
|
||||
{data.adminRoles?.map((role, idx) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={idx}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
<ActionResultModal actionData={actionData ?? undefined} />
|
||||
</div>
|
||||
async function redirectToDedicatedAdminIdentity(request: Request, email: string | undefined) {
|
||||
const adminUser = email
|
||||
? await runAsAdminIdentity(request, "admin_identity.users.manage", () =>
|
||||
db.adminUser.findFirst({
|
||||
where: { email: { equals: email, mode: "insensitive" } },
|
||||
select: { id: true },
|
||||
})
|
||||
)
|
||||
: null;
|
||||
throw redirect(
|
||||
adminPath(adminUser ? `settings/admin-users/${adminUser.id}` : "accounts/users", {
|
||||
mode: "host-aware",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return redirectToDedicatedAdminIdentity(request, params.user);
|
||||
}
|
||||
|
||||
export function action({ request, params }: ActionFunctionArgs) {
|
||||
return redirectToDedicatedAdminIdentity(request, params.user);
|
||||
}
|
||||
|
||||
export default function LegacyAdminUserRolesRedirect() {
|
||||
return null;
|
||||
}
|
||||
+16
-173
@@ -1,179 +1,22 @@
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const data: LoaderData = {
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
async function redirectToAuthentikAdminUsers(request: Request) {
|
||||
await requireAdminIdentityPermission(request, "admin_identity.users.manage");
|
||||
throw redirect(adminPath("settings/admin-users", { mode: "host-aware" }), 303);
|
||||
}
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
export function loader({ request }: LoaderFunctionArgs) {
|
||||
return redirectToAuthentikAdminUsers(request);
|
||||
}
|
||||
|
||||
if (action === "new-user") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const email = form.get("email")?.toString();
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString();
|
||||
const password = form.get("password")?.toString();
|
||||
export function action({ request }: ActionFunctionArgs) {
|
||||
return redirectToAuthentikAdminUsers(request);
|
||||
}
|
||||
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!email || !password || !firstName) {
|
||||
return Response.json({ error: t("admin.users.create.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
// if (arrRoles.length === 0) {
|
||||
// return Response.json({ error: "You must select at least one role." }, { status: 400 });
|
||||
// }
|
||||
|
||||
const existingUser = await getUserByEmail(email);
|
||||
if (existingUser) {
|
||||
return Response.json({ error: t("admin.users.create.errors.userAlreadyExists") }, { status: 400 });
|
||||
}
|
||||
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
const setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const { id } = await register({
|
||||
email,
|
||||
firstName,
|
||||
lastName: lastName ?? "",
|
||||
password,
|
||||
request,
|
||||
});
|
||||
const user = await getUser(id);
|
||||
if (!user) {
|
||||
return Response.json({ error: t("admin.users.create.errors.unexpectedCreateError") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [email, setEmail] = useState<string>("");
|
||||
const [password, setPassword] = useState<string>("");
|
||||
const [firstName, setFirstName] = useState<string>("");
|
||||
const [lastName, setLastName] = useState<string>("");
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="new-user" hidden readOnly />
|
||||
{selectedRoles?.map((role) => {
|
||||
return (
|
||||
<input
|
||||
key={role}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputText autoFocus type="email" name="email" title={t("models.user.email")} value={email} setValue={setEmail} required />
|
||||
|
||||
<InputText type="password" name="password" title={t("account.shared.password")} value={password} setValue={setPassword} required />
|
||||
|
||||
<InputText name="firstName" title={t("models.user.firstName")} value={firstName} setValue={setFirstName} required />
|
||||
|
||||
<InputText name="lastName" title={t("models.user.lastName")} value={lastName} setValue={setLastName} />
|
||||
|
||||
<div>
|
||||
<label className="mb-1 flex justify-between space-x-2 truncate text-xs font-medium">{t("models.role.plural")}</label>
|
||||
<div className="border-border bg-background divide-border divide-y rounded-md border px-2 py-1">
|
||||
{data.adminRoles?.map((role) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={role.name}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
export default function LegacyAdminUserCreationRedirect() {
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user