Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Add user support for changing auth methods
Tuan Dangab43e32982a7
diff --git a/backend/src/controllers/v2/usersController.ts b/backend/src/controllers/v2/usersController.tsindex b5849f2e79..0c78d76675 100644--- a/backend/src/controllers/v2/usersController.ts+++ b/backend/src/controllers/v2/usersController.ts@@ -81,25 +81,62 @@ export const updateMyMfaEnabled = async (req: Request, res: Response) => {}/**- * Update the current user's name [firstName, lastName].+ * Update name of the current user to [firstName, lastName].* @param req* @param res* @returns*/export const updateName = async (req: Request, res: Response) => {- const { firstName, lastName }: { firstName: string; lastName: string; } = req.body;- req.user.firstName = firstName;- req.user.lastName = lastName || "";+ const {+ firstName,+ lastName+ }: {+ firstName: string;+ lastName: string;+ } = req.body;- await req.user.save();-- const user = req.user;+ const user = await User.findByIdAndUpdate(+ req.user._id.toString(),+ {+ firstName,+ lastName: lastName ?? ""+ },+ {+ new: true+ }+ );return res.status(200).send({user,});}+/**+ * Update auth provider of the current user to [authProvider]+ * @param req+ * @param res+ * @returns+ */+export const updateAuthProvider = async (req: Request, res: Response) => {+ const {+ authProvider+ } = req.body;++ const user = await User.findByIdAndUpdate(+ req.user._id.toString(),+ {+ authProvider+ },+ {+ new: true+ }+ );++ return res.status(200).send({+ user+ });+}+/*** Return organizations that the current user is part of.* @param reqdiff --git a/backend/src/controllers/v3/authController.ts b/backend/src/controllers/v3/authController.tsindex 7a70f171c1..7cb3cfd971 100644--- a/backend/src/controllers/v3/authController.ts+++ b/backend/src/controllers/v3/authController.ts@@ -56,7 +56,7 @@ export const login1 = async (req: Request, res: Response) => {if (!user) throw new Error("Failed to find user");- if (user.authProvider) {+ if (user.authProvider && user.authProvider !== AuthProvider.EMAIL) {await validateProviderAuthToken({email,user,@@ -117,7 +117,7 @@ export const login2 = async (req: Request, res: Response) => {if (!user) throw new Error("Failed to find user");- if (user.authProvider) {+ if (user.authProvider && user.authProvider !== AuthProvider.EMAIL) {await validateProviderAuthToken({email,user,diff --git a/backend/src/models/user.ts b/backend/src/models/user.tsindex 68f2965c6b..6559b1b7e7 100644--- a/backend/src/models/user.ts+++ b/backend/src/models/user.ts@@ -1,6 +1,7 @@import { Document, Schema, Types, model } from "mongoose";export enum AuthProvider {+ EMAIL = "email",GOOGLE = "google",OKTA_SAML = "okta-saml"}diff --git a/backend/src/routes/v2/users.ts b/backend/src/routes/v2/users.tsindex 7815513ec7..ca27d5b579 100644--- a/backend/src/routes/v2/users.ts+++ b/backend/src/routes/v2/users.ts@@ -10,6 +10,9 @@ import {AUTH_MODE_API_KEY,AUTH_MODE_JWT,} from "../../variables";+import {+ AuthProvider+} from "../../models";router.get("/me",@@ -34,11 +37,25 @@ router.patch(requireAuth({acceptedAuthModes: [AUTH_MODE_JWT, AUTH_MODE_API_KEY],}),- body("firstName").exists(),+ body("firstName").exists().isString(),+ body("lastName").isString(),validateRequest,usersController.updateName);+router.patch(+ "/me/auth-provider",+ requireAuth({+ acceptedAuthModes: [AUTH_MODE_JWT, AUTH_MODE_API_KEY],+ }),+ body("authProvider").exists().isString().isIn([+ AuthProvider.EMAIL,+ AuthProvider.GOOGLE+ ]),+ validateRequest,+ usersController.updateAuthProvider+);+router.get("/me/organizations",requireAuth({diff --git a/frontend/public/locales/en/translations.json b/frontend/public/locales/en/translations.jsonindex e4c671ca4f..a70a7dd8b3 100644--- a/frontend/public/locales/en/translations.json+++ b/frontend/public/locales/en/translations.json@@ -227,7 +227,7 @@},"password": {"password": "Password",- "change": "Change password",+ "change": "Change Password","current": "Current password","current-wrong": "The current password may be wrong","new": "New password",diff --git a/frontend/src/hooks/api/users/index.tsx b/frontend/src/hooks/api/users/index.tsxindex e1e530443d..0c00810e5e 100644--- a/frontend/src/hooks/api/users/index.tsx+++ b/frontend/src/hooks/api/users/index.tsx@@ -13,4 +13,6 @@ export {useLogoutUser,useRegisterUserAction,useRevokeMySessions,- useUpdateOrgUserRole} from "./queries";+ useUpdateOrgUserRole,+ useUpdateUserAuthProvider+} from "./queries";diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsxindex fe9efd73f5..19504217e1 100644--- a/frontend/src/hooks/api/users/queries.tsx+++ b/frontend/src/hooks/api/users/queries.tsx@@ -58,6 +58,27 @@ export const useRenameUser = () => {});};+export const useUpdateUserAuthProvider = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async ({+ authProvider+ }: {+ authProvider: string;+ }) => {+ const { data: { user } } = await apiRequest.patch("/api/v2/users/me/auth-provider", {+ authProvider+ });++ return user;+ },+ onSuccess: () => {+ queryClient.invalidateQueries(userKeys.getUser);+ }+ });+};+export const useGetUserAction = (action: string) =>useQuery({queryKey: userKeys.userAction,diff --git a/frontend/src/hooks/api/users/types.ts b/frontend/src/hooks/api/users/types.tsindex 31a33c756d..0c312b2b6a 100644--- a/frontend/src/hooks/api/users/types.ts+++ b/frontend/src/hooks/api/users/types.ts@@ -1,11 +1,18 @@import { UserWsKeyPair } from "../keys/types";+export enum AuthProvider {+ EMAIL = "email",+ GOOGLE = "google",+ OKTA_SAML = "okta-saml"+}+export type User = {createdAt: Date;updatedAt: Date;email?: string;firstName?: string;lastName?: string;+ authProvider?: AuthProvider;encryptionVersion?: number;protectedKey?: string;protectedKeyIV?: string;diff --git a/frontend/src/views/Login/components/InitialStep/InitialStep.tsx b/frontend/src/views/Login/components/InitialStep/InitialStep.tsxindex 86a6c4b5ee..abc6adf566 100644--- a/frontend/src/views/Login/components/InitialStep/InitialStep.tsx+++ b/frontend/src/views/Login/components/InitialStep/InitialStep.tsx@@ -2,8 +2,8 @@ import { FormEvent, useState } from "react";import { useTranslation } from "react-i18next";import Link from "next/link";import { useRouter } from "next/router";-// import { faGoogle } from "@fortawesome/free-brands-svg-icons";-// import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { faGoogle } from "@fortawesome/free-brands-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import axios from "axios"import Error from "@app/components/basic/Error";@@ -159,7 +159,7 @@ export const InitialStep = ({<span className='px-4 text-sm text-bunker-400'>or</span><div className='w-1/2 border-t border-mineshaft-500' /></div>- {/* <div className='lg:w-1/6 w-1/4 min-w-[20rem] rounded-md'>+ <div className='lg:w-1/6 w-1/4 min-w-[20rem] rounded-md'><ButtoncolorSchema="primary"variant="solid"@@ -172,7 +172,7 @@ export const InitialStep = ({>{t("login.continue-with-google")}</Button>- </div> */}+ </div><div className='lg:w-1/6 w-1/4 min-w-[20rem] text-center rounded-md mt-4'><ButtoncolorSchema="primary"diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsxindex 8173267887..73213db31f 100644--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsx+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgAuthTab/OrgSSOSection.tsx@@ -26,7 +26,7 @@ export const OrgSSOSection = (): JSX.Element => {"upgradePlan","addSSO"] as const);-+const handleSamlSSOToggle = async (value: boolean) => {try {if (!currentOrg?._id) return;@@ -53,7 +53,7 @@ export const OrgSSOSection = (): JSX.Element => {<div className="p-4 bg-mineshaft-900 mb-6 rounded-lg border border-mineshaft-600"><div className="flex items-center mb-8"><h2 className="text-xl font-semibold flex-1 text-white">- Configuration+ SAML SSO Configuration</h2>{!isLoading && (<Buttondiff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgTabGroup/OrgTabGroup.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgTabGroup/OrgTabGroup.tsxindex b955b9faa1..1d0ebeb65d 100644--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgTabGroup/OrgTabGroup.tsx+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgTabGroup/OrgTabGroup.tsx@@ -24,7 +24,7 @@ export const OrgTabGroup = () => {if (isRoleSufficient) {tabs.push(- { name: "SAML SSO", key: "tab-org-saml" }+ { name: "Authentication", key: "tab-org-auth" });}diff --git a/frontend/src/views/Settings/PersonalSettingsPage/AuthMethodSection/AuthMethodSection.tsx b/frontend/src/views/Settings/PersonalSettingsPage/AuthMethodSection/AuthMethodSection.tsxnew file mode 100644index 0000000000..7ca84318d5--- /dev/null+++ b/frontend/src/views/Settings/PersonalSettingsPage/AuthMethodSection/AuthMethodSection.tsx@@ -0,0 +1,132 @@+import { useEffect } from "react";+import { Controller, useForm } from "react-hook-form";+import { yupResolver } from "@hookform/resolvers/yup";+import * as yup from "yup";++import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";+import {+ Button,+ FormControl,+ Select,+ SelectItem} from "@app/components/v2";+import { useUser } from "@app/context";+import {+ useUpdateUserAuthProvider+} from "@app/hooks/api";++const authMethods = [+ { label: "Email", value: "email" },+ { label: "Google SSO", value: "google" },+ { label: "Okta SAML 2.0", value: "okta-saml" },+];++const schema = yup.object({+ authMethod: yup.string().required("Auth method is required")+});++export type FormData = yup.InferType<typeof schema>;++export const AuthMethodSection = () => {+ const { createNotification } = useNotificationContext();+ const { user } = useUser();+ const { mutateAsync, isLoading } = useUpdateUserAuthProvider();++ const {+ reset,+ control,+ handleSubmit+ } = useForm<FormData>({+ defaultValues: {+ authMethod: user?.authProvider ?? "email"+ },+ resolver: yupResolver(schema)+ });++ useEffect(() => {+ if (user) {+ reset({+ authMethod: user?.authProvider ?? "email"+ });+ }+ }, [user]);++ const onFormSubmit = async ({+ authMethod+ }: FormData) => {+ try {+ if (authMethod === "okta-saml") {+ createNotification({+ text: "Okta SAML 2.0 can only be configured in your organization settings",+ type: "error"+ });++ return;+ }++ await mutateAsync({+ authProvider: authMethod+ });++ createNotification({+ text: "Successfully updated authentication method",+ type: "success"+ });+ } catch (err) {+ console.error(err);+ createNotification({+ text: "Failed to update authentication method",+ type: "error"+ });+ }+ }++ return (+ <form+ className="p-4 bg-mineshaft-900 mb-6 rounded-lg border border-mineshaft-600"+ onSubmit={handleSubmit(onFormSubmit)}+ >+ <h2 className="text-xl font-semibold flex-1 text-mineshaft-100 mb-8">+ Authentication Method+ </h2>+ <div className="max-w-md mb-4">+ <Controller+ control={control}+ name="authMethod"+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (+ <FormControl+ className="mb-0"+ errorText={error?.message}+ isError={Boolean(error)}+ >+ <Select+ defaultValue={field.value}+ {...field}+ onValueChange={(e) => onChange(e)}+ className="w-full"+ >+ {authMethods.map((authMethod) => {+ return (+ <SelectItem+ value={authMethod.value}+ key={`auth-method-${authMethod.value}`}+ >+ {authMethod.label}+ </SelectItem>+ );+ })}+ </Select>+ </FormControl>+ )}+ />+ </div>+ <Button+ type="submit"+ colorSchema="secondary"+ isLoading={isLoading}+ isDisabled={isLoading}+ >+ Save+ </Button>+ </form>+ );+}\ No newline at end of filediff --git a/frontend/src/views/Settings/PersonalSettingsPage/AuthMethodSection/index.tsx b/frontend/src/views/Settings/PersonalSettingsPage/AuthMethodSection/index.tsxnew file mode 100644index 0000000000..12540cbb40--- /dev/null+++ b/frontend/src/views/Settings/PersonalSettingsPage/AuthMethodSection/index.tsx@@ -0,0 +1 @@+export { AuthMethodSection } from "./AuthMethodSection";\ No newline at end of filediff --git a/frontend/src/views/Settings/PersonalSettingsPage/PersonalAuthTab/PersonalAuthTab.tsx b/frontend/src/views/Settings/PersonalSettingsPage/PersonalAuthTab/PersonalAuthTab.tsxnew file mode 100644index 0000000000..73f04113ee--- /dev/null+++ b/frontend/src/views/Settings/PersonalSettingsPage/PersonalAuthTab/PersonalAuthTab.tsx@@ -0,0 +1,13 @@+import { AuthMethodSection } from "../AuthMethodSection";+import { ChangePasswordSection } from "../ChangePasswordSection";+import { MFASection } from "../SecuritySection";++export const PersonalAuthTab = () => {+ return (+ <div>+ <MFASection />+ <AuthMethodSection />+ <ChangePasswordSection />+ </div>+ );+}\ No newline at end of filediff --git a/frontend/src/views/Settings/PersonalSettingsPage/PersonalAuthTab/index.tsx b/frontend/src/views/Settings/PersonalSettingsPage/PersonalAuthTab/index.tsxnew file mode 100644index 0000000000..4ab3d0b6ef--- /dev/null+++ b/frontend/src/views/Settings/PersonalSettingsPage/PersonalAuthTab/index.tsx@@ -0,0 +1 @@+export { PersonalAuthTab } from "./PersonalAuthTab";\ No newline at end of filediff --git a/frontend/src/views/Settings/PersonalSettingsPage/PersonalSecurityTab/PersonalSecurityTab.tsx b/frontend/src/views/Settings/PersonalSettingsPage/PersonalGeneralTab/PersonalGeneralTab.tsxsimilarity index 64%rename from frontend/src/views/Settings/PersonalSettingsPage/PersonalSecurityTab/PersonalSecurityTab.tsxrename to frontend/src/views/Settings/PersonalSettingsPage/PersonalGeneralTab/PersonalGeneralTab.tsxindex abfec566a0..531776751a 100644--- a/frontend/src/views/Settings/PersonalSettingsPage/PersonalSecurityTab/PersonalSecurityTab.tsx+++ b/frontend/src/views/Settings/PersonalSettingsPage/PersonalGeneralTab/PersonalGeneralTab.tsx@@ -1,18 +1,14 @@import { ChangeLanguageSection } from "../ChangeLanguageSection";-import { ChangePasswordSection } from "../ChangePasswordSection";import { EmergencyKitSection } from "../EmergencyKitSection";-import { SecuritySection } from "../SecuritySection";import { SessionsSection } from "../SessionsSection";import { UserNameSection } from "../UserNameSection";-export const PersonalSecurityTab = () => {+export const PersonalGeneralTab = () => {return (<div><UserNameSection /><ChangeLanguageSection />- <SecuritySection /><SessionsSection />- <ChangePasswordSection /><EmergencyKitSection /></div>);diff --git a/frontend/src/views/Settings/PersonalSettingsPage/PersonalGeneralTab/index.tsx b/frontend/src/views/Settings/PersonalSettingsPage/PersonalGeneralTab/index.tsxnew file mode 100644index 0000000000..1a83f1b889--- /dev/null+++ b/frontend/src/views/Settings/PersonalSettingsPage/PersonalGeneralTab/index.tsx@@ -0,0 +1 @@+export { PersonalGeneralTab } from "./PersonalGeneralTab";\ No newline at end of filediff --git a/frontend/src/views/Settings/PersonalSettingsPage/PersonalSecurityTab/index.tsx b/frontend/src/views/Settings/PersonalSettingsPage/PersonalSecurityTab/index.tsxdeleted file mode 100644index e9d5025cb5..0000000000--- a/frontend/src/views/Settings/PersonalSettingsPage/PersonalSecurityTab/index.tsx+++ /dev/null@@ -1 +0,0 @@-export { PersonalSecurityTab } from "./PersonalSecurityTab";\ No newline at end of filediff --git a/frontend/src/views/Settings/PersonalSettingsPage/PersonalTabGroup/PersonalTabGroup.tsx b/frontend/src/views/Settings/PersonalSettingsPage/PersonalTabGroup/PersonalTabGroup.tsxindex 6f3edef97a..f2e367b360 100644--- a/frontend/src/views/Settings/PersonalSettingsPage/PersonalTabGroup/PersonalTabGroup.tsx+++ b/frontend/src/views/Settings/PersonalSettingsPage/PersonalTabGroup/PersonalTabGroup.tsx@@ -2,10 +2,12 @@ import { Fragment } from "react"import { Tab } from "@headlessui/react"import { PersonalAPIKeyTab } from "../PersonalAPIKeyTab";-import { PersonalSecurityTab } from "../PersonalSecurityTab";+import { PersonalAuthTab } from "../PersonalAuthTab";+import { PersonalGeneralTab } from "../PersonalGeneralTab";const tabs = [- { name: "General", key: "tab-account-security" },+ { name: "General", key: "tab-account-general" },+ { name: "Authentication", key: "tab-account-auth" },{ name: "API Keys", key: "tab-account-api-keys" }];@@ -28,7 +30,10 @@ export const PersonalTabGroup = () => {</Tab.List><Tab.Panels><Tab.Panel>- <PersonalSecurityTab />+ <PersonalGeneralTab />+ </Tab.Panel>+ <Tab.Panel>+ <PersonalAuthTab /></Tab.Panel><Tab.Panel><PersonalAPIKeyTab />diff --git a/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/SecuritySection.tsx b/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/MFASection.tsxsimilarity index 98%rename from frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/SecuritySection.tsxrename to frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/MFASection.tsxindex 4f23cbf083..8f9b36db74 100644--- a/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/SecuritySection.tsx+++ b/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/MFASection.tsx@@ -9,7 +9,7 @@ import { useGetUser } from "../../../../hooks/api";import { User } from "../../../../hooks/api/types";import updateMyMfaEnabled from "../../../../pages/api/user/updateMyMfaEnabled";-export const SecuritySection = () => {+export const MFASection = () => {const [isMfaEnabled, setIsMfaEnabled] = useState(false);const { data: user } = useGetUser();const { createNotification } = useNotificationContext();diff --git a/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/index.tsx b/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/index.tsxindex b360c0b4b1..981ac6d5c7 100644--- a/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/index.tsx+++ b/frontend/src/views/Settings/PersonalSettingsPage/SecuritySection/index.tsx@@ -1 +1 @@-export { SecuritySection } from "./SecuritySection";\ No newline at end of file+export { MFASection } from "./MFASection";\ No newline at end of filediff --git a/frontend/src/views/Settings/PersonalSettingsPage/UserNameSection/UserNameSection.tsx b/frontend/src/views/Settings/PersonalSettingsPage/UserNameSection/UserNameSection.tsxindex bf03877a8e..722112bf9b 100644--- a/frontend/src/views/Settings/PersonalSettingsPage/UserNameSection/UserNameSection.tsx+++ b/frontend/src/views/Settings/PersonalSettingsPage/UserNameSection/UserNameSection.tsx@@ -55,7 +55,7 @@ export const UserNameSection = (): JSX.Element => {className="p-4 bg-mineshaft-900 mb-6 rounded-lg border border-mineshaft-600"><p className="text-xl font-semibold text-mineshaft-100 mb-4">- User name+ Name</p><div className="mb-2 max-w-md"><Controller