Merge branch 'dev' into aig

This commit is contained in:
Owen
2026-08-12 16:34:52 -04:00
9 changed files with 128 additions and 21 deletions
+2
View File
@@ -43,6 +43,8 @@
"inviteLoginUser": "Please make sure you're logged in as the correct user.", "inviteLoginUser": "Please make sure you're logged in as the correct user.",
"inviteErrorNoUser": "We're sorry, but it looks like the invite you're trying to access is not for a user that exists.", "inviteErrorNoUser": "We're sorry, but it looks like the invite you're trying to access is not for a user that exists.",
"inviteCreateUser": "Please create an account first.", "inviteCreateUser": "Please create an account first.",
"inviteErrorOidcNotAllowed": "Invites can only be accepted by internal accounts. Sign out and log in with your password for this email.",
"inviteLoginInternalOnly": "Invites require an internal account with a password. Create an account or sign in with your password.",
"goHome": "Go Home", "goHome": "Go Home",
"inviteLogInOtherUser": "Log In as a Different User", "inviteLogInOtherUser": "Log In as a Different User",
"createAnAccount": "Create an Account", "createAnAccount": "Create an Account",
+2 -1
View File
@@ -1,8 +1,9 @@
import { db, idp, idpOrg, Transaction } from "@server/db"; import { db, idp, idpOrg, Transaction } from "@server/db";
import { and, eq } from "drizzle-orm"; import { and, eq } from "drizzle-orm";
import { build } from "@server/build";
export function isOrgIdentityProviderMode(): boolean { export function isOrgIdentityProviderMode(): boolean {
return process.env.IDENTITY_PROVIDER_MODE === "org"; return build === "saas" || process.env.IDENTITY_PROVIDER_MODE === "org";
} }
/** /**
+24 -10
View File
@@ -22,6 +22,7 @@ import { calculateUserClientsForOrgs } from "@server/lib/calculateUserClientsFor
import { build } from "@server/build"; import { build } from "@server/build";
import { assignUserToOrg } from "@server/lib/userOrg"; import { assignUserToOrg } from "@server/lib/userOrg";
import { isOrgRebuildRateLimited } from "@server/lib/rebuildClientAssociations"; import { isOrgRebuildRateLimited } from "@server/lib/rebuildClientAssociations";
import { UserType } from "@server/types/UserTypes";
const acceptInviteBodySchema = z.strictObject({ const acceptInviteBodySchema = z.strictObject({
token: z.string(), token: z.string(),
@@ -66,12 +67,17 @@ export async function acceptInvite(
); );
} }
const existingUser = await db const [existingInternalUser] = await db
.select() .select()
.from(users) .from(users)
.where(eq(users.email, existingInvite.email)) .where(
and(
eq(users.email, existingInvite.email),
eq(users.type, UserType.Internal)
)
)
.limit(1); .limit(1);
if (!existingUser.length) { if (!existingInternalUser) {
return next( return next(
createHttpError( createHttpError(
HttpCode.BAD_REQUEST, HttpCode.BAD_REQUEST,
@@ -80,9 +86,8 @@ export async function acceptInvite(
); );
} }
const { user, session } = await verifySession(req); const { user } = await verifySession(req);
// at this point we know the user exists
if (!user) { if (!user) {
return next( return next(
createHttpError( createHttpError(
@@ -92,7 +97,7 @@ export async function acceptInvite(
); );
} }
if (user && user.email !== existingInvite.email) { if (user.email !== existingInvite.email) {
return next( return next(
createHttpError( createHttpError(
HttpCode.BAD_REQUEST, HttpCode.BAD_REQUEST,
@@ -101,6 +106,15 @@ export async function acceptInvite(
); );
} }
if (user.type !== UserType.Internal) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invites can only be accepted by internal users."
)
);
}
if (build == "saas") { if (build == "saas") {
const usage = await usageService.getUsage( const usage = await usageService.getUsage(
existingInvite.orgId, existingInvite.orgId,
@@ -195,7 +209,7 @@ export async function acceptInvite(
await assignUserToOrg( await assignUserToOrg(
org, org,
{ {
userId: existingUser[0].userId, userId: user.userId,
orgId: existingInvite.orgId orgId: existingInvite.orgId
}, },
inviteRoleIds, inviteRoleIds,
@@ -208,13 +222,13 @@ export async function acceptInvite(
.where(eq(userInvites.inviteId, inviteId)); .where(eq(userInvites.inviteId, inviteId));
logger.debug( logger.debug(
`User ${existingUser[0].userId} accepted invite to org ${existingInvite.orgId}` `User ${user.userId} accepted invite to org ${existingInvite.orgId}`
); );
}); });
calculateUserClientsForOrgs(existingUser[0].userId).catch((e) => { calculateUserClientsForOrgs(user.userId).catch((e) => {
logger.error( logger.error(
`Failed to calculate user clients after accepting invite for user ${existingUser[0].userId}: ${e}` `Failed to calculate user clients after accepting invite for user ${user.userId}: ${e}`
); );
}); });
+11
View File
@@ -20,6 +20,7 @@ import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
import { assignUserToOrg } from "@server/lib/userOrg"; import { assignUserToOrg } from "@server/lib/userOrg";
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed"; import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
import { isOrgRebuildRateLimited } from "@server/lib/rebuildClientAssociations"; import { isOrgRebuildRateLimited } from "@server/lib/rebuildClientAssociations";
import { idpExistsForOrg } from "@server/lib/idp/idpExistsForOrg";
const paramsSchema = z.strictObject({ const paramsSchema = z.strictObject({
orgId: z.string().nonempty() orgId: z.string().nonempty()
@@ -239,6 +240,16 @@ export async function createOrgUser(
); );
} }
const providerExists = await idpExistsForOrg(idpId, orgId);
if (!providerExists) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Identity provider not found in this organization"
)
);
}
const [idpRes] = await db const [idpRes] = await db
.select() .select()
.from(idp) .from(idp)
@@ -237,10 +237,13 @@ export default function Page() {
return; return;
} }
const useOrgIdps =
build === "saas" || env.app.identityProviderMode === "org";
const res = await api const res = await api
.get< .get<
AxiosResponse<ListIdpsResponse> AxiosResponse<ListIdpsResponse>
>(build === "saas" ? `/org/${orgId}/idp` : "/idp") >(useOrgIdps ? `/org/${orgId}/idp` : "/idp")
.catch((e) => { .catch((e) => {
console.error(e); console.error(e);
toast({ toast({
@@ -301,8 +304,7 @@ export default function Page() {
); );
const [isSubmittingExternal, setIsSubmittingExternal] = useState(false); const [isSubmittingExternal, setIsSubmittingExternal] = useState(false);
const loading = const loading = isSubmittingInternal || isSubmittingExternal;
isSubmittingInternal || isSubmittingExternal;
async function onSubmitInternal() { async function onSubmitInternal() {
const isValid = await internalForm.trigger(); const isValid = await internalForm.trigger();
+5 -2
View File
@@ -193,7 +193,10 @@ export default async function Page(props: {
redirect={redirectUrl} redirect={redirectUrl}
forceLogin={forceLogin} forceLogin={forceLogin}
defaultUser={defaultUser} defaultUser={defaultUser}
lastUsedIdp={lastUsedIdpForSmartLogin} inviteMode={isInvite}
lastUsedIdp={
isInvite ? null : lastUsedIdpForSmartLogin
}
orgSignIn={ orgSignIn={
!isInvite && !isInvite &&
(build === "saas" || (build === "saas" ||
@@ -213,7 +216,7 @@ export default async function Page(props: {
) : ( ) : (
<DashboardLoginForm <DashboardLoginForm
redirect={redirectUrl} redirect={redirectUrl}
idps={loginIdps} idps={isInvite ? [] : loginIdps}
forceLogin={forceLogin} forceLogin={forceLogin}
showOrgLogin={ showOrgLogin={
!isInvite && !isInvite &&
+19
View File
@@ -44,6 +44,7 @@ export default function InviteStatusCard({
| "user_does_not_exist" | "user_does_not_exist"
| "not_logged_in" | "not_logged_in"
| "user_limit_exceeded" | "user_limit_exceeded"
| "oidc_not_allowed"
>("rejected"); >("rejected");
useEffect(() => { useEffect(() => {
@@ -69,6 +70,12 @@ export default function InviteStatusCard({
function cardType() { function cardType() {
if (error.includes("Invite is not for this user")) { if (error.includes("Invite is not for this user")) {
return "wrong_user"; return "wrong_user";
} else if (
error.includes(
"Invites can only be accepted by internal users."
)
) {
return "oidc_not_allowed";
} else if ( } else if (
error.includes( error.includes(
"User does not exist. Please create an account first." "User does not exist. Please create an account first."
@@ -166,6 +173,14 @@ export default function InviteStatusCard({
<p className="text-center">{t("inviteCreateUser")}</p> <p className="text-center">{t("inviteCreateUser")}</p>
</div> </div>
); );
} else if (type === "oidc_not_allowed") {
return (
<div>
<p className="text-center mb-4">
{t("inviteErrorOidcNotAllowed")}
</p>
</div>
);
} else if (type === "user_limit_exceeded") { } else if (type === "user_limit_exceeded") {
return ( return (
<div> <div>
@@ -199,6 +214,10 @@ export default function InviteStatusCard({
); );
} else if (type === "user_does_not_exist") { } else if (type === "user_does_not_exist") {
return <Button onClick={goToSignup}>{t("createAnAccount")}</Button>; return <Button onClick={goToSignup}>{t("createAnAccount")}</Button>;
} else if (type === "oidc_not_allowed") {
return (
<Button onClick={goToLogin}>{t("inviteLogInOtherUser")}</Button>
);
} else if (type === "user_limit_exceeded") { } else if (type === "user_limit_exceeded") {
return ( return (
<Button <Button
+33 -4
View File
@@ -56,6 +56,7 @@ type SmartLoginFormProps = {
defaultUser?: string; defaultUser?: string;
orgSignIn?: OrgSignInConfig; orgSignIn?: OrgSignInConfig;
lastUsedIdp?: (LoginFormIDP & { orgId?: string }) | null; lastUsedIdp?: (LoginFormIDP & { orgId?: string }) | null;
inviteMode?: boolean;
}; };
type ViewState = type ViewState =
@@ -93,7 +94,8 @@ export default function SmartLoginForm({
forceLogin, forceLogin,
defaultUser, defaultUser,
orgSignIn, orgSignIn,
lastUsedIdp lastUsedIdp,
inviteMode = false
}: SmartLoginFormProps) { }: SmartLoginFormProps) {
const router = useRouter(); const router = useRouter();
const { env } = useEnvContext(); const { env } = useEnvContext();
@@ -136,6 +138,10 @@ export default function SmartLoginForm({
return; return;
} }
const signupUrl = redirect
? `/auth/signup?email=${encodeURIComponent(identifier)}&redirect=${encodeURIComponent(redirect)}&fromSmartLogin=true`
: `/auth/signup?email=${encodeURIComponent(identifier)}&fromSmartLogin=true`;
if (!result.found || result.accounts.length === 0) { if (!result.found || result.accounts.length === 0) {
// No accounts found // No accounts found
if (!isEmail || forceLogin) { if (!isEmail || forceLogin) {
@@ -147,13 +153,36 @@ export default function SmartLoginForm({
return; return;
} }
// Valid email but no accounts and not forceLogin - redirect to signup // Valid email but no accounts and not forceLogin - redirect to signup
const signupUrl = redirect
? `/auth/signup?email=${encodeURIComponent(identifier)}&redirect=${encodeURIComponent(redirect)}&fromSmartLogin=true`
: `/auth/signup?email=${encodeURIComponent(identifier)}&fromSmartLogin=true`;
router.push(signupUrl); router.push(signupUrl);
return; return;
} }
// Invite accept only supports internal (password) accounts
if (inviteMode) {
const internalAccount = result.accounts.find(
(acc) => acc.hasInternalAuth
);
if (internalAccount) {
setViewState({
type: "password",
identifier,
account: internalAccount
});
return;
}
if (isEmail && !forceLogin) {
router.push(signupUrl);
return;
}
form.setError("identifier", {
type: "manual",
message: t("inviteLoginInternalOnly")
});
return;
}
// Determine which view to show // Determine which view to show
const account = result.accounts[0]; // Use first account for now const account = result.accounts[0]; // Use first account for now
@@ -15,11 +15,14 @@ import {
} from "@app/components/ui/popover"; } from "@app/components/ui/popover";
import { cn } from "@app/lib/cn"; import { cn } from "@app/lib/cn";
import { ListUserOrgsResponse } from "@server/routers/org"; import { ListUserOrgsResponse } from "@server/routers/org";
import { Check, ChevronDown, ChevronsUpDown } from "lucide-react"; import { Check, ChevronDown, Plus } from "lucide-react";
import { usePathname, useRouter } from "next/navigation"; import { usePathname, useRouter } from "next/navigation";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useUserContext } from "@app/hooks/useUserContext";
import { build } from "@server/build";
type LauncherOrgSelectorProps = { type LauncherOrgSelectorProps = {
orgId?: string; orgId?: string;
@@ -31,9 +34,16 @@ export function LauncherOrgSelector({ orgId, orgs }: LauncherOrgSelectorProps) {
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
const t = useTranslations(); const t = useTranslations();
const { env } = useEnvContext();
const { user } = useUserContext();
const selectedOrg = orgs?.find((org) => org.orgId === orgId); const selectedOrg = orgs?.find((org) => org.orgId === orgId);
let canCreateOrg = !env.flags.disableUserCreateOrg || user.serverAdmin;
if (build === "saas" && user.type !== "internal") {
canCreateOrg = false;
}
const sortedOrgs = useMemo(() => { const sortedOrgs = useMemo(() => {
if (!orgs?.length) { if (!orgs?.length) {
return orgs ?? []; return orgs ?? [];
@@ -108,6 +118,22 @@ export function LauncherOrgSelector({ orgId, orgs }: LauncherOrgSelectorProps) {
</CommandGroup> </CommandGroup>
</CommandList> </CommandList>
</Command> </Command>
{canCreateOrg && (
<div className="p-2 border-t border-border">
<Button
variant="ghost"
size="sm"
className="w-full justify-start h-8 font-normal text-muted-foreground"
onClick={() => {
setOpen(false);
router.push("/setup");
}}
>
<Plus className="h-3.5 w-3.5 mr-2" />
{t("setupNewOrg")}
</Button>
</div>
)}
</PopoverContent> </PopoverContent>
</Popover> </Popover>
); );