Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

16.2 KB
Raw Blame
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button, Checkbox, FormField, Input, Modal, Select } from "@editor/ui";
import {
  createMember,
  fetchUsers,
  ROLE_LABEL,
  type AuthType,
} from "@processor/api/users";
import { usersBackend } from "@editor/portal/usersBackend";
import { createGrant } from "@processor/api/access";
import { errorMessage } from "@processor/api/http";
import type { Team } from "@processor/api/teams";
import { useTier } from "@processor/contexts/TierContext";
import "@processor/views/Users.css";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";

interface InviteMemberModalProps {
  open: boolean;
  onClose: () => void;
  onInvited?: () => void;
  teams: Team[];
  defaultTeamId?: number | null;
  /** Self-hosted with password login: enables the "Create account" mode. */
  canDirectCreate?: boolean;
  /** Whether "Invite by email" is offered. Off when SMTP/invites aren't configured
   * (self-hosted); always on for SaaS. */
  canEmailInvite?: boolean;
  hasOauth?: boolean;
  hasSaml?: boolean;
  /** Whether the "admin" (Org Owner) role can be assigned. Off on SaaS. */
  adminRole?: boolean;
  /** Whether portal-access grants can be created (ADMIN-only). Gates the Processor option. */
  manageGrants?: boolean;
  /** Non-blocking notice back to the parent (e.g. a deferred Processor grant). */
  onNotice?: (message: string) => void;
  /** Requested method, used only if the server supports it. Otherwise the search text
   * and available methods determine the initial selection. */
  initialMode?: "email" | "direct";
  /** Unvalidated search text, editable in either invitation method. */
  initialValue?: string;
}

type InviteRole = "member" | "admin";
type Mode = "email" | "direct";

// Values hold i18n keys; resolved with t() where the select renders.
const ROLE_SELECT_OPTIONS: { value: InviteRole; labelKey: string }[] = [
  { value: "member", labelKey: ROLE_LABEL.member },
  { value: "admin", labelKey: ROLE_LABEL.admin },
];

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const USERNAME_RE =
  /^[a-zA-Z0-9](?!.*[-@._+]{2,})[a-zA-Z0-9@._+-]{1,48}[a-zA-Z0-9]$/;
const RESERVED_USERNAMES = new Set(["all_users", "anonymoususer"]);

interface TouchedFields {
  email: boolean;
  username: boolean;
  password: boolean;
}

const UNTOUCHED_FIELDS: TouchedFields = {
  email: false,
  username: false,
  password: false,
};

export function InviteMemberModal({
  open,
  onClose,
  onInvited,
  teams,
  defaultTeamId,
  canDirectCreate = false,
  canEmailInvite = true,
  hasOauth = false,
  hasSaml = false,
  adminRole = true,
  manageGrants = false,
  onNotice,
  initialMode,
  initialValue = "",
}: InviteMemberModalProps) {
  const { t } = useTranslation();
  const { tier } = useTier();
  const [mode, setMode] = useState<Mode>("email");
  const [email, setEmail] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [authType, setAuthType] = useState<AuthType>("WEB");
  const [forceChange, setForceChange] = useState(true);
  const [forceMFA, setForceMFA] = useState(false);
  const [role, setRole] = useState<InviteRole>("member");
  const [teamId, setTeamId] = useState<string>("");
  const [processor, setProcessor] = useState(false);
  const [touched, setTouched] = useState<TouchedFields>(UNTOUCHED_FIELDS);
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  // Which add-user modes this flavor/config offers. Self-hosted offers direct create;
  // SaaS offers email; self-hosted also offers email once SMTP + invites are configured.
  const directAvailable = canDirectCreate;
  const emailAvailable = canEmailInvite;
  const preferredMode: Mode =
    emailAvailable && EMAIL_RE.test(initialValue.trim())
      ? "email"
      : directAvailable
        ? "direct"
        : "email";

  useEffect(() => {
    if (!open) return;
    // Honor an explicit initialMode only when that mode is actually available.
    const requested: Mode =
      initialMode &&
      (initialMode === "email" ? emailAvailable : directAvailable)
        ? initialMode
        : preferredMode;
    setMode(requested);
    setTeamId(
      defaultTeamId != null
        ? String(defaultTeamId)
        : teams.length > 0
          ? String(teams[0].id)
          : "",
    );
  }, [
    open,
    defaultTeamId,
    teams,
    directAvailable,
    emailAvailable,
    preferredMode,
    initialMode,
  ]);

  // A server-side submit error must not outlive the input that caused it.
  useEffect(() => {
    setSubmitError(null);
  }, [email, username, password]);

  // Drop the "admin" (Org Owner) option where it can't be assigned (SaaS).
  const roleOptions = (
    adminRole
      ? ROLE_SELECT_OPTIONS
      : ROLE_SELECT_OPTIONS.filter((o) => o.value !== "admin")
  ).map((o) => ({ value: o.value, label: t(o.labelKey) }));

  const authTypeOptions: { value: AuthType; label: string }[] = [
    { value: "WEB", label: t("users.invite.authWeb", "Password") },
    ...(hasOauth
      ? [
          {
            value: "OAUTH2" as AuthType,
            label: t("users.invite.authOauth", "OAuth2 / SSO"),
          },
        ]
      : []),
    ...(hasSaml
      ? [
          {
            value: "SAML2" as AuthType,
            label: t("users.invite.authSaml", "SAML 2.0"),
          },
        ]
      : []),
  ];

  const trimmedEmail = email.trim();
  const trimmedUsername = username.trim();
  const emailValid = EMAIL_RE.test(trimmedEmail);
  const usernameValid =
    (USERNAME_RE.test(trimmedUsername) ||
      (trimmedUsername.length <= 320 && EMAIL_RE.test(trimmedUsername))) &&
    !RESERVED_USERNAMES.has(trimmedUsername.toLowerCase());
  const needsPassword = mode === "direct" && authType === "WEB";
  const passwordValid = !needsPassword || password.length >= 6;
  const emailError =
    mode === "email" && (submitted || touched.email) && !emailValid
      ? t("users.invite.emailError", "Enter a valid email address")
      : undefined;
  const usernameError =
    mode === "direct" && (submitted || touched.username) && !usernameValid
      ? t(
          "users.invite.usernameError",
          "Enter a valid username (3-50 characters) or email address",
        )
      : undefined;
  const passwordError =
    needsPassword && (submitted || touched.password) && !passwordValid
      ? t(
          "users.invite.passwordError",
          "Password must be at least 6 characters",
        )
      : undefined;

  function touch(field: keyof TouchedFields) {
    setTouched((current) => ({ ...current, [field]: true }));
  }

  const resetTimerRef = useRef<number | null>(null);

  useEffect(() => {
    if (!open) return;
    if (resetTimerRef.current !== null)
      window.clearTimeout(resetTimerRef.current);
    setEmail(initialValue);
    setUsername(initialValue);
  }, [open, initialValue]);

  useEffect(() => {
    return () => {
      if (resetTimerRef.current !== null) {
        window.clearTimeout(resetTimerRef.current);
      }
    };
  }, []);

  function close() {
    onClose();
    // The form resets after the close animation; if the modal unmounts first,
    // the timer must not outlive it.
    resetTimerRef.current = window.setTimeout(() => {
      setEmail("");
      setUsername("");
      setPassword("");
      setAuthType("WEB");
      setForceChange(true);
      setForceMFA(false);
      setRole("member");
      setProcessor(false);
      setTouched(UNTOUCHED_FIELDS);
      setSubmitted(false);
      setSubmitError(null);
    }, 200);
  }

  // Grant Processor to the just-added user. Returns false when it couldn't be applied
  // (an email invitee usually isn't a resolvable user yet, or the grant call is denied).
  async function grantProcessor(
    match: (m: { email: string; username?: string }) => boolean,
  ): Promise<boolean> {
    const { members } = await fetchUsers(tier);
    const user = members.find(match);
    if (!user) return false;
    await createGrant({
      resourceType: "PORTAL",
      resourceId: "",
      principalType: "USER",
      principalId: Number(user.id),
      permission: "USE",
    });
    return true;
  }

  async function submit() {
    setSubmitted(true);
    setSubmitError(null);
    if (sending) return;
    const teamNum = teamId ? Number(teamId) : undefined;
    setSending(true);
    try {
      let processorApplied = true;
      if (mode === "email") {
        if (!emailValid) return;
        const result = await usersBackend.inviteMember(
          email.trim(),
          role,
          teamNum,
        );
        if (result?.error || result?.errors) {
          setSubmitError(result.error ?? result.errors ?? null);
          return;
        }
        if (processor)
          processorApplied = await grantProcessor(
            (m) => m.email === email.trim() || m.username === email.trim(),
          ).catch(() => false);
      } else {
        if (!usernameValid || !passwordValid) return;
        const created = await createMember({
          username: username.trim(),
          password: authType === "WEB" ? password : undefined,
          role,
          teamId: teamNum,
          authType,
          forceChange: authType === "WEB" && forceChange,
          forceMFA: authType === "WEB" && forceMFA,
        });
        if (processor)
          processorApplied = await grantProcessor(
            (m) => m.username === created,
          ).catch(() => false);
      }
      if (processor && !processorApplied)
        onNotice?.(
          t(
            "users.invite.processorDeferred",
            "Invite sent, but Processor access couldn't be granted yet - set it from the roster once they've joined.",
          ),
        );
      onInvited?.();
      close();
    } catch (e) {
      setSubmitError(errorMessage(e));
    } finally {
      setSending(false);
    }
  }

  return (
    <Modal
      open={open}
      onClose={close}
      width="sm"
      title={
        mode === "direct"
          ? t("users.invite.createTitle", "Create account")
          : t("users.invite.title", "Invite people")
      }
      subtitle={
        mode === "direct"
          ? t(
              "users.invite.createSubtitle",
              "Create a self-hosted account with a password or SSO.",
            )
          : t(
              "users.invite.subtitle2",
              "They'll get an email to join your Stirling workspace.",
            )
      }
      footer={
        <div className="portal-users__modal-footer">
          <Button variant="tertiary" size="sm" onClick={close}>
            {t("common.cancel", "Cancel")}
          </Button>
          <Button size="sm" onClick={() => void submit()} disabled={sending}>
            {mode === "direct"
              ? t("users.invite.create", "Create account")
              : t("users.invite.send2", "Send invite")}
          </Button>
        </div>
      }
    >
      <div className="portal-users__invite-body">
        {directAvailable && emailAvailable && (
          <FormField label={t("users.invite.method", "How to add them")}>
            <Select
              options={[
                {
                  value: "email",
                  label: t("users.invite.methodEmail", "Invite by email"),
                },
                {
                  value: "direct",
                  label: t(
                    "users.invite.methodDirect",
                    "Create account directly",
                  ),
                },
              ]}
              value={mode}
              onChange={(value) => {
                setMode((value ?? "email") as Mode);
                setSubmitted(false);
                setSubmitError(null);
              }}
            />
          </FormField>
        )}

        {mode === "email" ? (
          <FormField
            label={t("users.invite.email", "Email address")}
            error={emailError}
            required
          >
            <Input
              type="email"
              placeholder={t(
                "users.invite.emailPlaceholder2",
                "[email protected]",
              )}
              value={email}
              invalid={!!emailError}
              className={privateContentClassName}
              onChange={(e) => setEmail(e.target.value)}
              onBlur={() => touch("email")}
            />
          </FormField>
        ) : (
          <>
            <FormField
              label={t("users.invite.username", "Username")}
              error={usernameError}
              required
            >
              <Input
                placeholder={t("users.invite.usernamePlaceholder", "jsmith")}
                value={username}
                invalid={!!usernameError}
                className={privateContentClassName}
                onChange={(e) => setUsername(e.target.value)}
                onBlur={() => touch("username")}
              />
            </FormField>
            {authTypeOptions.length > 1 && (
              <FormField label={t("users.invite.authType", "Sign-in method")}>
                <Select
                  options={authTypeOptions}
                  value={authType}
                  onChange={(value) =>
                    setAuthType((value ?? "WEB") as AuthType)
                  }
                />
              </FormField>
            )}
            {authType === "WEB" && (
              <FormField
                label={t("users.invite.password", "Password")}
                error={passwordError}
                required
              >
                <Input
                  type="password"
                  value={password}
                  invalid={!!passwordError}
                  onChange={(e) => setPassword(e.target.value)}
                  onBlur={() => touch("password")}
                />
              </FormField>
            )}
          </>
        )}

        <div className="portal-users__invite-grid">
          <FormField label={t("users.invite.role", "Role")}>
            <Select
              options={roleOptions}
              value={role}
              onChange={(value) => setRole((value ?? "member") as InviteRole)}
            />
          </FormField>
          <FormField label={t("users.invite.team", "Team")}>
            <Select
              options={teams.map((tm) => ({
                value: String(tm.id),
                label: tm.name,
              }))}
              value={teamId}
              onChange={(value) => setTeamId(value ?? "")}
            />
          </FormField>
        </div>

        {mode === "direct" && (
          <div className="portal-users__invite-access">
            {authType === "WEB" && (
              <Checkbox
                checked={forceChange}
                onChange={(e) => setForceChange(e.target.checked)}
                label={t(
                  "users.invite.forceChange",
                  "Require a password change on first login",
                )}
              />
            )}
            {authType === "WEB" && (
              <Checkbox
                checked={forceMFA}
                onChange={(e) => setForceMFA(e.target.checked)}
                label={t(
                  "users.invite.forceMfa",
                  "Require MFA setup on first login",
                )}
              />
            )}
          </div>
        )}

        <div className="portal-users__invite-access">
          <span className="portal-users__invite-access-label">
            {t("users.invite.access", "Access")}
          </span>
          <Checkbox
            checked
            disabled
            label={t("users.cap.editor", "Editor")}
            description={t(
              "users.invite.editorDesc",
              "Edit PDFs in the Stirling PDF Editor. Everyone gets this.",
            )}
          />
          {manageGrants && (
            <Checkbox
              checked={processor}
              onChange={(e) => setProcessor(e.target.checked)}
              label={t("users.cap.processor", "Processor")}
              description={t(
                "users.invite.processorDesc",
                "The governance surface, run pipelines, agents, and the API.",
              )}
            />
          )}
        </div>
        {submitError && (
          <p className="portal-users__error" role="alert">
            {submitError}
          </p>
        )}
      </div>
    </Modal>
  );
}