@webiny/cognito 6.5.4-beta.0 → 6.5.4-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Cognito.js.map +1 -1
- package/admin/presentation/Cognito/CognitoLoginScreen.js.map +1 -1
- package/admin/presentation/Cognito/CognitoPresenter.test.js.map +1 -1
- package/admin/presentation/users/ResetMfa/ResetMfaPresenter.test.js.map +1 -1
- package/admin/presentation/users/UserForm/UserFormPresenter.js.map +1 -1
- package/admin/presentation/users/UserForm/UserFormPresenter.test.js.map +1 -1
- package/admin/routes.js.map +1 -1
- package/admin/ui/views/Users/UsersDataList.js.map +1 -1
- package/admin/ui/views/Users/search.js +18 -17
- package/admin/ui/views/Users/search.js.map +1 -1
- package/api/features/CognitoService/CognitoService.js.map +1 -1
- package/api/features/CognitoService/adminDeleteSoftwareToken.js.map +1 -1
- package/api/features/CognitoService/adminDeleteSoftwareToken.test.js.map +1 -1
- package/api/features/UpdateUser/UpdateUserUseCase.js.map +1 -1
- package/package.json +20 -20
- /package/static/svg/{search.43fa797c.svg → search.f9a0a1d6.svg} +0 -0
package/Cognito.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Cognito.js","sources":["../src/Cognito.tsx"],"sourcesContent":["import React from \"react\";\nimport { defineExtension } from \"@webiny/project/defineExtension/index.js\";\nimport { Api, Admin, Infra } from \"@webiny/project-aws\";\nimport { Await } from \"@webiny/react-properties\";\nimport { z } from \"zod\";\n\nconst identityProviderSchema = z.object({\n type: z.enum([\"google\", \"facebook\", \"amazon\", \"apple\", \"oidc\"]),\n name: z.string().optional(),\n label: z.string(),\n providerDetails: z.record(z.string(), z.any()),\n idpIdentifiers: z.array(z.string()).optional(),\n attributeMapping: z.record(z.string(), z.string()).optional()\n});\n\nconst federationSchema = z.object({\n domain: z.string().describe(\"Cognito User Pool domain prefix.\"),\n callbackUrls: z.array(z.string()).describe(\"OAuth callback URLs.\"),\n logoutUrls: z.array(z.string()).optional(),\n responseType: z.enum([\"code\", \"token\"]).default(\"code\"),\n allowCredentialsLogin: z.boolean().default(true),\n identityProviders: z.array(identityProviderSchema)\n});\n\nexport const Cognito = defineExtension({\n type: \"Project/Cognito\",\n tags: { runtimeContext: \"project\" },\n description: \"Enable and configure Cognito authentication.\",\n paramsSchema: z.object({\n apiConfig: z.string().describe(\"Path to API configuration.\").optional(),\n adminConfig: z.string().describe(\"Path to Admin configuration.\").optional(),\n federation: z\n .union([\n federationSchema,\n z.custom<() => Promise<z.infer<typeof federationSchema>>>(\n val => typeof val === \"function\"\n )\n ])\n .optional(),\n mfa: z.boolean().describe(\"Enable TOTP MFA for all users.\").default(false)\n }),\n render: props => {\n const federationProp = props.federation;\n const federationFn = federationProp\n ? typeof federationProp === \"function\"\n ? federationProp\n : () => Promise.resolve(federationProp)\n : null;\n\n return (\n <>\n <Infra.EnvVar varName={\"REACT_APP_IDP_TYPE\"} value={\"cognito\"} />\n {props.mfa ? <Infra.EnvVar varName={\"COGNITO_MFA\"} value={\"true\"} /> : null}\n\n {/* Api extensions */}\n <Api.Extension\n src={import.meta.dirname + \"/api/CognitoApiFeature.js\"}\n exportName={\"CognitoApiFeature\"}\n />\n {props.apiConfig ? <Api.Extension src={props.apiConfig} /> : null}\n\n {/* Admin extensions */}\n <Admin.Extension src={import.meta.dirname + \"/admin/Extension.js\"} />\n {props.adminConfig ? <Admin.Extension src={props.adminConfig} /> : null}\n\n {/* Federation infra + admin config */}\n {federationFn ? (\n <Await fn={federationFn}>\n {federation => (\n <>\n <Admin.Extension\n src={import.meta.dirname + \"/admin/SignInExtension.js\"}\n exportName={\"SignInExtension\"}\n />\n <Infra.EnvVar\n varName={\"COGNITO_FEDERATION_INFRA_CONFIG\"}\n value={JSON.stringify({\n domain: federation.domain,\n callbackUrls: federation.callbackUrls,\n logoutUrls: federation.logoutUrls,\n identityProviders: federation.identityProviders.map(\n idp => ({\n type: idp.type,\n name: idp.name,\n providerDetails: idp.providerDetails,\n idpIdentifiers: idp.idpIdentifiers,\n attributeMapping: idp.attributeMapping\n })\n )\n })}\n />\n <Infra.Core.Pulumi\n src={import.meta.dirname + \"/infra/CognitoFederationPulumi.js\"}\n />\n <Admin.BuildParam\n paramName={\"cognitoFederation\"}\n value={{\n callbackUrls: federation.callbackUrls,\n logoutUrls:\n federation.logoutUrls || federation.callbackUrls,\n responseType: federation.responseType,\n allowCredentialsLogin: federation.allowCredentialsLogin,\n providers: federation.identityProviders.map(idp => ({\n name: idp.name || idp.type,\n label: idp.label\n }))\n }}\n />\n </>\n )}\n </Await>\n ) : null}\n </>\n );\n }\n});\n"],"names":["identityProviderSchema","z","federationSchema","Cognito","defineExtension","val","props","federationProp","federationFn","Promise","Infra","Api","Admin","Await","federation","JSON","idp"],"mappings":";;;;;AAMA,MAAMA,yBAAyBC,EAAE,MAAM,CAAC;IACpC,MAAMA,CAAC,CAADA,OAAM,CAAC;QAAC;QAAU;QAAY;QAAU;QAAS;KAAO;IAC9D,MAAMA,EAAE,MAAM,GAAG,QAAQ;IACzB,OAAOA,EAAE,MAAM;IACf,iBAAiBA,EAAE,MAAM,CAACA,EAAE,MAAM,IAAIA,EAAE,GAAG;IAC3C,gBAAgBA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ;IAC5C,kBAAkBA,EAAE,MAAM,CAACA,EAAE,MAAM,IAAIA,EAAE,MAAM,IAAI,QAAQ;AAC/D;AAEA,MAAMC,mBAAmBD,EAAE,MAAM,CAAC;IAC9B,QAAQA,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC5B,cAAcA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ,CAAC;IAC3C,YAAYA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ;IACxC,cAAcA,CAAC,CAADA,OAAM,CAAC;QAAC;QAAQ;KAAQ,EAAE,OAAO,CAAC;IAChD,uBAAuBA,EAAE,OAAO,GAAG,OAAO,CAAC;IAC3C,mBAAmB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MAAM,MAAM;gBACT,SAAS;gBACT,OAAOK,KAAK,SAAS,CAAC;oBAClB,QAAQD,WAAW,MAAM;oBACzB,cAAcA,WAAW,YAAY;oBACrC,YAAYA,WAAW,UAAU;oBACjC,mBAAmBA,WAAW,iBAAiB,CAAC,GAAG,CAC/CE,CAAAA,MAAQ;4BACJ,MAAMA,IAAI,IAAI;4BACd,MAAMA,IAAI,IAAI;4BACd,iBAAiBA,IAAI,eAAe;4BACpC,gBAAgBA,IAAI,cAAc;4BAClC,kBAAkBA,IAAI,gBAAgB;wBAC1C;
|
|
1
|
+
{"version":3,"file":"Cognito.js","sources":["../src/Cognito.tsx"],"sourcesContent":["import React from \"react\";\nimport { defineExtension } from \"@webiny/project/defineExtension/index.js\";\nimport { Api, Admin, Infra } from \"@webiny/project-aws\";\nimport { Await } from \"@webiny/react-properties\";\nimport { z } from \"zod\";\n\nconst identityProviderSchema = z.object({\n type: z.enum([\"google\", \"facebook\", \"amazon\", \"apple\", \"oidc\"]),\n name: z.string().optional(),\n label: z.string(),\n providerDetails: z.record(z.string(), z.any()),\n idpIdentifiers: z.array(z.string()).optional(),\n attributeMapping: z.record(z.string(), z.string()).optional()\n});\n\nconst federationSchema = z.object({\n domain: z.string().describe(\"Cognito User Pool domain prefix.\"),\n callbackUrls: z.array(z.string()).describe(\"OAuth callback URLs.\"),\n logoutUrls: z.array(z.string()).optional(),\n responseType: z.enum([\"code\", \"token\"]).default(\"code\"),\n allowCredentialsLogin: z.boolean().default(true),\n identityProviders: z.array(identityProviderSchema)\n});\n\nexport const Cognito = defineExtension({\n type: \"Project/Cognito\",\n tags: { runtimeContext: \"project\" },\n description: \"Enable and configure Cognito authentication.\",\n paramsSchema: z.object({\n apiConfig: z.string().describe(\"Path to API configuration.\").optional(),\n adminConfig: z.string().describe(\"Path to Admin configuration.\").optional(),\n federation: z\n .union([\n federationSchema,\n z.custom<() => Promise<z.infer<typeof federationSchema>>>(\n val => typeof val === \"function\"\n )\n ])\n .optional(),\n mfa: z.boolean().describe(\"Enable TOTP MFA for all users.\").default(false)\n }),\n render: props => {\n const federationProp = props.federation;\n const federationFn = federationProp\n ? typeof federationProp === \"function\"\n ? federationProp\n : () => Promise.resolve(federationProp)\n : null;\n\n return (\n <>\n <Infra.EnvVar varName={\"REACT_APP_IDP_TYPE\"} value={\"cognito\"} />\n {props.mfa ? <Infra.EnvVar varName={\"COGNITO_MFA\"} value={\"true\"} /> : null}\n\n {/* Api extensions */}\n <Api.Extension\n src={import.meta.dirname + \"/api/CognitoApiFeature.js\"}\n exportName={\"CognitoApiFeature\"}\n />\n {props.apiConfig ? <Api.Extension src={props.apiConfig} /> : null}\n\n {/* Admin extensions */}\n <Admin.Extension src={import.meta.dirname + \"/admin/Extension.js\"} />\n {props.adminConfig ? <Admin.Extension src={props.adminConfig} /> : null}\n\n {/* Federation infra + admin config */}\n {federationFn ? (\n <Await fn={federationFn}>\n {federation => (\n <>\n <Admin.Extension\n src={import.meta.dirname + \"/admin/SignInExtension.js\"}\n exportName={\"SignInExtension\"}\n />\n <Infra.EnvVar\n varName={\"COGNITO_FEDERATION_INFRA_CONFIG\"}\n value={JSON.stringify({\n domain: federation.domain,\n callbackUrls: federation.callbackUrls,\n logoutUrls: federation.logoutUrls,\n identityProviders: federation.identityProviders.map(\n idp => ({\n type: idp.type,\n name: idp.name,\n providerDetails: idp.providerDetails,\n idpIdentifiers: idp.idpIdentifiers,\n attributeMapping: idp.attributeMapping\n })\n )\n })}\n />\n <Infra.Core.Pulumi\n src={import.meta.dirname + \"/infra/CognitoFederationPulumi.js\"}\n />\n <Admin.BuildParam\n paramName={\"cognitoFederation\"}\n value={{\n callbackUrls: federation.callbackUrls,\n logoutUrls:\n federation.logoutUrls || federation.callbackUrls,\n responseType: federation.responseType,\n allowCredentialsLogin: federation.allowCredentialsLogin,\n providers: federation.identityProviders.map(idp => ({\n name: idp.name || idp.type,\n label: idp.label\n }))\n }}\n />\n </>\n )}\n </Await>\n ) : null}\n </>\n );\n }\n});\n"],"names":["identityProviderSchema","z","federationSchema","Cognito","defineExtension","val","props","federationProp","federationFn","Promise","Infra","Api","Admin","Await","federation","JSON","idp"],"mappings":";;;;;AAMA,MAAMA,yBAAyBC,EAAE,MAAM,CAAC;IACpC,MAAMA,CAAC,CAADA,OAAM,CAAC;QAAC;QAAU;QAAY;QAAU;QAAS;KAAO;IAC9D,MAAMA,EAAE,MAAM,GAAG,QAAQ;IACzB,OAAOA,EAAE,MAAM;IACf,iBAAiBA,EAAE,MAAM,CAACA,EAAE,MAAM,IAAIA,EAAE,GAAG;IAC3C,gBAAgBA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ;IAC5C,kBAAkBA,EAAE,MAAM,CAACA,EAAE,MAAM,IAAIA,EAAE,MAAM,IAAI,QAAQ;AAC/D;AAEA,MAAMC,mBAAmBD,EAAE,MAAM,CAAC;IAC9B,QAAQA,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC5B,cAAcA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ,CAAC;IAC3C,YAAYA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ;IACxC,cAAcA,CAAC,CAADA,OAAM,CAAC;QAAC;QAAQ;KAAQ,EAAE,OAAO,CAAC;IAChD,uBAAuBA,EAAE,OAAO,GAAG,OAAO,CAAC;IAC3C,mBAAmBA,EAAE,KAAK,CAACD;AAC/B;AAEO,MAAMG,UAAUC,gBAAgB;IACnC,MAAM;IACN,MAAM;QAAE,gBAAgB;IAAU;IAClC,aAAa;IACb,cAAcH,EAAE,MAAM,CAAC;QACnB,WAAWA,EAAE,MAAM,GAAG,QAAQ,CAAC,8BAA8B,QAAQ;QACrE,aAAaA,EAAE,MAAM,GAAG,QAAQ,CAAC,gCAAgC,QAAQ;QACzE,YAAYA,EAAAA,KACF,CAAC;YACHC;YACAD,EAAE,MAAM,CACJI,CAAAA,MAAO,AAAe,cAAf,OAAOA;SAErB,EACA,QAAQ;QACb,KAAKJ,EAAE,OA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AAM;gBACd,KAAK,YAAY,OAAO,GAAG;8BAE/B,oBAACE,MAAM,UAAU;gBACb,WAAW;gBACX,OAAO;oBACH,cAAcE,WAAW,YAAY;oBACrC,YACIA,WAAW,UAAU,IAAIA,WAAW,YAAY;oBACpD,cAAcA,WAAW,YAAY;oBACrC,uBAAuBA,WAAW,qBAAqB;oBACvD,WAAWA,WAAW,iBAAiB,CAAC,GAAG,CAACE,CAAAA,MAAQ;4BAChD,MAAMA,IAAI,IAAI,IAAIA,IAAI,IAAI;4BAC1B,OAAOA,IAAI,KAAK;wBACpB,CAAC;gBACL;mBAKhB;IAGhB;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin/presentation/Cognito/CognitoLoginScreen.js","sources":["../../../../src/admin/presentation/Cognito/CognitoLoginScreen.tsx"],"sourcesContent":["import React, { useEffect } from \"react\";\nimport { observer } from \"mobx-react-lite\";\nimport { useFeature } from \"@webiny/app\";\nimport { OverlayLoader } from \"@webiny/admin-ui\";\nimport { CognitoFeature } from \"./feature.js\";\nimport { SignIn } from \"./components/SignIn.js\";\nimport { RequireNewPassword } from \"./components/RequireNewPassword.js\";\nimport { RequestPasswordResetCode } from \"./components/RequestPasswordResetCode.js\";\nimport { SetNewPassword } from \"./components/SetNewPassword.js\";\nimport { PasswordResetCodeSent } from \"~/admin/presentation/Cognito/components/PasswordResetCodeSent.js\";\nimport { ConfirmTotpCode } from \"./components/ConfirmTotpCode.js\";\nimport { SetupTotp } from \"./components/SetupTotp.js\";\nimport { SelectTenant } from \"./components/SelectTenant.js\";\nimport { NoTenantAccess } from \"./components/NoTenantAccess.js\";\n\nexport interface CognitoLoginScreenProps {\n region: string;\n userPoolId: string;\n clientId: string;\n children: React.ReactNode;\n}\n\nexport const CognitoLoginScreen = observer((props: CognitoLoginScreenProps) => {\n const { presenter } = useFeature(CognitoFeature);\n\n useEffect(() => {\n presenter.init({\n region: props.region,\n userPoolId: props.userPoolId,\n clientId: props.clientId\n });\n }, []);\n\n const vm = presenter.vm;\n\n if (vm.isAuthenticated) {\n return <>{props.children}</>;\n }\n\n return (\n <>\n {vm.isLoggingIn ? <OverlayLoader text={\"Signing in...\"} /> : null}\n {vm.checkingSession ? <OverlayLoader text={\"Checking session...\"} /> : null}\n\n {!vm.isLoggingIn && !vm.checkingSession ? (\n <>\n {vm.authState === \"requireNewPassword\" && (\n <RequireNewPassword\n vm={vm.requireNewPassword}\n onSubmit={(password, attributes) =>\n presenter.confirmNewPassword(password, attributes)\n }\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"requestPasswordResetCode\" && (\n <RequestPasswordResetCode\n vm={vm.requestPasswordResetCode}\n onRequestCode={username => presenter.requestPasswordReset(username)}\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"passwordResetCodeSent\" && (\n <PasswordResetCodeSent\n vm={vm.passwordResetCodeSent}\n onResendCode={() => presenter.resendPasswordResetCode()}\n onCodeAcquired={() => presenter.showSetNewPassword()}\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"setNewPassword\" && (\n <SetNewPassword\n vm={vm.setNewPassword}\n onSetNewPassword={(code, password) =>\n presenter.confirmPasswordReset(code, password)\n }\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"confirmTotpCode\" && (\n <ConfirmTotpCode\n vm={vm.confirmTotpCode}\n onSubmit={code => presenter.confirmTotpCode(code)}\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"setupTotp\" && (\n <SetupTotp\n vm={vm.setupTotp}\n onSubmit={code => presenter.verifyTotpSetup(code)}\n />\n )}\n\n {vm.authState === \"selectTenant\" ? (\n <SelectTenant\n vm={vm.selectTenant}\n onSelect={tenantId => presenter.selectTenant(tenantId)}\n onSignOut={() => presenter.signOut()}\n />\n ) : null}\n\n {vm.authState === \"noTenantAccess\" ? (\n <NoTenantAccess onSignOut={() => presenter.signOut()} />\n ) : null}\n\n {(vm.authState === \"signIn\" || vm.authState === \"signedOut\") && (\n <SignIn\n vm={vm.signIn}\n onSubmit={(username, password) => presenter.signIn(username, password)}\n onForgotPassword={() => presenter.showRequestPasswordResetCode()}\n />\n )}\n </>\n ) : null}\n </>\n );\n});\n"],"names":["CognitoLoginScreen","observer","props","presenter","useFeature","CognitoFeature","useEffect","vm","OverlayLoader","RequireNewPassword","password","attributes","RequestPasswordResetCode","username","PasswordResetCodeSent","SetNewPassword","code","ConfirmTotpCode","SetupTotp","SelectTenant","tenantId","NoTenantAccess","SignIn"],"mappings":";;;;;;;;;;;;;;AAsBO,MAAMA,qBAAqBC,SAAS,CAACC;IACxC,MAAM,EAAEC,SAAS,EAAE,GAAGC,WAAWC;IAEjCC,UAAU;QACNH,UAAU,IAAI,CAAC;YACX,QAAQD,MAAM,MAAM;YACpB,YAAYA,MAAM,UAAU;YAC5B,UAAUA,MAAM,QAAQ;QAC5B;IACJ,GAAG,EAAE;IAEL,MAAMK,KAAKJ,UAAU,EAAE;IAEvB,IAAII,GAAG,eAAe,EAClB,OAAO,WAAP,GAAO,0CAAGL,MAAM,QAAQ;IAG5B,OAAO,WAAP,GACI,0CACKK,GAAG,WAAW,GAAG,WAAH,GAAG,oBAACC,eAAaA;QAAC,MAAM;SAAsB,MAC5DD,GAAG,eAAe,GAAG,WAAH,GAAG,oBAACC,eAAaA;QAAC,MAAM;SAA4B,MAEtE,AAACD,GAAG,WAAW,IAAKA,GAAG,eAAe,GA0EnC,OA1EsC,WAAH,GACnC,0CACKA,AAAiB,yBAAjBA,GAAG,SAAS,IAA6B,WAAxB,GACd,oBAACE,oBAAkBA;QACf,IAAIF,GAAG,kBAAkB;QACzB,UAAU,CAACG,UAAUC,aACjBR,UAAU,kBAAkB,CAACO,UAAUC;QAE3C,UAAU,IAAMR,UAAU,UAAU;QAI3CI,AAAiB,+BAAjBA,GAAG,SAAS,IAAmC,WAA9B,GACd,oBAACK,0BAAwBA;QACrB,IAAIL,GAAG,wBAAwB;QAC/B,eAAe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ation/Cognito/CognitoLoginScreen.tsx"],"sourcesContent":["import React, { useEffect } from \"react\";\nimport { observer } from \"mobx-react-lite\";\nimport { useFeature } from \"@webiny/app\";\nimport { OverlayLoader } from \"@webiny/admin-ui\";\nimport { CognitoFeature } from \"./feature.js\";\nimport { SignIn } from \"./components/SignIn.js\";\nimport { RequireNewPassword } from \"./components/RequireNewPassword.js\";\nimport { RequestPasswordResetCode } from \"./components/RequestPasswordResetCode.js\";\nimport { SetNewPassword } from \"./components/SetNewPassword.js\";\nimport { PasswordResetCodeSent } from \"~/admin/presentation/Cognito/components/PasswordResetCodeSent.js\";\nimport { ConfirmTotpCode } from \"./components/ConfirmTotpCode.js\";\nimport { SetupTotp } from \"./components/SetupTotp.js\";\nimport { SelectTenant } from \"./components/SelectTenant.js\";\nimport { NoTenantAccess } from \"./components/NoTenantAccess.js\";\n\nexport interface CognitoLoginScreenProps {\n region: string;\n userPoolId: string;\n clientId: string;\n children: React.ReactNode;\n}\n\nexport const CognitoLoginScreen = observer((props: CognitoLoginScreenProps) => {\n const { presenter } = useFeature(CognitoFeature);\n\n useEffect(() => {\n presenter.init({\n region: props.region,\n userPoolId: props.userPoolId,\n clientId: props.clientId\n });\n }, []);\n\n const vm = presenter.vm;\n\n if (vm.isAuthenticated) {\n return <>{props.children}</>;\n }\n\n return (\n <>\n {vm.isLoggingIn ? <OverlayLoader text={\"Signing in...\"} /> : null}\n {vm.checkingSession ? <OverlayLoader text={\"Checking session...\"} /> : null}\n\n {!vm.isLoggingIn && !vm.checkingSession ? (\n <>\n {vm.authState === \"requireNewPassword\" && (\n <RequireNewPassword\n vm={vm.requireNewPassword}\n onSubmit={(password, attributes) =>\n presenter.confirmNewPassword(password, attributes)\n }\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"requestPasswordResetCode\" && (\n <RequestPasswordResetCode\n vm={vm.requestPasswordResetCode}\n onRequestCode={username => presenter.requestPasswordReset(username)}\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"passwordResetCodeSent\" && (\n <PasswordResetCodeSent\n vm={vm.passwordResetCodeSent}\n onResendCode={() => presenter.resendPasswordResetCode()}\n onCodeAcquired={() => presenter.showSetNewPassword()}\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"setNewPassword\" && (\n <SetNewPassword\n vm={vm.setNewPassword}\n onSetNewPassword={(code, password) =>\n presenter.confirmPasswordReset(code, password)\n }\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"confirmTotpCode\" && (\n <ConfirmTotpCode\n vm={vm.confirmTotpCode}\n onSubmit={code => presenter.confirmTotpCode(code)}\n onCancel={() => presenter.showSignIn()}\n />\n )}\n\n {vm.authState === \"setupTotp\" && (\n <SetupTotp\n vm={vm.setupTotp}\n onSubmit={code => presenter.verifyTotpSetup(code)}\n />\n )}\n\n {vm.authState === \"selectTenant\" ? (\n <SelectTenant\n vm={vm.selectTenant}\n onSelect={tenantId => presenter.selectTenant(tenantId)}\n onSignOut={() => presenter.signOut()}\n />\n ) : null}\n\n {vm.authState === \"noTenantAccess\" ? (\n <NoTenantAccess onSignOut={() => presenter.signOut()} />\n ) : null}\n\n {(vm.authState === \"signIn\" || vm.authState === \"signedOut\") && (\n <SignIn\n vm={vm.signIn}\n onSubmit={(username, password) => presenter.signIn(username, password)}\n onForgotPassword={() => presenter.showRequestPasswordResetCode()}\n />\n )}\n </>\n ) : null}\n </>\n );\n});\n"],"names":["CognitoLoginScreen","observer","props","presenter","useFeature","CognitoFeature","useEffect","vm","OverlayLoader","RequireNewPassword","password","attributes","RequestPasswordResetCode","username","PasswordResetCodeSent","SetNewPassword","code","ConfirmTotpCode","SetupTotp","SelectTenant","tenantId","NoTenantAccess","SignIn"],"mappings":";;;;;;;;;;;;;;AAsBO,MAAMA,qBAAqBC,SAAS,CAACC;IACxC,MAAM,EAAEC,SAAS,EAAE,GAAGC,WAAWC;IAEjCC,UAAU;QACNH,UAAU,IAAI,CAAC;YACX,Q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jBA,GAAG,SAAS,IAA0B,WAArB,GACd,oBAACU,iBAAeA;QACZ,IAAIV,GAAG,eAAe;QACtB,UAAUS,CAAAA,OAAQb,UAAU,eAAe,CAACa;QAC5C,UAAU,IAAMb,UAAU,UAAU;QAI3CI,AAAiB,gBAAjBA,GAAG,SAAS,IAAoB,WAAf,GACd,oBAACW,WAASA;QACN,IAAIX,GAAG,SAAS;QAChB,UAAUS,CAAAA,OAAQb,UAAU,eAAe,CAACa;QAInDT,AAAiB,mBAAjBA,GAAG,SAAS,GAAsB,WAAjB,GACd,oBAACY,cAAYA;QACT,IAAIZ,GAAG,YAAY;QACnB,UAAUa,CAAAA,WAAYjB,UAAU,YAAY,CAACiB;QAC7C,WAAW,IAAMjB,UAAU,OAAO;SAEtC,MAEHI,AAAiB,qBAAjBA,GAAG,SAAS,GAAwB,WAAnB,GACd,oBAACc,gBAAcA;QAAC,WAAW,IAAMlB,UAAU,OAAO;SAClD,MAEFI,AAAAA,CAAAA,AAAiB,aAAjBA,GAAG,SAAS,IAAiBA,AAAiB,gBAAjBA,GAAG,SAAS,AAAgB,KAAK,WAAL,GACvD,oBAACe,QAAMA;QACH,IAAIf,GAAG,MAAM;QACb,UAAU,CAACM,UAAUH,WAAaP,UAAU,MAAM,CAACU,UAAUH;QAC7D,kBAAkB,IAAMP,UAAU,4BAA4B;;AAO1F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin/presentation/Cognito/CognitoPresenter.test.js","sources":["../../../../src/admin/presentation/Cognito/CognitoPresenter.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { Container } from \"@webiny/di\";\nimport { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { LocalStorage } from \"@webiny/app/features/localStorage/index.js\";\nimport { TenancyFeature } from \"@webiny/app-admin/features/tenancy/feature.js\";\nimport { SecurityFeature } from \"@webiny/app-admin/features/security/SecurityFeature.js\";\nimport { CognitoFeature } from \"./feature.js\";\n\nconst amplify = vi.hoisted(() => {\n return {\n signIn: vi.fn(),\n signOut: vi.fn(),\n fetchAuthSession: vi.fn()\n };\n});\n\nvi.mock(\"aws-amplify\", () => ({ Amplify: { configure: vi.fn() } }));\n\nvi.mock(\"aws-amplify/auth\", () => ({\n signIn: amplify.signIn,\n signOut: amplify.signOut,\n fetchAuthSession: amplify.fetchAuthSession,\n confirmSignIn: vi.fn(),\n resetPassword: vi.fn(),\n confirmResetPassword: vi.fn()\n}));\n\nconst createLocalStorage = (): LocalStorage.Interface => {\n const values = new Map<string, any>();\n return {\n get: key => values.get(key),\n set: (key, value) => {\n values.set(key, value);\n },\n remove: key => {\n values.delete(key);\n },\n clear: () => values.clear(),\n keys: () => Array.from(values.keys())\n };\n};\n\nconst loginResponse = (login: { data?: any; error?: any }) => {\n return { security: { login: { data: login.data ?? null, error: login.error ?? null } } };\n};\n\nconst tenantSelection = (tenants: { id: string; name: string }[]) => {\n return loginResponse({ data: { __typename: \"SecurityLoginTenantSelection\", tenants } });\n};\n\nconst identityDto = {\n __typename: \"SecurityIdentity\",\n id: \"user-1\",\n type: \"admin\",\n displayName: \"User 1\",\n roles: [],\n teams: [],\n permissions: [{ name: \"*\" }],\n profile: { firstName: \"\", lastName: \"\", email: \"user-1@webiny.local\" },\n currentTenant: { id: \"root\", name: \"Root\" },\n defaultTenant: { id: \"root\", name: \"Root\" }\n};\n\ndescribe(\"CognitoPresenter: signing in to a tenant\", () => {\n let container: Container;\n let execute: ReturnType<typeof vi.fn>;\n\n const presenter = () => CognitoFeature.resolve(container).presenter;\n const currentTenant = () => TenancyFeature.resolve(container).service.getCurrentTenant();\n\n beforeEach(() => {\n vi.clearAllMocks();\n amplify.signIn.mockResolvedValue({ nextStep: { signInStep: \"DONE\" } });\n amplify.signOut.mockResolvedValue(undefined);\n amplify.fetchAuthSession.mockResolvedValue({ tokens: { idToken: \"token\" } });\n\n container = new Container();\n execute = vi.fn();\n container.registerInstance(LocalStorage, createLocalStorage());\n container.registerInstance(MainGraphQLClient, {\n execute\n } as unknown as MainGraphQLClient.Interface);\n\n TenancyFeature.register(container);\n SecurityFeature.register(container);\n CognitoFeature.register(container);\n });\n\n it(\"signs the user in when they can access the current tenant\", async () => {\n execute.mockResolvedValue(loginResponse({ data: identityDto }));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"signedIn\");\n expect(presenter().vm.isAuthenticated).toBe(true);\n });\n\n it(\"keeps the loader on while the app reloads on the user's only tenant\", async () => {\n execute.mockResolvedValue(tenantSelection([{ id: \"acme\", name: \"Acme\" }]));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.isLoggingIn).toBe(true);\n expect(currentTenant()).toBe(\"acme\");\n expect(amplify.signOut).not.toHaveBeenCalled();\n });\n\n it(\"shows a tenant picker when the user can access several tenants, and picking one opens it\", async () => {\n const tenants = [\n { id: \"acme\", name: \"Acme\" },\n { id: \"beta\", name: \"Beta\" }\n ];\n execute.mockResolvedValue(tenantSelection(tenants));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"selectTenant\");\n expect(presenter().vm.isLoggingIn).toBe(false);\n expect(presenter().vm.selectTenant.tenants).toEqual(tenants);\n\n presenter().selectTenant(\"beta\");\n\n expect(currentTenant()).toBe(\"beta\");\n expect(presenter().vm.isLoggingIn).toBe(true);\n });\n\n it(\"shows the no-access screen, and signing out returns to the sign-in form\", async () => {\n execute.mockResolvedValue(\n loginResponse({\n error: { code: \"Security/Identity/NotAuthorized\", message: \"Missing user profile!\" }\n })\n );\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"noTenantAccess\");\n\n await presenter().signOut();\n\n expect(amplify.signOut).toHaveBeenCalled();\n expect(presenter().vm.authState).toBe(\"signIn\");\n expect(presenter().vm.signIn.message).toBeNull();\n });\n\n it(\"shows any other login error on the sign-in form instead of failing silently\", async () => {\n execute.mockResolvedValue(loginResponse({ data: { ...identityDto, permissions: [] } }));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"signIn\");\n expect(presenter().vm.signIn.message).toEqual({\n title: \"Login Failed\",\n text: \"You have no permissions on this tenant!\",\n type: \"danger\"\n });\n // The Cognito session is closed, so the user can sign in again.\n expect(amplify.signOut).toHaveBeenCalled();\n });\n});\n"],"names":["amplify","vi","createLocalStorage","values","Map","key","value","Array","loginResponse","login","tenantSelection","tenants","identityDto","describe","container","execute","presenter","CognitoFeature","currentTenant","TenancyFeature","beforeEach","undefined","Container","LocalStorage","MainGraphQLClient","SecurityFeature","it","expect"],"mappings":";;;;;;;AAQA,MAAMA,UAAUC,GAAG,OAAO,CAAC,IAChB;QACH,QAAQA,GAAG,EAAE;QACb,SAASA,GAAG,EAAE;QACd,kBAAkBA,GAAG,EAAE;IAC3B;
|
|
1
|
+
{"version":3,"file":"admin/presentation/Cognito/CognitoPresenter.test.js","sources":["../../../../src/admin/presentation/Cognito/CognitoPresenter.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { Container } from \"@webiny/di\";\nimport { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { LocalStorage } from \"@webiny/app/features/localStorage/index.js\";\nimport { TenancyFeature } from \"@webiny/app-admin/features/tenancy/feature.js\";\nimport { SecurityFeature } from \"@webiny/app-admin/features/security/SecurityFeature.js\";\nimport { CognitoFeature } from \"./feature.js\";\n\nconst amplify = vi.hoisted(() => {\n return {\n signIn: vi.fn(),\n signOut: vi.fn(),\n fetchAuthSession: vi.fn()\n };\n});\n\nvi.mock(\"aws-amplify\", () => ({ Amplify: { configure: vi.fn() } }));\n\nvi.mock(\"aws-amplify/auth\", () => ({\n signIn: amplify.signIn,\n signOut: amplify.signOut,\n fetchAuthSession: amplify.fetchAuthSession,\n confirmSignIn: vi.fn(),\n resetPassword: vi.fn(),\n confirmResetPassword: vi.fn()\n}));\n\nconst createLocalStorage = (): LocalStorage.Interface => {\n const values = new Map<string, any>();\n return {\n get: key => values.get(key),\n set: (key, value) => {\n values.set(key, value);\n },\n remove: key => {\n values.delete(key);\n },\n clear: () => values.clear(),\n keys: () => Array.from(values.keys())\n };\n};\n\nconst loginResponse = (login: { data?: any; error?: any }) => {\n return { security: { login: { data: login.data ?? null, error: login.error ?? null } } };\n};\n\nconst tenantSelection = (tenants: { id: string; name: string }[]) => {\n return loginResponse({ data: { __typename: \"SecurityLoginTenantSelection\", tenants } });\n};\n\nconst identityDto = {\n __typename: \"SecurityIdentity\",\n id: \"user-1\",\n type: \"admin\",\n displayName: \"User 1\",\n roles: [],\n teams: [],\n permissions: [{ name: \"*\" }],\n profile: { firstName: \"\", lastName: \"\", email: \"user-1@webiny.local\" },\n currentTenant: { id: \"root\", name: \"Root\" },\n defaultTenant: { id: \"root\", name: \"Root\" }\n};\n\ndescribe(\"CognitoPresenter: signing in to a tenant\", () => {\n let container: Container;\n let execute: ReturnType<typeof vi.fn>;\n\n const presenter = () => CognitoFeature.resolve(container).presenter;\n const currentTenant = () => TenancyFeature.resolve(container).service.getCurrentTenant();\n\n beforeEach(() => {\n vi.clearAllMocks();\n amplify.signIn.mockResolvedValue({ nextStep: { signInStep: \"DONE\" } });\n amplify.signOut.mockResolvedValue(undefined);\n amplify.fetchAuthSession.mockResolvedValue({ tokens: { idToken: \"token\" } });\n\n container = new Container();\n execute = vi.fn();\n container.registerInstance(LocalStorage, createLocalStorage());\n container.registerInstance(MainGraphQLClient, {\n execute\n } as unknown as MainGraphQLClient.Interface);\n\n TenancyFeature.register(container);\n SecurityFeature.register(container);\n CognitoFeature.register(container);\n });\n\n it(\"signs the user in when they can access the current tenant\", async () => {\n execute.mockResolvedValue(loginResponse({ data: identityDto }));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"signedIn\");\n expect(presenter().vm.isAuthenticated).toBe(true);\n });\n\n it(\"keeps the loader on while the app reloads on the user's only tenant\", async () => {\n execute.mockResolvedValue(tenantSelection([{ id: \"acme\", name: \"Acme\" }]));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.isLoggingIn).toBe(true);\n expect(currentTenant()).toBe(\"acme\");\n expect(amplify.signOut).not.toHaveBeenCalled();\n });\n\n it(\"shows a tenant picker when the user can access several tenants, and picking one opens it\", async () => {\n const tenants = [\n { id: \"acme\", name: \"Acme\" },\n { id: \"beta\", name: \"Beta\" }\n ];\n execute.mockResolvedValue(tenantSelection(tenants));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"selectTenant\");\n expect(presenter().vm.isLoggingIn).toBe(false);\n expect(presenter().vm.selectTenant.tenants).toEqual(tenants);\n\n presenter().selectTenant(\"beta\");\n\n expect(currentTenant()).toBe(\"beta\");\n expect(presenter().vm.isLoggingIn).toBe(true);\n });\n\n it(\"shows the no-access screen, and signing out returns to the sign-in form\", async () => {\n execute.mockResolvedValue(\n loginResponse({\n error: { code: \"Security/Identity/NotAuthorized\", message: \"Missing user profile!\" }\n })\n );\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"noTenantAccess\");\n\n await presenter().signOut();\n\n expect(amplify.signOut).toHaveBeenCalled();\n expect(presenter().vm.authState).toBe(\"signIn\");\n expect(presenter().vm.signIn.message).toBeNull();\n });\n\n it(\"shows any other login error on the sign-in form instead of failing silently\", async () => {\n execute.mockResolvedValue(loginResponse({ data: { ...identityDto, permissions: [] } }));\n\n await presenter().signIn(\"user-1@webiny.local\", \"password\");\n\n expect(presenter().vm.authState).toBe(\"signIn\");\n expect(presenter().vm.signIn.message).toEqual({\n title: \"Login Failed\",\n text: \"You have no permissions on this tenant!\",\n type: \"danger\"\n });\n // The Cognito session is closed, so the user can sign in again.\n expect(amplify.signOut).toHaveBeenCalled();\n });\n});\n"],"names":["amplify","vi","createLocalStorage","values","Map","key","value","Array","loginResponse","login","tenantSelection","tenants","identityDto","describe","container","execute","presenter","CognitoFeature","currentTenant","TenancyFeature","beforeEach","undefined","Container","LocalStorage","MainGraphQLClient","SecurityFeature","it","expect"],"mappings":";;;;;;;AAQA,MAAMA,UAAUC,GAAG,OAAO,CAAC,IAChB;QACH,QAAQA,GAAG,EAAE;QACb,SAASA,GAAG,EAAE;QACd,kBAAkBA,GAAG,EAAE;IAC3B,CAAC;AAGLA,GAAG,IAAI,CAAC,eAAe,IAAO;QAAE,SAAS;YAAE,WAAWA,GAAG,EAAE;QAAG;IAAE,CAAC;AAEjEA,GAAG,IAAI,CAAC,oBAAoB,IAAO;QAC/B,QAAQD,QAAQ,MAAM;QACtB,SAASA,QAAQ,OAAO;QACxB,kBAAkBA,QAAQ,gBAAgB;QAC1C,eAAeC,GAAG,EAAE;QACpB,eAAeA,GAAG,EAAE;QACpB,sBAAsBA,GAAG,EAAE;IAC/B,CAAC;AAED,MAAMC,qBAAqB;IACvB,MAAMC,SAAS,IAAIC;IACnB,OAAO;QACH,KAAKC,CAAAA,MAAOF,OAAO,GAAG,CAACE;QACvB,KAAK,CAACA,KAAKC;YACPH,OAAO,GAAG,CAACE,KAAKC;QACpB;QACA,QAAQD,CAAAA;YACJF,OAAO,MAAM,CAACE;QAClB;QACA,OAAO,IAAMF,OAAO,KAAK;QACzB,MAAM,IAAMI,MAAM,IAAI,CAACJ,OAAO,IAAI;IACtC;AACJ;AAEA,MAAMK,gBAAgB,CAACC,QACZ;QAAE,UAAU;YAAE,OAAO;gBAAE,MAAMA,MAAM,IAAI,IAAI;gBAAM,OAAOA,MAAM,KAAK,IAAI;YAAK;QAAE;IAAE,CAAC;AAG5F,MAAMC,kBAAkB,CAACC,UACdH,cAAc;QAAE,MAAM;YAAE,YAAY;YAAgCG;QAAQ;IAAE;AAGzF,MAAMC,cAAc;IAChB,YAAY;IACZ,IAAI;IACJ,MAAM;IACN,aAAa;IACb,OAAO,EA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MAAM,CAAC,uBAAuB;QAEhDW,OAAOX,YAAY,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;QACtCW,OAAOX,YAAY,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC;YAC1C,OAAO;YACP,MAAM;YACN,MAAM;QACV;QAEAW,OAAO3B,QAAQ,OAAO,EAAE,gBAAgB;IAC5C;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin/presentation/users/ResetMfa/ResetMfaPresenter.test.js","sources":["../../../../../src/admin/presentation/users/ResetMfa/ResetMfaPresenter.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { Container } from \"@webiny/di\";\nimport { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { ResetUserMfaFeature } from \"~/admin/features/users/resetUserMfa/index.js\";\nimport { ResetMfaFeature } from \"./feature.js\";\n\nconst user = { id: \"user-1\", email: \"person@example.com\", external: false };\n\nconst resetResponse = (error: Record<string, any> | null = null) => {\n return { adminUsers: { resetUserMfa: { data: error ? null : true, error } } };\n};\n\ndescribe(\"ResetMfaPresenter: resetting a user's MFA\", () => {\n let container: Container;\n let execute: ReturnType<typeof vi.fn>;\n\n const presenter = () => ResetMfaFeature.resolve(container).presenter;\n\n beforeEach(() => {\n container = new Container();\n execute = vi.fn();\n container.registerInstance(MainGraphQLClient, {\n execute\n } as unknown as MainGraphQLClient.Interface);\n\n ResetUserMfaFeature.register(container);\n ResetMfaFeature.register(container);\n });\n\n it(\"offers the reset for another user who signs in with Cognito\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n expect(resetMfa.vm).toEqual({ available: true, resetting: false });\n });\n\n it(\"doesn't offer the reset for a federated user\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user: { ...user, external: true }, currentIdentityId: \"admin-1\" });\n\n expect(resetMfa.vm.available).toBe(false);\n });\n\n it(\"doesn't offer the reset for yourself\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user, currentIdentityId: user.id });\n\n expect(resetMfa.vm.available).toBe(false);\n });\n\n it(\"doesn't offer the reset without a user\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user: undefined, currentIdentityId: \"admin-1\" });\n\n expect(resetMfa.vm.available).toBe(false);\n });\n\n it(\"resets the user's MFA and says they'll set it up on their next sign-in\", async () => {\n execute.mockResolvedValue(resetResponse());\n const resetMfa = presenter();\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n const result = await resetMfa.reset();\n\n expect(result).toEqual({\n type: \"reset\",\n message:\n \"MFA reset for person@example.com. They'll set it up again on their next sign-in.\"\n });\n expect(execute).toHaveBeenCalledTimes(1);\n expect(execute.mock.calls[0][0].variables).toEqual({ id: user.id });\n expect(resetMfa.vm.resetting).toBe(false);\n });\n\n it(\"shows that it's resetting while the request runs\", async () => {\n let answer: (value: unknown) => void = () => {};\n execute.mockReturnValue(new Promise(resolve => (answer = resolve)));\n const resetMfa = presenter();\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n const result = resetMfa.reset();\n expect(resetMfa.vm.resetting).toBe(true);\n\n answer(resetResponse());\n await result;\n expect(resetMfa.vm.resetting).toBe(false);\n });\n\n it(\"reports the API's error\", async () => {\n execute.mockResolvedValue(\n resetResponse({\n code: \"Cognito/User/ResetMfa\",\n message: \"Failed to reset the user's MFA in Cognito: User has no software token.\",\n data: null\n })\n );\n const resetMfa = presenter();\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n const result = await resetMfa.reset();\n\n expect(result).toEqual({\n type: \"failed\",\n message: \"Failed to reset the user's MFA in Cognito: User has no software token.\"\n });\n expect(resetMfa.vm.resetting).toBe(false);\n });\n\n it(\"doesn't send a reset for a user it isn't offered for\", async () => {\n const resetMfa = presenter();\n resetMfa.init({ user: { ...user, external: true }, currentIdentityId: \"admin-1\" });\n\n const result = await resetMfa.reset();\n\n expect(result.type).toBe(\"failed\");\n expect(execute).not.toHaveBeenCalled();\n });\n});\n"],"names":["user","resetResponse","error","describe","container","execute","presenter","ResetMfaFeature","beforeEach","Container","vi","MainGraphQLClient","ResetUserMfaFeature","it","resetMfa","expect","undefined","result","answer","Promise","resolve"],"mappings":";;;;;AAMA,MAAMA,OAAO;IAAE,IAAI;IAAU,OAAO;IAAsB,UAAU;AAAM;AAE1E,MAAMC,gBAAgB,CAACC,QAAoC,IAAI,GACpD;QAAE,YAAY;YAAE,cAAc;gBAAE,MAAMA,QAAQ,OAAO;gBAAMA;YAAM;QAAE;IAAE;
|
|
1
|
+
{"version":3,"file":"admin/presentation/users/ResetMfa/ResetMfaPresenter.test.js","sources":["../../../../../src/admin/presentation/users/ResetMfa/ResetMfaPresenter.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { Container } from \"@webiny/di\";\nimport { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { ResetUserMfaFeature } from \"~/admin/features/users/resetUserMfa/index.js\";\nimport { ResetMfaFeature } from \"./feature.js\";\n\nconst user = { id: \"user-1\", email: \"person@example.com\", external: false };\n\nconst resetResponse = (error: Record<string, any> | null = null) => {\n return { adminUsers: { resetUserMfa: { data: error ? null : true, error } } };\n};\n\ndescribe(\"ResetMfaPresenter: resetting a user's MFA\", () => {\n let container: Container;\n let execute: ReturnType<typeof vi.fn>;\n\n const presenter = () => ResetMfaFeature.resolve(container).presenter;\n\n beforeEach(() => {\n container = new Container();\n execute = vi.fn();\n container.registerInstance(MainGraphQLClient, {\n execute\n } as unknown as MainGraphQLClient.Interface);\n\n ResetUserMfaFeature.register(container);\n ResetMfaFeature.register(container);\n });\n\n it(\"offers the reset for another user who signs in with Cognito\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n expect(resetMfa.vm).toEqual({ available: true, resetting: false });\n });\n\n it(\"doesn't offer the reset for a federated user\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user: { ...user, external: true }, currentIdentityId: \"admin-1\" });\n\n expect(resetMfa.vm.available).toBe(false);\n });\n\n it(\"doesn't offer the reset for yourself\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user, currentIdentityId: user.id });\n\n expect(resetMfa.vm.available).toBe(false);\n });\n\n it(\"doesn't offer the reset without a user\", () => {\n const resetMfa = presenter();\n\n resetMfa.init({ user: undefined, currentIdentityId: \"admin-1\" });\n\n expect(resetMfa.vm.available).toBe(false);\n });\n\n it(\"resets the user's MFA and says they'll set it up on their next sign-in\", async () => {\n execute.mockResolvedValue(resetResponse());\n const resetMfa = presenter();\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n const result = await resetMfa.reset();\n\n expect(result).toEqual({\n type: \"reset\",\n message:\n \"MFA reset for person@example.com. They'll set it up again on their next sign-in.\"\n });\n expect(execute).toHaveBeenCalledTimes(1);\n expect(execute.mock.calls[0][0].variables).toEqual({ id: user.id });\n expect(resetMfa.vm.resetting).toBe(false);\n });\n\n it(\"shows that it's resetting while the request runs\", async () => {\n let answer: (value: unknown) => void = () => {};\n execute.mockReturnValue(new Promise(resolve => (answer = resolve)));\n const resetMfa = presenter();\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n const result = resetMfa.reset();\n expect(resetMfa.vm.resetting).toBe(true);\n\n answer(resetResponse());\n await result;\n expect(resetMfa.vm.resetting).toBe(false);\n });\n\n it(\"reports the API's error\", async () => {\n execute.mockResolvedValue(\n resetResponse({\n code: \"Cognito/User/ResetMfa\",\n message: \"Failed to reset the user's MFA in Cognito: User has no software token.\",\n data: null\n })\n );\n const resetMfa = presenter();\n resetMfa.init({ user, currentIdentityId: \"admin-1\" });\n\n const result = await resetMfa.reset();\n\n expect(result).toEqual({\n type: \"failed\",\n message: \"Failed to reset the user's MFA in Cognito: User has no software token.\"\n });\n expect(resetMfa.vm.resetting).toBe(false);\n });\n\n it(\"doesn't send a reset for a user it isn't offered for\", async () => {\n const resetMfa = presenter();\n resetMfa.init({ user: { ...user, external: true }, currentIdentityId: \"admin-1\" });\n\n const result = await resetMfa.reset();\n\n expect(result.type).toBe(\"failed\");\n expect(execute).not.toHaveBeenCalled();\n });\n});\n"],"names":["user","resetResponse","error","describe","container","execute","presenter","ResetMfaFeature","beforeEach","Container","vi","MainGraphQLClient","ResetUserMfaFeature","it","resetMfa","expect","undefined","result","answer","Promise","resolve"],"mappings":";;;;;AAMA,MAAMA,OAAO;IAAE,IAAI;IAAU,OAAO;IAAsB,UAAU;AAAM;AAE1E,MAAMC,gBAAgB,CAACC,QAAoC,IAAI,GACpD;QAAE,YAAY;YAAE,cAAc;gBAAE,MAAMA,QAAQ,OAAO;gBAAMA;YAAM;QAAE;IAAE,CAAC;AAGjFC,SAAS,6CAA6C;IAClD,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,YAAY,IAAMC,gBAAgB,OAAO,CAACH,WAAW,SAAS;IAEpEI,WAAW;QACPJ,YAAY,IAAIK;QAChBJ,UAAUK,GAAG,EAAE;QACfN,UAAU,gBAAgB,CAACO,mBAAmB;YAC1CN;QACJ;QAEAO,oBAAoB,QAAQ,CAACR;QAC7BG,gBAAgB,QAAQ,CAACH;IAC7B;IAEAS,GAAG,+DAA+D;QAC9D,MAAMC,WAAWR;QAEjBQ,SAAS,IAAI,CAAC;YAAEd;YAAM,mBAAmB;QAAU;QAEnDe,OAAOD,SAAS,EAAE,EAAE,OAAO,CAAC;YAAE,WAAW;YAAM,WAAW;QAAM;IACpE;IAEAD,GAAG,gDAAgD;QAC/C,MAAMC,WAAWR;QAEjBQ,SAAS,IAAI,CAAC;YAAE,MAAM;gBAAE,GAAGd,IAAI;gBAAE,UAAU;YAAK;YAAG,mBAAmB;QAAU;QAEhFe,OAAOD,SAAS,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IACvC;IAEAD,GAAG,wCAAwC;QACvC,MAAMC,WAAWR;QAEjBQ,SAAS,IAAI,CAAC;YAAEd;YAAM,mBAAmB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AmB;QAAU;QAEnD,MAAMiB,SAAS,MAAMH,SAAS,KAAK;QAEnCC,OAAOE,QAAQ,OAAO,CAAC;YACnB,MAAM;YACN,SAAS;QACb;QACAF,OAAOD,SAAS,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IACvC;IAEAD,GAAG,wDAAwD;QACvD,MAAMC,WAAWR;QACjBQ,SAAS,IAAI,CAAC;YAAE,MAAM;gBAAE,GAAGd,IAAI;gBAAE,UAAU;YAAK;YAAG,mBAAmB;QAAU;QAEhF,MAAMiB,SAAS,MAAMH,SAAS,KAAK;QAEnCC,OAAOE,OAAO,IAAI,EAAE,IAAI,CAAC;QACzBF,OAAOV,SAAS,GAAG,CAAC,gBAAgB;IACxC;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin/presentation/users/UserForm/UserFormPresenter.js","sources":["../../../../../src/admin/presentation/users/UserForm/UserFormPresenter.ts"],"sourcesContent":["import { makeAutoObservable, runInAction } from \"mobx\";\nimport { CreateUserUseCase } from \"~/admin/features/users/createUser/index.js\";\nimport { LinkUserUseCase } from \"~/admin/features/users/linkUser/index.js\";\nimport { CheckEmailUseCase } from \"~/admin/features/users/checkEmail/index.js\";\nimport { AdminUsersError } from \"~/admin/features/users/shared/AdminUsersError.js\";\nimport {\n UserFormPresenter as PresenterAbstraction,\n type NewUserFormData,\n type UserFormMode,\n type UserFormSubmitResult\n} from \"./abstractions.js\";\n\nexport const EMAIL_EXISTS_HERE = \"A user with this email already exists in this tenant.\";\n\nconst EXISTS_IN_OTHER_TENANT = \"Cognito/Account/ExistsInOtherTenant\";\n\nconst looksLikeEmail = (email: string) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n\nclass UserFormPresenterImpl implements PresenterAbstraction.Interface {\n private mode: UserFormMode = \"create\";\n private emailError: string | null = null;\n private saving = false;\n /** The email `mode` and `emailError` belong to. */\n private checkedEmail: string | null = null;\n private checkCount = 0;\n\n constructor(\n private createUser: CreateUserUseCase.Interface,\n private linkUser: LinkUserUseCase.Interface,\n private checkEmailUseCase: CheckEmailUseCase.Interface\n ) {\n makeAutoObservable(this);\n }\n\n get vm() {\n return {\n mode: this.mode,\n emailError: this.emailError,\n saving: this.saving\n };\n }\n\n reset() {\n this.mode = \"create\";\n this.emailError = null;\n this.saving = false;\n this.checkedEmail = null;\n }\n\n async checkEmail(value: string) {\n // The API finds this tenant's user by the email as stored, so send it as typed.\n const email = (value ?? \"\").trim();\n const key = email.toLowerCase();\n if (key === this.checkedEmail) {\n return;\n }\n\n const check = ++this.checkCount;\n this.checkedEmail = key;\n\n if (!looksLikeEmail(email)) {\n this.setStatus(\"create\", null);\n return;\n }\n\n let status: CheckEmailUseCase.Status;\n try {\n status = await this.checkEmailUseCase.execute(email);\n } catch {\n // Creating the user reports any problem with the email. Check it again next time.\n status = \"AVAILABLE\";\n runInAction(() => {\n if (check === this.checkCount) {\n this.checkedEmail = null;\n }\n });\n }\n\n // A newer email was entered while this one was being checked.\n if (check !== this.checkCount) {\n return;\n }\n\n if (status === \"EXISTS_ELSEWHERE\") {\n this.setStatus(\"link\", null);\n } else if (status === \"EXISTS_HERE\") {\n this.setStatus(\"create\", EMAIL_EXISTS_HERE);\n } else {\n this.setStatus(\"create\", null);\n }\n }\n\n async submit(data: NewUserFormData): Promise<UserFormSubmitResult> {\n this.saving = true;\n\n try {\n if (this.mode === \"link\") {\n const user = await this.linkUser.execute({\n data: { email: data.email, roles: data.roles, teams: data.teams }\n });\n return { type: \"linked\", user };\n }\n\n try {\n const user = await this.createUser.execute({ data });\n return { type: \"created\", user };\n } catch (error) {\n if (error instanceof AdminUsersError && error.code === EXISTS_IN_OTHER_TENANT) {\n runInAction(() => {\n this.checkedEmail = (data.email ?? \"\").trim().toLowerCase();\n this.setStatus(\"link\", null);\n });\n return { type: \"linkRequired\" };\n }\n throw error;\n }\n } catch (error) {\n return {\n type: \"failed\",\n message: error instanceof Error ? error.message : \"Unknown error\"\n };\n } finally {\n runInAction(() => {\n this.saving = false;\n });\n }\n }\n\n private setStatus(mode: UserFormMode, emailError: string | null) {\n this.mode = mode;\n this.emailError = emailError;\n }\n}\n\nexport const UserFormPresenter = PresenterAbstraction.createImplementation({\n implementation: UserFormPresenterImpl,\n dependencies: [CreateUserUseCase, LinkUserUseCase, CheckEmailUseCase]\n});\n"],"names":["EMAIL_EXISTS_HERE","EXISTS_IN_OTHER_TENANT","looksLikeEmail","email","UserFormPresenterImpl","createUser","linkUser","checkEmailUseCase","makeAutoObservable","value","key","check","status","runInAction","data","user","error","AdminUsersError","Error","mode","emailError","UserFormPresenter","PresenterAbstraction","CreateUserUseCase","LinkUserUseCase","CheckEmailUseCase"],"mappings":";;;;;;AAYO,MAAMA,oBAAoB;AAEjC,MAAMC,yBAAyB;AAE/B,MAAMC,iBAAiB,CAACC,QAAkB,6BAA6B,IAAI,CAACA;AAE5E,MAAMC;IAQF,YACYC,UAAuC,EACvCC,QAAmC,EACnCC,iBAA8C,CACxD;aAHUF,UAAU,GAAVA;aACAC,QAAQ,GAARA;aACAC,iBAAiB,GAAjBA;aAVJ,IAAI,GAAiB;aACrB,UAAU,GAAkB;aAC5B,MAAM,GAAG;QACgC,KACzC,YAAY,GAAkB;aAC9B,UAAU,GAAG;QAOjBC,mBAAmB,IAAI;IAC3B;IAEA,IAAI,KAAK;QACL,OAAO;YACH,MAAM,IAAI,CAAC,IAAI;YACf,YAAY,IAAI,CAAC,UAAU;YAC3B,QAAQ,IAAI,CAAC,MAAM;QACvB;IACJ;IAEA,QAAQ;QACJ,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,UAAU,GAAG;QAClB,IAAI,CAAC,MAAM,GAAG;QACd,IAAI,CAAC,YAAY,GAAG;IACxB;IAEA,MAAM,WAAWC,KAAa,EAAE;QAE5B,MAAMN,QAASM,AAAAA,CAAAA,SAAS,
|
|
1
|
+
{"version":3,"file":"admin/presentation/users/UserForm/UserFormPresenter.js","sources":["../../../../../src/admin/presentation/users/UserForm/UserFormPresenter.ts"],"sourcesContent":["import { makeAutoObservable, runInAction } from \"mobx\";\nimport { CreateUserUseCase } from \"~/admin/features/users/createUser/index.js\";\nimport { LinkUserUseCase } from \"~/admin/features/users/linkUser/index.js\";\nimport { CheckEmailUseCase } from \"~/admin/features/users/checkEmail/index.js\";\nimport { AdminUsersError } from \"~/admin/features/users/shared/AdminUsersError.js\";\nimport {\n UserFormPresenter as PresenterAbstraction,\n type NewUserFormData,\n type UserFormMode,\n type UserFormSubmitResult\n} from \"./abstractions.js\";\n\nexport const EMAIL_EXISTS_HERE = \"A user with this email already exists in this tenant.\";\n\nconst EXISTS_IN_OTHER_TENANT = \"Cognito/Account/ExistsInOtherTenant\";\n\nconst looksLikeEmail = (email: string) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n\nclass UserFormPresenterImpl implements PresenterAbstraction.Interface {\n private mode: UserFormMode = \"create\";\n private emailError: string | null = null;\n private saving = false;\n /** The email `mode` and `emailError` belong to. */\n private checkedEmail: string | null = null;\n private checkCount = 0;\n\n constructor(\n private createUser: CreateUserUseCase.Interface,\n private linkUser: LinkUserUseCase.Interface,\n private checkEmailUseCase: CheckEmailUseCase.Interface\n ) {\n makeAutoObservable(this);\n }\n\n get vm() {\n return {\n mode: this.mode,\n emailError: this.emailError,\n saving: this.saving\n };\n }\n\n reset() {\n this.mode = \"create\";\n this.emailError = null;\n this.saving = false;\n this.checkedEmail = null;\n }\n\n async checkEmail(value: string) {\n // The API finds this tenant's user by the email as stored, so send it as typed.\n const email = (value ?? \"\").trim();\n const key = email.toLowerCase();\n if (key === this.checkedEmail) {\n return;\n }\n\n const check = ++this.checkCount;\n this.checkedEmail = key;\n\n if (!looksLikeEmail(email)) {\n this.setStatus(\"create\", null);\n return;\n }\n\n let status: CheckEmailUseCase.Status;\n try {\n status = await this.checkEmailUseCase.execute(email);\n } catch {\n // Creating the user reports any problem with the email. Check it again next time.\n status = \"AVAILABLE\";\n runInAction(() => {\n if (check === this.checkCount) {\n this.checkedEmail = null;\n }\n });\n }\n\n // A newer email was entered while this one was being checked.\n if (check !== this.checkCount) {\n return;\n }\n\n if (status === \"EXISTS_ELSEWHERE\") {\n this.setStatus(\"link\", null);\n } else if (status === \"EXISTS_HERE\") {\n this.setStatus(\"create\", EMAIL_EXISTS_HERE);\n } else {\n this.setStatus(\"create\", null);\n }\n }\n\n async submit(data: NewUserFormData): Promise<UserFormSubmitResult> {\n this.saving = true;\n\n try {\n if (this.mode === \"link\") {\n const user = await this.linkUser.execute({\n data: { email: data.email, roles: data.roles, teams: data.teams }\n });\n return { type: \"linked\", user };\n }\n\n try {\n const user = await this.createUser.execute({ data });\n return { type: \"created\", user };\n } catch (error) {\n if (error instanceof AdminUsersError && error.code === EXISTS_IN_OTHER_TENANT) {\n runInAction(() => {\n this.checkedEmail = (data.email ?? \"\").trim().toLowerCase();\n this.setStatus(\"link\", null);\n });\n return { type: \"linkRequired\" };\n }\n throw error;\n }\n } catch (error) {\n return {\n type: \"failed\",\n message: error instanceof Error ? error.message : \"Unknown error\"\n };\n } finally {\n runInAction(() => {\n this.saving = false;\n });\n }\n }\n\n private setStatus(mode: UserFormMode, emailError: string | null) {\n this.mode = mode;\n this.emailError = emailError;\n }\n}\n\nexport const UserFormPresenter = PresenterAbstraction.createImplementation({\n implementation: UserFormPresenterImpl,\n dependencies: [CreateUserUseCase, LinkUserUseCase, CheckEmailUseCase]\n});\n"],"names":["EMAIL_EXISTS_HERE","EXISTS_IN_OTHER_TENANT","looksLikeEmail","email","UserFormPresenterImpl","createUser","linkUser","checkEmailUseCase","makeAutoObservable","value","key","check","status","runInAction","data","user","error","AdminUsersError","Error","mode","emailError","UserFormPresenter","PresenterAbstraction","CreateUserUseCase","LinkUserUseCase","CheckEmailUseCase"],"mappings":";;;;;;AAYO,MAAMA,oBAAoB;AAEjC,MAAMC,yBAAyB;AAE/B,MAAMC,iBAAiB,CAACC,QAAkB,6BAA6B,IAAI,CAACA;AAE5E,MAAMC;IAQF,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
-
{"version":3,"file":"admin/presentation/users/UserForm/UserFormPresenter.test.js","sources":["../../../../../src/admin/presentation/users/UserForm/UserFormPresenter.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { Container } from \"@webiny/di\";\nimport { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { CreateUserFeature } from \"~/admin/features/users/createUser/index.js\";\nimport { LinkUserFeature } from \"~/admin/features/users/linkUser/index.js\";\nimport { CheckEmailFeature } from \"~/admin/features/users/checkEmail/index.js\";\nimport { UserFormFeature } from \"./feature.js\";\nimport { EMAIL_EXISTS_HERE } from \"./UserFormPresenter.js\";\n\nconst user = {\n id: \"user-1\",\n email: \"person@example.com\",\n firstName: \"Some\",\n lastName: \"Person\",\n avatar: null,\n createdOn: \"2026-10-23T00:00:00.000Z\",\n external: false\n};\n\nconst emailStatus = (status: string) => {\n return { adminUsers: { checkEmail: { data: { status }, error: null } } };\n};\n\nconst userResponse = (data: typeof user | null, error: Record<string, any> | null = null) => {\n return { adminUsers: { user: { data, error } } };\n};\n\ndescribe(\"UserFormPresenter: creating or linking a user\", () => {\n let container: Container;\n let execute: ReturnType<typeof vi.fn>;\n\n const presenter = () => UserFormFeature.resolve(container).presenter;\n\n /** The GraphQL operations the presenter sent, by their operation name. */\n const operations = () => {\n return execute.mock.calls.map(([request]) => {\n return /(query|mutation) (\\w+)/.exec(request.query)?.[2];\n });\n };\n\n beforeEach(() => {\n container = new Container();\n execute = vi.fn();\n container.registerInstance(MainGraphQLClient, {\n execute\n } as unknown as MainGraphQLClient.Interface);\n\n CreateUserFeature.register(container);\n LinkUserFeature.register(container);\n CheckEmailFeature.register(container);\n UserFormFeature.register(container);\n });\n\n it(\"starts in create mode\", () => {\n expect(presenter().vm).toEqual({ mode: \"create\", emailError: null, saving: false });\n });\n\n it(\"stays in create mode for a new email\", async () => {\n execute.mockResolvedValue(emailStatus(\"AVAILABLE\"));\n const form = presenter();\n\n await form.checkEmail(\"new@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: null });\n });\n\n it(\"switches to link mode for an email with an account in another tenant\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_ELSEWHERE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"link\", emailError: null });\n });\n\n it(\"shows an email error for a user already in this tenant\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_HERE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: EMAIL_EXISTS_HERE });\n });\n\n it(\"goes back to create mode when the email changes to a new one\", async () => {\n execute.mockResolvedValueOnce(emailStatus(\"EXISTS_ELSEWHERE\"));\n execute.mockResolvedValueOnce(emailStatus(\"AVAILABLE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n await form.checkEmail(\"someone-new@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: null });\n });\n\n it(\"doesn't check an incomplete email, or the same email twice\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_ELSEWHERE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@\");\n await form.checkEmail(\"person@example.com\");\n await form.checkEmail(\" Person@example.com \");\n\n expect(operations()).toEqual([\"CheckEmail\"]);\n expect(form.vm.mode).toBe(\"link\");\n });\n\n it(\"checks the email as typed, so a mixed-case email in this tenant is found\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_HERE\"));\n const form = presenter();\n\n await form.checkEmail(\" Foo@X.com \");\n\n expect(execute.mock.calls[0][0].variables).toEqual({ email: \"Foo@X.com\" });\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: EMAIL_EXISTS_HERE });\n });\n\n it(\"keeps the latest email's result when an earlier check answers last\", async () => {\n let answerFirst: (value: unknown) => void = () => {};\n execute.mockReturnValueOnce(new Promise(resolve => (answerFirst = resolve)));\n execute.mockResolvedValueOnce(emailStatus(\"AVAILABLE\"));\n const form = presenter();\n\n const first = form.checkEmail(\"person@example.com\");\n await form.checkEmail(\"someone-new@example.com\");\n answerFirst(emailStatus(\"EXISTS_ELSEWHERE\"));\n await first;\n\n expect(form.vm.mode).toBe(\"create\");\n });\n\n it(\"stays in create mode when the check fails\", async () => {\n execute.mockRejectedValue(new Error(\"Network error\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: null });\n });\n\n it(\"creates the user in create mode\", async () => {\n execute.mockResolvedValue(userResponse(user));\n const form = presenter();\n\n const result = await form.submit({\n email: user.email,\n firstName: \"Some\",\n lastName: \"Person\",\n password: \"SecurePass123!\"\n });\n\n expect(result).toEqual({ type: \"created\", user });\n expect(operations()).toEqual([\"CreateUser\"]);\n });\n\n it(\"links the account in link mode, sending only the email, roles and teams\", async () => {\n execute.mockResolvedValueOnce(emailStatus(\"EXISTS_ELSEWHERE\"));\n execute.mockResolvedValueOnce(userResponse(user));\n const form = presenter();\n await form.checkEmail(user.email);\n\n const result = await form.submit({\n email: user.email,\n firstName: \"Typed\",\n password: \"Ignored123!\",\n roles: [{ id: \"editors\" }],\n teams: []\n });\n\n expect(result).toEqual({ type: \"linked\", user });\n expect(operations()).toEqual([\"CheckEmail\", \"LinkUser\"]);\n expect(execute.mock.calls[1][0].variables).toEqual({\n data: { email: user.email, roles: [{ id: \"editors\" }], teams: [] }\n });\n expect(form.vm.saving).toBe(false);\n });\n\n it(\"switches to link mode when creating finds an account in another tenant\", async () => {\n execute.mockResolvedValue(\n userResponse(null, {\n code: \"Cognito/Account/ExistsInOtherTenant\",\n message: \"This email already has an account in another tenant. Link it instead.\",\n data: null\n })\n );\n const form = presenter();\n\n const result = await form.submit({ email: user.email, password: \"SecurePass123!\" });\n\n expect(result).toEqual({ type: \"linkRequired\" });\n expect(form.vm).toMatchObject({ mode: \"link\", emailError: null, saving: false });\n\n // The email is known now, so leaving the field doesn't check it again.\n await form.checkEmail(user.email);\n expect(operations()).toEqual([\"CreateUser\"]);\n });\n\n it(\"reports any other error and stays in create mode\", async () => {\n execute.mockResolvedValue(\n userResponse(null, { code: \"AdminUser/Validation\", message: \"Invalid.\", data: null })\n );\n const form = presenter();\n\n const result = await form.submit({ email: user.email, password: \"SecurePass123!\" });\n\n expect(result).toEqual({ type: \"failed\", message: \"Invalid.\" });\n expect(form.vm.mode).toBe(\"create\");\n });\n\n it(\"starts over in create mode after a reset\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_ELSEWHERE\"));\n const form = presenter();\n await form.checkEmail(user.email);\n\n form.reset();\n\n expect(form.vm).toEqual({ mode: \"create\", emailError: null, saving: false });\n });\n});\n"],"names":["user","emailStatus","status","userResponse","data","error","describe","container","execute","presenter","UserFormFeature","operations","request","beforeEach","Container","vi","MainGraphQLClient","CreateUserFeature","LinkUserFeature","CheckEmailFeature","it","expect","form","EMAIL_EXISTS_HERE","answerFirst","Promise","resolve","first","Error","result"],"mappings":";;;;;;;;AASA,MAAMA,OAAO;IACT,IAAI;IACJ,OAAO;IACP,WAAW;IACX,UAAU;IACV,QAAQ;IACR,WAAW;IACX,UAAU;AACd;AAEA,MAAMC,cAAc,CAACC,SACV;QAAE,YAAY;YAAE,YAAY;gBAAE,MAAM;oBAAEA;gBAAO;gBAAG,OAAO;YAAK;QAAE;IAAE;AAG3E,MAAMC,eAAe,CAACC,MAA0BC,QAAoC,IAAI,GAC7E;QAAE,YAAY;YAAE,MAAM;gBAAED;gBAAMC;YAAM;QAAE;IAAE;AAGnDC,SAAS,iDAAiD;IACtD,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,YAAY,IAAMC,gBAAgB,OAAO,CAACH,WAAW,SAAS;IAGpE,MAAMI,aAAa,IACRH,QAAQ,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAACI,QAAQ,GAC7B,yBAAyB,IAAI,CAACA,QAAQ,KAAK,GAAG,CAAC,EAAE;IAIhEC,WAAW;Q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AAQ;QAAM;QAG9E,MAAMA,KAAK,UAAU,CAACtB,KAAK,KAAK;QAChCqB,OAAOV,cAAc,OAAO,CAAC;YAAC;SAAa;IAC/C;IAEAS,GAAG,oDAAoD;QACnDZ,QAAQ,iBAAiB,CACrBL,aAAa,MAAM;YAAE,MAAM;YAAwB,SAAS;YAAY,MAAM;QAAK;QAEvF,MAAMmB,OAAOb;QAEb,MAAMoB,SAAS,MAAMP,KAAK,MAAM,CAAC;YAAE,OAAOtB,KAAK,KAAK;YAAE,UAAU;QAAiB;QAEjFqB,OAAOQ,QAAQ,OAAO,CAAC;YAAE,MAAM;YAAU,SAAS;QAAW;QAC7DR,OAAOC,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;IAC9B;IAEAF,GAAG,4CAA4C;QAC3CZ,QAAQ,iBAAiB,CAACP,YAAY;QACtC,MAAMqB,OAAOb;QACb,MAAMa,KAAK,UAAU,CAACtB,KAAK,KAAK;QAEhCsB,KAAK,KAAK;QAEVD,OAAOC,KAAK,EAAE,EAAE,OAAO,CAAC;YAAE,MAAM;YAAU,YAAY;YAAM,QAAQ;QAAM;IAC9E;AACJ"}
|
|
1
|
+
{"version":3,"file":"admin/presentation/users/UserForm/UserFormPresenter.test.js","sources":["../../../../../src/admin/presentation/users/UserForm/UserFormPresenter.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { Container } from \"@webiny/di\";\nimport { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { CreateUserFeature } from \"~/admin/features/users/createUser/index.js\";\nimport { LinkUserFeature } from \"~/admin/features/users/linkUser/index.js\";\nimport { CheckEmailFeature } from \"~/admin/features/users/checkEmail/index.js\";\nimport { UserFormFeature } from \"./feature.js\";\nimport { EMAIL_EXISTS_HERE } from \"./UserFormPresenter.js\";\n\nconst user = {\n id: \"user-1\",\n email: \"person@example.com\",\n firstName: \"Some\",\n lastName: \"Person\",\n avatar: null,\n createdOn: \"2026-10-23T00:00:00.000Z\",\n external: false\n};\n\nconst emailStatus = (status: string) => {\n return { adminUsers: { checkEmail: { data: { status }, error: null } } };\n};\n\nconst userResponse = (data: typeof user | null, error: Record<string, any> | null = null) => {\n return { adminUsers: { user: { data, error } } };\n};\n\ndescribe(\"UserFormPresenter: creating or linking a user\", () => {\n let container: Container;\n let execute: ReturnType<typeof vi.fn>;\n\n const presenter = () => UserFormFeature.resolve(container).presenter;\n\n /** The GraphQL operations the presenter sent, by their operation name. */\n const operations = () => {\n return execute.mock.calls.map(([request]) => {\n return /(query|mutation) (\\w+)/.exec(request.query)?.[2];\n });\n };\n\n beforeEach(() => {\n container = new Container();\n execute = vi.fn();\n container.registerInstance(MainGraphQLClient, {\n execute\n } as unknown as MainGraphQLClient.Interface);\n\n CreateUserFeature.register(container);\n LinkUserFeature.register(container);\n CheckEmailFeature.register(container);\n UserFormFeature.register(container);\n });\n\n it(\"starts in create mode\", () => {\n expect(presenter().vm).toEqual({ mode: \"create\", emailError: null, saving: false });\n });\n\n it(\"stays in create mode for a new email\", async () => {\n execute.mockResolvedValue(emailStatus(\"AVAILABLE\"));\n const form = presenter();\n\n await form.checkEmail(\"new@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: null });\n });\n\n it(\"switches to link mode for an email with an account in another tenant\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_ELSEWHERE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"link\", emailError: null });\n });\n\n it(\"shows an email error for a user already in this tenant\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_HERE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: EMAIL_EXISTS_HERE });\n });\n\n it(\"goes back to create mode when the email changes to a new one\", async () => {\n execute.mockResolvedValueOnce(emailStatus(\"EXISTS_ELSEWHERE\"));\n execute.mockResolvedValueOnce(emailStatus(\"AVAILABLE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n await form.checkEmail(\"someone-new@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: null });\n });\n\n it(\"doesn't check an incomplete email, or the same email twice\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_ELSEWHERE\"));\n const form = presenter();\n\n await form.checkEmail(\"person@\");\n await form.checkEmail(\"person@example.com\");\n await form.checkEmail(\" Person@example.com \");\n\n expect(operations()).toEqual([\"CheckEmail\"]);\n expect(form.vm.mode).toBe(\"link\");\n });\n\n it(\"checks the email as typed, so a mixed-case email in this tenant is found\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_HERE\"));\n const form = presenter();\n\n await form.checkEmail(\" Foo@X.com \");\n\n expect(execute.mock.calls[0][0].variables).toEqual({ email: \"Foo@X.com\" });\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: EMAIL_EXISTS_HERE });\n });\n\n it(\"keeps the latest email's result when an earlier check answers last\", async () => {\n let answerFirst: (value: unknown) => void = () => {};\n execute.mockReturnValueOnce(new Promise(resolve => (answerFirst = resolve)));\n execute.mockResolvedValueOnce(emailStatus(\"AVAILABLE\"));\n const form = presenter();\n\n const first = form.checkEmail(\"person@example.com\");\n await form.checkEmail(\"someone-new@example.com\");\n answerFirst(emailStatus(\"EXISTS_ELSEWHERE\"));\n await first;\n\n expect(form.vm.mode).toBe(\"create\");\n });\n\n it(\"stays in create mode when the check fails\", async () => {\n execute.mockRejectedValue(new Error(\"Network error\"));\n const form = presenter();\n\n await form.checkEmail(\"person@example.com\");\n\n expect(form.vm).toMatchObject({ mode: \"create\", emailError: null });\n });\n\n it(\"creates the user in create mode\", async () => {\n execute.mockResolvedValue(userResponse(user));\n const form = presenter();\n\n const result = await form.submit({\n email: user.email,\n firstName: \"Some\",\n lastName: \"Person\",\n password: \"SecurePass123!\"\n });\n\n expect(result).toEqual({ type: \"created\", user });\n expect(operations()).toEqual([\"CreateUser\"]);\n });\n\n it(\"links the account in link mode, sending only the email, roles and teams\", async () => {\n execute.mockResolvedValueOnce(emailStatus(\"EXISTS_ELSEWHERE\"));\n execute.mockResolvedValueOnce(userResponse(user));\n const form = presenter();\n await form.checkEmail(user.email);\n\n const result = await form.submit({\n email: user.email,\n firstName: \"Typed\",\n password: \"Ignored123!\",\n roles: [{ id: \"editors\" }],\n teams: []\n });\n\n expect(result).toEqual({ type: \"linked\", user });\n expect(operations()).toEqual([\"CheckEmail\", \"LinkUser\"]);\n expect(execute.mock.calls[1][0].variables).toEqual({\n data: { email: user.email, roles: [{ id: \"editors\" }], teams: [] }\n });\n expect(form.vm.saving).toBe(false);\n });\n\n it(\"switches to link mode when creating finds an account in another tenant\", async () => {\n execute.mockResolvedValue(\n userResponse(null, {\n code: \"Cognito/Account/ExistsInOtherTenant\",\n message: \"This email already has an account in another tenant. Link it instead.\",\n data: null\n })\n );\n const form = presenter();\n\n const result = await form.submit({ email: user.email, password: \"SecurePass123!\" });\n\n expect(result).toEqual({ type: \"linkRequired\" });\n expect(form.vm).toMatchObject({ mode: \"link\", emailError: null, saving: false });\n\n // The email is known now, so leaving the field doesn't check it again.\n await form.checkEmail(user.email);\n expect(operations()).toEqual([\"CreateUser\"]);\n });\n\n it(\"reports any other error and stays in create mode\", async () => {\n execute.mockResolvedValue(\n userResponse(null, { code: \"AdminUser/Validation\", message: \"Invalid.\", data: null })\n );\n const form = presenter();\n\n const result = await form.submit({ email: user.email, password: \"SecurePass123!\" });\n\n expect(result).toEqual({ type: \"failed\", message: \"Invalid.\" });\n expect(form.vm.mode).toBe(\"create\");\n });\n\n it(\"starts over in create mode after a reset\", async () => {\n execute.mockResolvedValue(emailStatus(\"EXISTS_ELSEWHERE\"));\n const form = presenter();\n await form.checkEmail(user.email);\n\n form.reset();\n\n expect(form.vm).toEqual({ mode: \"create\", emailError: null, saving: false });\n });\n});\n"],"names":["user","emailStatus","status","userResponse","data","error","describe","container","execute","presenter","UserFormFeature","operations","request","beforeEach","Container","vi","MainGraphQLClient","CreateUserFeature","LinkUserFeature","CheckEmailFeature","it","expect","form","EMAIL_EXISTS_HERE","answerFirst","Promise","resolve","first","Error","result"],"mappings":";;;;;;;;AASA,MAAMA,OAAO;IACT,IAAI;IACJ,OAAO;IACP,WAAW;IACX,UAAU;IACV,QAAQ;IACR,WAAW;IACX,UAAU;AACd;AAEA,MAAMC,cAAc,CAACC,SACV;QAAE,YAAY;YAAE,YAAY;gBAAE,MAAM;oBAAEA;gBAAO;gBAAG,OAAO;YAAK;QAAE;IAAE,CAAC;AAG5E,MAAMC,eAAe,CAACC,MAA0BC,QAAoC,IAAI,GAC7E;QAAE,YAAY;YAAE,MAAM;gBAAED;gBAAMC;YAAM;QAAE;IAAE,CAAC;AAGpDC,SAAS,iDAAiD;IACtD,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,YAAY,IAAMC,gBAAgB,OAAO,CAACH,WAAW,SAAS;IAGpE,MAAMI,aAAa,IACRH,QAAQ,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAACI,QAAQ,GAC7B,yBAAyB,IAAI,CAACA,QAAQ,KAAK,GAAG,CAAC,EAAE;IAIhEC,WAAW;QACPN,YAAY,IAAIO;QAChBN,UAAUO,GAAG,EAAE;QACfR,UAAU,gBAAgB,CAACS,mBAAmB;YAC1CR;QACJ;QAEAS,kBAAkB,QAAQ,CAACV;QAC3BW,gBAAgB,QAAQ,CAACX;QACzBY,kBAAkB,QAAQ,CAACZ;QAC3BG,gBAAgB,QAAQ,CAACH;IAC7B;IAEAa,GAAG,yBAAyB;QACxBC,OAAOZ,YAAY,EAAE,EAAE,OAAO,CAAC;YAAE,MAAM;YAAU,YAAY;YAAM,QAAQ;QAAM;IACrF;IAEAW,GAAG,wCAAwC;QACvCZ,QAAQ,iBAAiB,CAACP,YAAY;QACtC,MAAMqB,OAAOb;QAEb,MAAMa,KAAK,UAAU,CAAC;QAEtBD,OAAOC,KAAK,EAAE,EAAE,aAAa,CAAC;YAA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QAAQ,iBAAiB,CAACP,YAAY;QACtC,MAAMqB,OAAOb;QACb,MAAMa,KAAK,UAAU,CAACtB,KAAK,KAAK;QAEhCsB,KAAK,KAAK;QAEVD,OAAOC,KAAK,EAAE,EAAE,OAAO,CAAC;YAAE,MAAM;YAAU,YAAY;YAAM,QAAQ;QAAM;IAC9E;AACJ"}
|
package/admin/routes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin/routes.js","sources":["../../src/admin/routes.ts"],"sourcesContent":["import { Route } from \"@webiny/app-admin\";\n\nexport const Routes = {\n Users: {\n List: new Route({\n name: \"Cognito/Users/List\",\n path: \"/admin-users\",\n params: z => {\n return {\n id: z.string().optional(),\n new: z.boolean().optional()\n };\n }\n }),\n Account: new Route({\n name: \"Cognito/Users/Account\",\n path: \"/account\"\n })\n }\n};\n"],"names":["Routes","Route","z"],"mappings":";AAEO,MAAMA,SAAS;IAClB,OAAO;QACH,MAAM,IAAIC,MAAM;YACZ,MAAM;YACN,MAAM;YACN,QAAQC,CAAAA,IACG;oBACH,IAAIA,EAAE,MAAM,GAAG,QAAQ;oBACvB,KAAKA,EAAE,OAAO,GAAG,QAAQ;gBAC7B;
|
|
1
|
+
{"version":3,"file":"admin/routes.js","sources":["../../src/admin/routes.ts"],"sourcesContent":["import { Route } from \"@webiny/app-admin\";\n\nexport const Routes = {\n Users: {\n List: new Route({\n name: \"Cognito/Users/List\",\n path: \"/admin-users\",\n params: z => {\n return {\n id: z.string().optional(),\n new: z.boolean().optional()\n };\n }\n }),\n Account: new Route({\n name: \"Cognito/Users/Account\",\n path: \"/account\"\n })\n }\n};\n"],"names":["Routes","Route","z"],"mappings":";AAEO,MAAMA,SAAS;IAClB,OAAO;QACH,MAAM,IAAIC,MAAM;YACZ,MAAM;YACN,MAAM;YACN,QAAQC,CAAAA,IACG;oBACH,IAAIA,EAAE,MAAM,GAAG,QAAQ;oBACvB,KAAKA,EAAE,OAAO,GAAG,QAAQ;gBAC7B,CAAC;QAET;QACA,SAAS,IAAID,MAAM;YACf,MAAM;YACN,MAAM;QACV;IACJ;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin/ui/views/Users/UsersDataList.js","sources":["../../../../../src/admin/ui/views/Users/UsersDataList.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useState } from \"react\";\nimport orderBy from \"lodash/orderBy.js\";\nimport { useFeature } from \"@webiny/app\";\nimport { Avatar, Button, Grid, Select, Tooltip } from \"@webiny/admin-ui\";\nimport { ReactComponent as AddIcon } from \"@webiny/icons/add.svg\";\nimport { i18n } from \"@webiny/app/i18n/index.js\";\nimport { useSecurity } from \"@webiny/app-admin\";\nimport { List, DataList, DataListModal, DeleteIcon } from \"@webiny/admin-ui\";\nimport { useRouter, useSnackbar, useConfirmationDialog, SearchUI } from \"@webiny/app-admin\";\nimport { ListUsersFeature } from \"~/admin/features/users/listUsers/index.js\";\nimport { DeleteUserFeature } from \"~/admin/features/users/deleteUser/index.js\";\nimport { deserializeSorters } from \"../utils.js\";\nimport { Routes } from \"~/admin/routes.js\";\nimport type { UserItem } from \"~/admin/ui/UserItem.js\";\n\nconst t = i18n.ns(\"app-identity/admin/users/data-list\");\n\nconst SORTERS = [\n {\n label: t`Newest to oldest`,\n sorter: \"createdOn_DESC\"\n },\n {\n label: t`Oldest to newest`,\n sorter: \"createdOn_ASC\"\n },\n {\n label: t`Email A-Z`,\n sorter: \"email_ASC\"\n },\n {\n label: t`Email Z-A`,\n sorter: \"email_DESC\"\n }\n];\n\ninterface FilterUsersCallable {\n (user: Pick<UserItem, \"email\" | \"firstName\" | \"lastName\">): boolean;\n}\n\nconst UsersDataList = () => {\n const [filter, setFilter] = useState(\"\");\n const [sort, setSort] = useState<string>(SORTERS[0].sorter);\n const [users, setUsers] = useState<UserItem[]>([]);\n const [usersLoading, setUsersLoading] = useState(true);\n const [deleteLoading, setDeleteLoading] = useState(false);\n const { identity } = useSecurity();\n const { goToRoute } = useRouter();\n const { showSnackbar } = useSnackbar();\n const { showConfirmation } = useConfirmationDialog({\n dataTestId: \"default-data-list.delete-dialog\",\n title: \"Delete user\",\n message: \"Are you sure you want to delete this user? This action cannot be undone.\"\n });\n\n const { useCase: listUsers } = useFeature(ListUsersFeature);\n const { useCase: deleteUser } = useFeature(DeleteUserFeature);\n\n const fetchUsers = useCallback(() => {\n setUsersLoading(true);\n listUsers.execute().then(data => {\n setUsers((data || []) as UserItem[]);\n setUsersLoading(false);\n });\n }, [listUsers]);\n\n useEffect(() => {\n fetchUsers();\n }, []);\n\n const filterUsers = useCallback<FilterUsersCallable>(\n ({ email, firstName, lastName }) => {\n return (\n email.toLowerCase().includes(filter) ||\n firstName.toLowerCase().includes(filter) ||\n lastName.toLowerCase().includes(filter)\n );\n },\n [filter]\n );\n\n const sortUsers = useCallback(\n (list: UserItem[]) => {\n if (!sort) {\n return list;\n }\n const [key, sortBy] = deserializeSorters(sort);\n return orderBy(list, [key], [sortBy]);\n },\n [sort]\n );\n\n const filteredData = filter === \"\" ? users : users.filter(filterUsers);\n const userList = sortUsers(filteredData);\n const id = new URLSearchParams(location.search).get(\"id\");\n\n const deleteItem = useCallback(\n (item: Pick<UserItem, \"id\" | \"email\">) => {\n showConfirmation(async () => {\n setDeleteLoading(true);\n try {\n await deleteUser.execute({ id: item.id });\n showSnackbar(t`User \"{email}\" deleted.`({ email: item.email }));\n fetchUsers();\n\n if (id === item.id) {\n goToRoute(Routes.Users.List);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n showSnackbar(message);\n } finally {\n setDeleteLoading(false);\n }\n });\n },\n [id, deleteUser, fetchUsers]\n );\n\n const usersDataListModalOverlay = useMemo(\n () => (\n <DataListModal.Content>\n <Grid>\n <Grid.Column span={12}>\n <Select\n value={sort}\n onChange={setSort}\n label={t`Sort by`}\n options={SORTERS.map(({ label, sorter: value }) => ({\n label,\n value\n }))}\n />\n </Grid.Column>\n </Grid>\n </DataListModal.Content>\n ),\n [sort]\n );\n\n const loading = usersLoading || deleteLoading;\n\n return (\n <DataList\n title={t`Admin Users`}\n actions={\n <Button\n text={t`New`}\n icon={<AddIcon />}\n size={\"sm\"}\n className={\"ml-xs\"}\n data-testid=\"new-record-button\"\n onClick={() => {\n goToRoute(Routes.Users.List, { new: true });\n }}\n />\n }\n data={userList}\n loading={loading}\n search={\n <SearchUI\n value={filter}\n onChange={setFilter}\n inputPlaceholder={t`Search users...`}\n />\n }\n modalOverlay={usersDataListModalOverlay}\n modalOverlayAction={<DataListModal.Trigger data-testid={\"default-data-list.filter\"} />}\n showOptions={{\n refresh: false\n }}\n >\n {({ data }: { data: UserItem[] }) => (\n <List data-testid=\"default-data-list\">\n {data.map(item => (\n <List.Item\n key={item.id}\n selected={item.id === id}\n title={`${item.firstName} ${item.lastName}`}\n description={item.email}\n icon={\n <Avatar\n image={\n <Avatar.Image\n src={item.avatar ? item.avatar.src : undefined}\n alt={item.firstName}\n />\n }\n fallback={\n <Avatar.Fallback delayMs={0}>\n {item.firstName ? item.firstName.charAt(0) : \"A\"}\n </Avatar.Fallback>\n }\n />\n }\n onClick={() => {\n goToRoute(Routes.Users.List, { id: item.id });\n }}\n actions={\n identity && identity.id !== item.id ? (\n <DeleteIcon\n onClick={() => deleteItem(item)}\n data-testid={\"default-data-list.delete\"}\n />\n ) : (\n <Tooltip\n content={\n <span>{t`You can't delete your own user account.`}</span>\n }\n trigger={<DeleteIcon disabled />}\n />\n )\n }\n />\n ))}\n </List>\n )}\n </DataList>\n );\n};\n\nexport default UsersDataList;\n"],"names":["t","i18n","SORTERS","UsersDataList","filter","setFilter","useState","sort","setSort","users","setUsers","usersLoading","setUsersLoading","deleteLoading","setDeleteLoading","identity","useSecurity","goToRoute","useRouter","showSnackbar","useSnackbar","showConfirmation","useConfirmationDialog","listUsers","useFeature","ListUsersFeature","deleteUser","DeleteUserFeature","fetchUsers","useCallback","data","useEffect","filterUsers","email","firstName","lastName","sortUsers","list","key","sortBy","deserializeSorters","orderBy","filteredData","userList","id","URLSearchParams","location","deleteItem","item","Routes","error","message","Error","usersDataListModalOverlay","useMemo","DataListModal","Grid","Select","label","value","loading","DataList","Button","AddIcon","SearchUI","List","Avatar","undefined","DeleteIcon","Tooltip"],"mappings":";;;;;;;;;;;AAeA,MAAMA,IAAIC,KAAK,EAAE,CAAC;AAElB,MAAMC,UAAU;IACZ;QACI,OAAOF,CAAC,CAAC,gBAAgB,CAAC;QAC1B,QAAQ;IACZ;IACA;QACI,OAAOA,CAAC,CAAC,gBAAgB,CAAC;QAC1B,QAAQ;IACZ;IACA;QACI,OAAOA,CAAC,CAAC,SAAS,CAAC;QACnB,QAAQ;IACZ;IACA;QACI,OAAOA,CAAC,CAAC,SAAS,CAAC;QACnB,QAAQ;IACZ;CACH;AAMD,MAAMG,gBAAgB;IAClB,MAAM,CAACC,QAAQC,UAAU,GAAGC,SAAS;IACrC,MAAM,CAACC,MAAMC,QAAQ,GAAGF,SAAiBJ,OAAO,CAAC,EAAE,CAAC,MAAM;IAC1D,MAAM,CAACO,OAAOC,SAAS,GAAGJ,SAAqB,EAAE;IACjD,MAAM,CAACK,cAAcC,gBAAgB,GAAGN,SAAS;IACjD,MAAM,CAACO,eAAeC,iBAAiB,GAAGR,SAAS;IACnD,MAAM,EAAES,QAAQ,EAAE,GAAGC;IACrB,MAAM,EAAEC,SAAS,EAAE,GAAGC;IACtB,MAAM,EAAEC,YAAY,EAAE,GAAGC;IACzB,MAAM,EAAEC,gBAAgB,EAAE,GAAGC,sBAAsB;QAC/C,YAAY;QACZ,OAAO;QACP,SAAS;IACb;IAEA,MAAM,EAAE,SAASC,SAAS,EAAE,GAAGC,WAAWC;IAC1C,MAAM,EAAE,SAASC,UAAU,EAAE,GAAGF,WAAWG;IAE3C,MAAMC,aAAaC,YAAY;QAC3BjB,gBAAgB;QAChBW,UAAU,OAAO,GAAG,IAAI,CAACO,CAAAA;YACrBpB,SAAUoB,QAAQ,EAAE;YACpBlB,gBAAgB;QACpB;IACJ,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AS;;oBAG3B,wBACI,oBAACkB,OAAO,QAAQ;wBAAC,SAAS;uBACrBlB,KAAK,SAAS,GAAGA,KAAK,SAAS,CAAC,MAAM,CAAC,KAAK;;gBAK7D,SAAS;oBACL/B,UAAUgC,OAAO,KAAK,CAAC,IAAI,EAAE;wBAAE,IAAID,KAAK,EAAE;oBAAC;gBAC/C;gBACA,SACIjC,YAAYA,SAAS,EAAE,KAAKiC,KAAK,EAAE,GAAG,WAAH,GAC/B,oBAACoB,YAAUA;oBACP,SAAS,IAAMrB,WAAWC;oBAC1B,eAAa;mCAGjB,oBAACqB,SAAOA;oBACJ,uBACI,oBAAC,cAAMrE,CAAC,CAAC,uCAAuC,CAAC;oBAErD,uBAAS,oBAACoE,YAAUA;wBAAC;;;;AAU7D;AAEA,4BAAejE"}
|
|
1
|
+
{"version":3,"file":"admin/ui/views/Users/UsersDataList.js","sources":["../../../../../src/admin/ui/views/Users/UsersDataList.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useState } from \"react\";\nimport orderBy from \"lodash/orderBy.js\";\nimport { useFeature } from \"@webiny/app\";\nimport { Avatar, Button, Grid, Select, Tooltip } from \"@webiny/admin-ui\";\nimport { ReactComponent as AddIcon } from \"@webiny/icons/add.svg\";\nimport { i18n } from \"@webiny/app/i18n/index.js\";\nimport { useSecurity } from \"@webiny/app-admin\";\nimport { List, DataList, DataListModal, DeleteIcon } from \"@webiny/admin-ui\";\nimport { useRouter, useSnackbar, useConfirmationDialog, SearchUI } from \"@webiny/app-admin\";\nimport { ListUsersFeature } from \"~/admin/features/users/listUsers/index.js\";\nimport { DeleteUserFeature } from \"~/admin/features/users/deleteUser/index.js\";\nimport { deserializeSorters } from \"../utils.js\";\nimport { Routes } from \"~/admin/routes.js\";\nimport type { UserItem } from \"~/admin/ui/UserItem.js\";\n\nconst t = i18n.ns(\"app-identity/admin/users/data-list\");\n\nconst SORTERS = [\n {\n label: t`Newest to oldest`,\n sorter: \"createdOn_DESC\"\n },\n {\n label: t`Oldest to newest`,\n sorter: \"createdOn_ASC\"\n },\n {\n label: t`Email A-Z`,\n sorter: \"email_ASC\"\n },\n {\n label: t`Email Z-A`,\n sorter: \"email_DESC\"\n }\n];\n\ninterface FilterUsersCallable {\n (user: Pick<UserItem, \"email\" | \"firstName\" | \"lastName\">): boolean;\n}\n\nconst UsersDataList = () => {\n const [filter, setFilter] = useState(\"\");\n const [sort, setSort] = useState<string>(SORTERS[0].sorter);\n const [users, setUsers] = useState<UserItem[]>([]);\n const [usersLoading, setUsersLoading] = useState(true);\n const [deleteLoading, setDeleteLoading] = useState(false);\n const { identity } = useSecurity();\n const { goToRoute } = useRouter();\n const { showSnackbar } = useSnackbar();\n const { showConfirmation } = useConfirmationDialog({\n dataTestId: \"default-data-list.delete-dialog\",\n title: \"Delete user\",\n message: \"Are you sure you want to delete this user? This action cannot be undone.\"\n });\n\n const { useCase: listUsers } = useFeature(ListUsersFeature);\n const { useCase: deleteUser } = useFeature(DeleteUserFeature);\n\n const fetchUsers = useCallback(() => {\n setUsersLoading(true);\n listUsers.execute().then(data => {\n setUsers((data || []) as UserItem[]);\n setUsersLoading(false);\n });\n }, [listUsers]);\n\n useEffect(() => {\n fetchUsers();\n }, []);\n\n const filterUsers = useCallback<FilterUsersCallable>(\n ({ email, firstName, lastName }) => {\n return (\n email.toLowerCase().includes(filter) ||\n firstName.toLowerCase().includes(filter) ||\n lastName.toLowerCase().includes(filter)\n );\n },\n [filter]\n );\n\n const sortUsers = useCallback(\n (list: UserItem[]) => {\n if (!sort) {\n return list;\n }\n const [key, sortBy] = deserializeSorters(sort);\n return orderBy(list, [key], [sortBy]);\n },\n [sort]\n );\n\n const filteredData = filter === \"\" ? users : users.filter(filterUsers);\n const userList = sortUsers(filteredData);\n const id = new URLSearchParams(location.search).get(\"id\");\n\n const deleteItem = useCallback(\n (item: Pick<UserItem, \"id\" | \"email\">) => {\n showConfirmation(async () => {\n setDeleteLoading(true);\n try {\n await deleteUser.execute({ id: item.id });\n showSnackbar(t`User \"{email}\" deleted.`({ email: item.email }));\n fetchUsers();\n\n if (id === item.id) {\n goToRoute(Routes.Users.List);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n showSnackbar(message);\n } finally {\n setDeleteLoading(false);\n }\n });\n },\n [id, deleteUser, fetchUsers]\n );\n\n const usersDataListModalOverlay = useMemo(\n () => (\n <DataListModal.Content>\n <Grid>\n <Grid.Column span={12}>\n <Select\n value={sort}\n onChange={setSort}\n label={t`Sort by`}\n options={SORTERS.map(({ label, sorter: value }) => ({\n label,\n value\n }))}\n />\n </Grid.Column>\n </Grid>\n </DataListModal.Content>\n ),\n [sort]\n );\n\n const loading = usersLoading || deleteLoading;\n\n return (\n <DataList\n title={t`Admin Users`}\n actions={\n <Button\n text={t`New`}\n icon={<AddIcon />}\n size={\"sm\"}\n className={\"ml-xs\"}\n data-testid=\"new-record-button\"\n onClick={() => {\n goToRoute(Routes.Users.List, { new: true });\n }}\n />\n }\n data={userList}\n loading={loading}\n search={\n <SearchUI\n value={filter}\n onChange={setFilter}\n inputPlaceholder={t`Search users...`}\n />\n }\n modalOverlay={usersDataListModalOverlay}\n modalOverlayAction={<DataListModal.Trigger data-testid={\"default-data-list.filter\"} />}\n showOptions={{\n refresh: false\n }}\n >\n {({ data }: { data: UserItem[] }) => (\n <List data-testid=\"default-data-list\">\n {data.map(item => (\n <List.Item\n key={item.id}\n selected={item.id === id}\n title={`${item.firstName} ${item.lastName}`}\n description={item.email}\n icon={\n <Avatar\n image={\n <Avatar.Image\n src={item.avatar ? item.avatar.src : undefined}\n alt={item.firstName}\n />\n }\n fallback={\n <Avatar.Fallback delayMs={0}>\n {item.firstName ? item.firstName.charAt(0) : \"A\"}\n </Avatar.Fallback>\n }\n />\n }\n onClick={() => {\n goToRoute(Routes.Users.List, { id: item.id });\n }}\n actions={\n identity && identity.id !== item.id ? (\n <DeleteIcon\n onClick={() => deleteItem(item)}\n data-testid={\"default-data-list.delete\"}\n />\n ) : (\n <Tooltip\n content={\n <span>{t`You can't delete your own user account.`}</span>\n }\n trigger={<DeleteIcon disabled />}\n />\n )\n }\n />\n ))}\n </List>\n )}\n </DataList>\n );\n};\n\nexport default UsersDataList;\n"],"names":["t","i18n","SORTERS","UsersDataList","filter","setFilter","useState","sort","setSort","users","setUsers","usersLoading","setUsersLoading","deleteLoading","setDeleteLoading","identity","useSecurity","goToRoute","useRouter","showSnackbar","useSnackbar","showConfirmation","useConfirmationDialog","listUsers","useFeature","ListUsersFeature","deleteUser","DeleteUserFeature","fetchUsers","useCallback","data","useEffect","filterUsers","email","firstName","lastName","sortUsers","list","key","sortBy","deserializeSorters","orderBy","filteredData","userList","id","URLSearchParams","location","deleteItem","item","Routes","error","message","Error","usersDataListModalOverlay","useMemo","DataListModal","Grid","Select","label","value","loading","DataList","Button","AddIcon","SearchUI","List","Avatar","undefined","DeleteIcon","Tooltip"],"mappings":";;;;;;;;;;;AAeA,MAAMA,IAAIC,KAAK,EAAE,CAAC;AAElB,MAAMC,UAAU;IACZ;QACI,OAAOF,CAAC,CAAC,gBAAgB,CAAC;QAC1B,QAAQ;IACZ;IACA;QACI,OAAOA,CAAC,CAAC,gBAAgB,CAAC;QAC1B,QAAQ;IACZ;IACA;QACI,OAAOA,CAAC,CAAC,SAAS,CAAC;QACnB,QAAQ;IACZ;IACA;QACI,OAAOA,CAAC,CAAC,SAAS,CAAC;QACnB,QAAQ;IACZ;CACH;AAMD,MAAMG,gBAAgB;IAClB,MAAM,CAACC,QAAQC,UAAU,GAAGC,SAAS;IACrC,MAAM,CAACC,MAAMC,QAAQ,GAAGF,SAAiBJ,OAAO,CAAC,EAAE,CAAC,MAAM;IAC1D,MAAM,CAACO,OAAOC,SAAS,GAAGJ,SAAqB,EAAE;IACjD,MAAM,CAACK,cAAcC,gBAAgB,GAAGN,SAAS;IACjD,MAAM,CAACO,eAAeC,iBAAiB,GAAGR,SAAS;IACnD,MAAM,EAAES,QAAQ,EAAE,GAAGC;IACrB,MAAM,EAAEC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mC,MAAIA;YAAC,eAAY;WACbnC,KAAK,GAAG,CAACkB,CAAAA,OAAAA,WAAAA,GACN,oBAACiB,KAAK,IAAI;gBACN,KAAKjB,KAAK,EAAE;gBACZ,UAAUA,KAAK,EAAE,KAAKJ;gBACtB,OAAO,GAAGI,KAAK,SAAS,CAAC,CAAC,EAAEA,KAAK,QAAQ,EAAE;gBAC3C,aAAaA,KAAK,KAAK;gBACvB,oBACI,oBAACkB,QAAMA;oBACH,qBACI,oBAACA,OAAO,KAAK;wBACT,KAAKlB,KAAK,MAAM,GAAGA,KAAK,MAAM,CAAC,GAAG,GAAGmB;wBACrC,KAAKnB,KAAK,SAAS;;oBAG3B,wBACI,oBAACkB,OAAO,QAAQ;wBAAC,SAAS;uBACrBlB,KAAK,SAAS,GAAGA,KAAK,SAAS,CAAC,MAAM,CAAC,KAAK;;gBAK7D,SAAS;oBACL/B,UAAUgC,OAAO,KAAK,CAAC,IAAI,EAAE;wBAAE,IAAID,KAAK,EAAE;oBAAC;gBAC/C;gBACA,SACIjC,YAAYA,SAAS,EAAE,KAAKiC,KAAK,EAAE,GAAG,WAAH,GAC/B,oBAACoB,YAAUA;oBACP,SAAS,IAAMrB,WAAWC;oBAC1B,eAAa;mCAGjB,oBAACqB,SAAOA;oBACJ,uBACI,oBAAC,cAAMrE,CAAC,CAAC,uCAAuC,CAAC;oBAErD,uBAAS,oBAACoE,YAAUA;wBAAC;;;;AAU7D;AAEA,4BAAejE"}
|
|
@@ -1,21 +1,22 @@
|
|
|
1
|
-
import __rslib_svgr_url__0__ from "../../../../static/svg/search.
|
|
2
|
-
import
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
1
|
+
import __rslib_svgr_url__0__ from "../../../../static/svg/search.f9a0a1d6.svg";
|
|
2
|
+
import { createElement } from "react";
|
|
3
|
+
const attributes = {
|
|
4
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
5
|
+
xmlSpace: "preserve",
|
|
6
|
+
width: "24",
|
|
7
|
+
height: "24",
|
|
8
|
+
viewBox: "0 0 24 24"
|
|
9
|
+
};
|
|
10
|
+
const innerHTML = {
|
|
11
|
+
__html: "<path fill=\"none\" d=\"M0 0h24v24H0z\"/><path fill=\"currentColor\" d=\"M15.5 14h-.79l-.28-.27a6.5 6.5 0 0 0 1.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 0 0-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 0 0 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0s.41-1.08 0-1.49zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14\"/>"
|
|
12
|
+
};
|
|
13
|
+
const ReactComponent = ({ children, ...props })=>createElement("svg", {
|
|
14
|
+
...attributes,
|
|
15
|
+
...props,
|
|
16
|
+
dangerouslySetInnerHTML: innerHTML
|
|
17
|
+
});
|
|
17
18
|
const search = __rslib_svgr_url__0__;
|
|
18
19
|
export default search;
|
|
19
|
-
export {
|
|
20
|
+
export { ReactComponent };
|
|
20
21
|
|
|
21
22
|
//# sourceMappingURL=search.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin/ui/views/Users/search.js","sources":["../../../../../src/admin/ui/views/Users/search.svg"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"admin/ui/views/Users/search.js","sources":["../../../../../src/admin/ui/views/Users/search.svg"],"sourcesContent":["import { createElement } from \"react\";\n\nconst attributes = {\"xmlns\":\"http://www.w3.org/2000/svg\",\"xmlSpace\":\"preserve\",\"width\":\"24\",\"height\":\"24\",\"viewBox\":\"0 0 24 24\"};\nconst innerHTML = { __html: \"<path fill=\\\"none\\\" d=\\\"M0 0h24v24H0z\\\"/><path fill=\\\"currentColor\\\" d=\\\"M15.5 14h-.79l-.28-.27a6.5 6.5 0 0 0 1.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 0 0-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 0 0 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0s.41-1.08 0-1.49zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14\\\"/>\" };\n\nexport const ReactComponent = ({ children, ...props }) => {\n return createElement(\"svg\", { ...attributes, ...props, dangerouslySetInnerHTML: innerHTML });\n};\n\nexport default \"__RSLIB_SVGR_AUTO_PUBLIC_PATH__static/svg/search.f9a0a1d6.svg\";\n"],"names":["attributes","innerHTML","ReactComponent","children","props","createElement"],"mappings":";;AAEA,MAAMA,aAAa;IAAC,OAAQ;IAA6B,UAAW;IAAW,OAAQ;IAAK,QAAS;IAAK,SAAU;AAAW;AAC/H,MAAMC,YAAY;IAAE,QAAQ;AAA4W;AAEjY,MAAMC,iBAAiB,CAAC,EAAEC,QAAQ,EAAE,GAAGC,OAAO,GAC1CC,cAAc,OAAO;QAAE,GAAGL,UAAU;QAAE,GAAGI,KAAK;QAAE,yBAAyBH;IAAU;AAG9F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api/features/CognitoService/CognitoService.js","sources":["../../../../src/api/features/CognitoService/CognitoService.ts"],"sourcesContent":["import type { AdminCreateUserRequest } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoIdentityProvider } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoConfig, CognitoService as ServiceAbstraction } from \"./abstractions.js\";\nimport { adminDeleteSoftwareToken } from \"./adminDeleteSoftwareToken.js\";\n\nclass CognitoServiceImpl implements ServiceAbstraction.Interface {\n private cognito: CognitoIdentityProvider;\n\n constructor(private config: CognitoConfig.Interface) {\n this.cognito = new CognitoIdentityProvider({ region: config.region });\n }\n\n async getUser(username: string): Promise<ServiceAbstraction.User | null> {\n try {\n const response = await this.cognito.adminGetUser({\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n\n const attributes: Record<string, string> = {};\n for (const attribute of response.UserAttributes ?? []) {\n if (attribute.Name) {\n attributes[attribute.Name] = attribute.Value ?? \"\";\n }\n }\n\n return { username: response.Username ?? username, attributes };\n } catch (error) {\n if ((error as Error).name === \"UserNotFoundException\") {\n return null;\n }\n throw error;\n }\n }\n\n async createUser(params: {\n username: string;\n temporaryPassword: string;\n attributes: ServiceAbstraction.UserAttributes;\n }): Promise<void> {\n const createUserParams: AdminCreateUserRequest = {\n UserPoolId: this.config.userPoolId,\n Username: params.username,\n DesiredDeliveryMediums: [],\n ForceAliasCreation: false,\n MessageAction: \"SUPPRESS\",\n TemporaryPassword: params.temporaryPassword,\n UserAttributes: [\n {\n Name: \"given_name\",\n Value: params.attributes.givenName || \"\"\n },\n {\n Name: \"family_name\",\n Value: params.attributes.familyName || \"\"\n },\n {\n Name: \"preferred_username\",\n Value: params.attributes.preferredUsername\n },\n {\n Name: \"email\",\n Value: params.attributes.email\n },\n {\n Name: \"custom:id\",\n Value: params.attributes.customId\n }\n ]\n };\n\n await this.cognito.adminCreateUser(createUserParams);\n }\n\n async setEmailVerified(username: string): Promise<void> {\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: [\n {\n Name: \"email_verified\",\n Value: \"true\"\n }\n ]\n });\n }\n\n async setPermanentPassword(username: string, password: string): Promise<void> {\n await this.cognito.adminSetUserPassword({\n Permanent: true,\n Password: password,\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n }\n\n async updateUserAttributes(\n username: string,\n attributes: Record<string, string>\n ): Promise<void> {\n const userAttributes = Object.entries(attributes).map(([name, value]) => ({\n Name: name,\n Value: value\n }));\n\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: userAttributes\n });\n }\n\n async deleteUser(username: string): Promise<void> {\n await this.cognito.adminDeleteUser({\n UserPoolId: this.config.userPoolId,\n Username: username\n });\n }\n\n async resetMfa(username: string): Promise<void> {\n // Deletes the user's TOTP software token, so Cognito asks them to set up TOTP again on\n // their next sign-in. Only turning the factor off (`AdminSetUserMFAPreference`) isn't\n // enough: with MFA required in the pool, Cognito keeps asking for the old token.\n // A signed request, not the SDK command: see `adminDeleteSoftwareToken`.\n await adminDeleteSoftwareToken({\n region: this.config.region,\n userPoolId: this.config.userPoolId,\n username,\n credentials: this.cognito.config.credentials\n });\n }\n}\n\nexport const CognitoService = ServiceAbstraction.createImplementation({\n implementation: CognitoServiceImpl,\n dependencies: [CognitoConfig]\n});\n"],"names":["CognitoServiceImpl","config","CognitoIdentityProvider","username","response","attributes","attribute","error","params","createUserParams","password","userAttributes","Object","name","value","adminDeleteSoftwareToken","CognitoService","ServiceAbstraction","CognitoConfig"],"mappings":";;;AAKA,MAAMA;IAGF,YAAoBC,MAA+B,CAAE;aAAjCA,MAAM,GAANA;QAChB,IAAI,CAAC,OAAO,GAAG,IAAIC,wBAAwB;YAAE,QAAQD,OAAO,MAAM;QAAC;IACvE;IAEA,MAAM,QAAQE,QAAgB,EAA2C;QACrE,IAAI;YACA,MAAMC,WAAW,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;gBAC7C,UAAUD;gBACV,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YACtC;YAEA,MAAME,aAAqC,CAAC;YAC5C,KAAK,MAAMC,aAAaF,SAAS,cAAc,IAAI,EAAE,CACjD,IAAIE,UAAU,IAAI,EACdD,UAAU,CAACC,UAAU,IAAI,CAAC,GAAGA,UAAU,KAAK,IAAI;YAIxD,OAAO;gBAAE,UAAUF,SAAS,QAAQ,IAAID;gBAAUE;YAAW;QACjE,EAAE,OAAOE,OAAO;YACZ,IAAKA,AAAyB,4BAAzBA,MAAgB,IAAI,EACrB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3,"file":"api/features/CognitoService/CognitoService.js","sources":["../../../../src/api/features/CognitoService/CognitoService.ts"],"sourcesContent":["import type { AdminCreateUserRequest } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoIdentityProvider } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoConfig, CognitoService as ServiceAbstraction } from \"./abstractions.js\";\nimport { adminDeleteSoftwareToken } from \"./adminDeleteSoftwareToken.js\";\n\nclass CognitoServiceImpl implements ServiceAbstraction.Interface {\n private cognito: CognitoIdentityProvider;\n\n constructor(private config: CognitoConfig.Interface) {\n this.cognito = new CognitoIdentityProvider({ region: config.region });\n }\n\n async getUser(username: string): Promise<ServiceAbstraction.User | null> {\n try {\n const response = await this.cognito.adminGetUser({\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n\n const attributes: Record<string, string> = {};\n for (const attribute of response.UserAttributes ?? []) {\n if (attribute.Name) {\n attributes[attribute.Name] = attribute.Value ?? \"\";\n }\n }\n\n return { username: response.Username ?? username, attributes };\n } catch (error) {\n if ((error as Error).name === \"UserNotFoundException\") {\n return null;\n }\n throw error;\n }\n }\n\n async createUser(params: {\n username: string;\n temporaryPassword: string;\n attributes: ServiceAbstraction.UserAttributes;\n }): Promise<void> {\n const createUserParams: AdminCreateUserRequest = {\n UserPoolId: this.config.userPoolId,\n Username: params.username,\n DesiredDeliveryMediums: [],\n ForceAliasCreation: false,\n MessageAction: \"SUPPRESS\",\n TemporaryPassword: params.temporaryPassword,\n UserAttributes: [\n {\n Name: \"given_name\",\n Value: params.attributes.givenName || \"\"\n },\n {\n Name: \"family_name\",\n Value: params.attributes.familyName || \"\"\n },\n {\n Name: \"preferred_username\",\n Value: params.attributes.preferredUsername\n },\n {\n Name: \"email\",\n Value: params.attributes.email\n },\n {\n Name: \"custom:id\",\n Value: params.attributes.customId\n }\n ]\n };\n\n await this.cognito.adminCreateUser(createUserParams);\n }\n\n async setEmailVerified(username: string): Promise<void> {\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: [\n {\n Name: \"email_verified\",\n Value: \"true\"\n }\n ]\n });\n }\n\n async setPermanentPassword(username: string, password: string): Promise<void> {\n await this.cognito.adminSetUserPassword({\n Permanent: true,\n Password: password,\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n }\n\n async updateUserAttributes(\n username: string,\n attributes: Record<string, string>\n ): Promise<void> {\n const userAttributes = Object.entries(attributes).map(([name, value]) => ({\n Name: name,\n Value: value\n }));\n\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: userAttributes\n });\n }\n\n async deleteUser(username: string): Promise<void> {\n await this.cognito.adminDeleteUser({\n UserPoolId: this.config.userPoolId,\n Username: username\n });\n }\n\n async resetMfa(username: string): Promise<void> {\n // Deletes the user's TOTP software token, so Cognito asks them to set up TOTP again on\n // their next sign-in. Only turning the factor off (`AdminSetUserMFAPreference`) isn't\n // enough: with MFA required in the pool, Cognito keeps asking for the old token.\n // A signed request, not the SDK command: see `adminDeleteSoftwareToken`.\n await adminDeleteSoftwareToken({\n region: this.config.region,\n userPoolId: this.config.userPoolId,\n username,\n credentials: this.cognito.config.credentials\n });\n }\n}\n\nexport const CognitoService = ServiceAbstraction.createImplementation({\n implementation: CognitoServiceImpl,\n dependencies: [CognitoConfig]\n});\n"],"names":["CognitoServiceImpl","config","CognitoIdentityProvider","username","response","attributes","attribute","error","params","createUserParams","password","userAttributes","Object","name","value","adminDeleteSoftwareToken","CognitoService","ServiceAbstraction","CognitoConfig"],"mappings":";;;AAKA,MAAMA;IAGF,YAAoBC,MAA+B,CAAE;aAAjCA,MAAM,GAANA;QAChB,IAAI,CAAC,OAAO,GAAG,IAAIC,wBAAwB;YAAE,QAAQD,OAAO,MAAM;QAAC;IACvE;IAEA,MAAM,QAAQE,QAAgB,EAA2C;QACrE,IAAI;YACA,MAAMC,WAAW,MAAM,IAAI,CAAC,OAAO,CA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AEA,MAAM,qBAAqBA,QAAgB,EAAEO,QAAgB,EAAiB;QAC1E,MAAM,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC;YACpC,WAAW;YACX,UAAUA;YACV,UAAUP;YACV,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;QACtC;IACJ;IAEA,MAAM,qBACFA,QAAgB,EAChBE,UAAkC,EACrB;QACb,MAAMM,iBAAiBC,OAAO,OAAO,CAACP,YAAY,GAAG,CAAC,CAAC,CAACQ,MAAMC,MAAM,GAAM;gBACtE,MAAMD;gBACN,OAAOC;YACX,CAAC;QAED,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YACzC,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUX;YACV,gBAAgBQ;QACpB;IACJ;IAEA,MAAM,WAAWR,QAAgB,EAAiB;QAC9C,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC;YAC/B,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUA;QACd;IACJ;IAEA,MAAM,SAASA,QAAgB,EAAiB;QAK5C,MAAMY,yBAAyB;YAC3B,QAAQ,IAAI,CAAC,MAAM,CAAC,MAAM;YAC1B,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClCZ;YACA,aAAa,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW;QAChD;IACJ;AACJ;AAEO,MAAMa,gCAAiBC,eAAAA,oBAAuC,CAAC;IAClE,gBAAgBjB;IAChB,cAAc;QAACkB;KAAc;AACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api/features/CognitoService/adminDeleteSoftwareToken.js","sources":["../../../../src/api/features/CognitoService/adminDeleteSoftwareToken.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport type { Hash as HashInterface } from \"@smithy/types\";\nimport type { AwsCredentialIdentity, Provider, SourceData } from \"@smithy/types\";\nimport { SignatureV4 } from \"@smithy/signature-v4\";\n\n/**\n * Calls Cognito's `AdminDeleteSoftwareToken` as a signed HTTP request.\n *\n * Function bundles leave `@aws-sdk/*` out (`createRsbuildConfig.js`), so the API Lambda uses the\n * AWS SDK built into the Lambda runtime, and that SDK doesn't have `AdminDeleteSoftwareTokenCommand`\n * yet. `@smithy/*` is bundled, so this works on any runtime. Switch to the SDK command once the\n * Lambda runtime has it.\n */\nexport interface AdminDeleteSoftwareTokenParams {\n region: string;\n userPoolId: string;\n username: string;\n credentials: AwsCredentialIdentity | Provider<AwsCredentialIdentity>;\n}\n\nconst SERVICE = \"cognito-idp\";\nconst TARGET = \"AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken\";\n\nexport const adminDeleteSoftwareToken = async (\n params: AdminDeleteSoftwareTokenParams\n): Promise<void> => {\n const hostname = `${SERVICE}.${params.region}.amazonaws.com`;\n\n const signer = new SignatureV4({\n service: SERVICE,\n region: params.region,\n credentials: params.credentials,\n sha256: Sha256\n });\n\n const request = await signer.sign({\n method: \"POST\",\n protocol: \"https:\",\n hostname,\n path: \"/\",\n query: {},\n headers: {\n host: hostname,\n \"content-type\": \"application/x-amz-json-1.1\",\n \"x-amz-target\": TARGET\n },\n body: JSON.stringify({ UserPoolId: params.userPoolId, Username: params.username })\n });\n\n const response = await fetch(`https://${hostname}/`, {\n method: \"POST\",\n headers: request.headers,\n body: request.body\n });\n\n if (response.ok) {\n return;\n }\n\n const error = await toCognitoError(response);\n if (isNoSoftwareTokenError(error)) {\n // The user never set up TOTP, so there's no token to delete. That's already the state a\n // delete leads to: they set up TOTP on their next sign-in.\n return;\n }\n throw error;\n};\n\n/**\n * Cognito's answer for a user without a TOTP token:\n * `ResourceNotFoundException: Software token MFA has not been configured for this user.`\n * The name alone also covers a missing user pool, so the message must match too.\n */\nconst isNoSoftwareTokenError = (error: Error): boolean => {\n return (\n error.name === \"ResourceNotFoundException\" &&\n /software token mfa has not been configured/i.test(error.message)\n );\n};\n\n/**\n * Cognito answers a failed call with `{ \"__type\": \"...#UserNotFoundException\", \"message\": \"...\" }`.\n * The error gets the exception's name, as the SDK would give it.\n */\nconst toCognitoError = async (response: Response): Promise<Error> => {\n const text = await response.text();\n\n let body: { __type?: string; message?: string; Message?: string } = {};\n try {\n body = JSON.parse(text);\n } catch {\n // Not JSON: keep the raw text as the message.\n }\n\n const type = (body.__type ?? \"\").split(\"#\").pop() || `HTTP${response.status}`;\n const error = new Error(body.message ?? body.Message ?? (text || response.statusText));\n error.name = type;\n return error;\n};\n\nconst toBuffer = (data: SourceData): Buffer => {\n if (typeof data === \"string\") {\n return Buffer.from(data, \"utf8\");\n }\n if (ArrayBuffer.isView(data)) {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength);\n }\n return Buffer.from(data);\n};\n\n/**\n * SHA-256 (or HMAC-SHA-256 with a secret) for the signer, on Node's own crypto.\n */\nclass Sha256 implements HashInterface {\n private readonly hash;\n\n constructor(secret?: SourceData) {\n this.hash = secret ? createHmac(\"sha256\", toBuffer(secret)) : createHash(\"sha256\");\n }\n\n update(data: SourceData): void {\n this.hash.update(toBuffer(data));\n }\n\n async digest(): Promise<Uint8Array> {\n return new Uint8Array(this.hash.digest());\n }\n}\n"],"names":["SERVICE","TARGET","adminDeleteSoftwareToken","params","hostname","signer","SignatureV4","Sha256","request","JSON","response","fetch","error","toCognitoError","isNoSoftwareTokenError","text","body","type","Error","toBuffer","data","Buffer","ArrayBuffer","secret","createHmac","createHash","Uint8Array"],"mappings":";;AAoBA,MAAMA,UAAU;AAChB,MAAMC,SAAS;AAER,MAAMC,2BAA2B,OACpCC;IAEA,MAAMC,WAAW,GAAGJ,QAAQ,CAAC,EAAEG,OAAO,MAAM,CAAC,cAAc,CAAC;IAE5D,MAAME,SAAS,IAAIC,YAAY;QAC3B,SAASN;QACT,QAAQG,OAAO,MAAM;QACrB,aAAaA,OAAO,WAAW;QAC/B,QAAQI;IACZ;IAEA,MAAMC,UAAU,MAAMH,OAAO,IAAI,CAAC;QAC9B,QAAQ;QACR,UAAU;QACVD;QACA,MAAM;QACN,OAAO,CAAC;QACR,SAAS;YACL,MAAMA;YACN,gBAAgB;YAChB,gBAAgBH;QACpB;QACA,MAAMQ,KAAK,SAAS,CAAC;YAAE,YAAYN,OAAO,UAAU;YAAE,UAAUA,OAAO,QAAQ;QAAC;IACpF;IAEA,MAAMO,WAAW,MAAMC,MAAM,CAAC,QAAQ,EAAEP,SAAS,CAAC,CAAC,EAAE;QACjD,QAAQ;QACR,SAASI,QAAQ,OAAO;QACxB,MAAMA,QAAQ,IAAI;IACtB;IAEA,IAAIE,SAAS,EAAE,EACX;IAGJ,MAAME,QAAQ,MAAMC,eAAeH;IACnC,IAAII,uBAAuBF,QAGvB;IAEJ,MAAMA;AACV;AAOA,MAAME,yBAAyB,CAACF,QAExBA,AAAe,gCAAfA,MAAM,IAAI,IACV,8CAA8C,IAAI,CAACA,MAAM,OAAO;AAQxE,MAAMC,iBAAiB,OAAOH;IAC1B,MAAMK,OAAO,MAAML,SAAS,IAAI;IAEhC,IAAIM,OAAgE,CAAC;IACrE,IAAI;QACAA,OAAOP,KAAK,KAAK,CAACM;IACtB,EAAE,OAAM,CAER;IAEA,MAAME,OAAQD,AAAAA,CAAAA,KAAK,MAAM,IAAI,
|
|
1
|
+
{"version":3,"file":"api/features/CognitoService/adminDeleteSoftwareToken.js","sources":["../../../../src/api/features/CognitoService/adminDeleteSoftwareToken.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport type { Hash as HashInterface } from \"@smithy/types\";\nimport type { AwsCredentialIdentity, Provider, SourceData } from \"@smithy/types\";\nimport { SignatureV4 } from \"@smithy/signature-v4\";\n\n/**\n * Calls Cognito's `AdminDeleteSoftwareToken` as a signed HTTP request.\n *\n * Function bundles leave `@aws-sdk/*` out (`createRsbuildConfig.js`), so the API Lambda uses the\n * AWS SDK built into the Lambda runtime, and that SDK doesn't have `AdminDeleteSoftwareTokenCommand`\n * yet. `@smithy/*` is bundled, so this works on any runtime. Switch to the SDK command once the\n * Lambda runtime has it.\n */\nexport interface AdminDeleteSoftwareTokenParams {\n region: string;\n userPoolId: string;\n username: string;\n credentials: AwsCredentialIdentity | Provider<AwsCredentialIdentity>;\n}\n\nconst SERVICE = \"cognito-idp\";\nconst TARGET = \"AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken\";\n\nexport const adminDeleteSoftwareToken = async (\n params: AdminDeleteSoftwareTokenParams\n): Promise<void> => {\n const hostname = `${SERVICE}.${params.region}.amazonaws.com`;\n\n const signer = new SignatureV4({\n service: SERVICE,\n region: params.region,\n credentials: params.credentials,\n sha256: Sha256\n });\n\n const request = await signer.sign({\n method: \"POST\",\n protocol: \"https:\",\n hostname,\n path: \"/\",\n query: {},\n headers: {\n host: hostname,\n \"content-type\": \"application/x-amz-json-1.1\",\n \"x-amz-target\": TARGET\n },\n body: JSON.stringify({ UserPoolId: params.userPoolId, Username: params.username })\n });\n\n const response = await fetch(`https://${hostname}/`, {\n method: \"POST\",\n headers: request.headers,\n body: request.body\n });\n\n if (response.ok) {\n return;\n }\n\n const error = await toCognitoError(response);\n if (isNoSoftwareTokenError(error)) {\n // The user never set up TOTP, so there's no token to delete. That's already the state a\n // delete leads to: they set up TOTP on their next sign-in.\n return;\n }\n throw error;\n};\n\n/**\n * Cognito's answer for a user without a TOTP token:\n * `ResourceNotFoundException: Software token MFA has not been configured for this user.`\n * The name alone also covers a missing user pool, so the message must match too.\n */\nconst isNoSoftwareTokenError = (error: Error): boolean => {\n return (\n error.name === \"ResourceNotFoundException\" &&\n /software token mfa has not been configured/i.test(error.message)\n );\n};\n\n/**\n * Cognito answers a failed call with `{ \"__type\": \"...#UserNotFoundException\", \"message\": \"...\" }`.\n * The error gets the exception's name, as the SDK would give it.\n */\nconst toCognitoError = async (response: Response): Promise<Error> => {\n const text = await response.text();\n\n let body: { __type?: string; message?: string; Message?: string } = {};\n try {\n body = JSON.parse(text);\n } catch {\n // Not JSON: keep the raw text as the message.\n }\n\n const type = (body.__type ?? \"\").split(\"#\").pop() || `HTTP${response.status}`;\n const error = new Error(body.message ?? body.Message ?? (text || response.statusText));\n error.name = type;\n return error;\n};\n\nconst toBuffer = (data: SourceData): Buffer => {\n if (typeof data === \"string\") {\n return Buffer.from(data, \"utf8\");\n }\n if (ArrayBuffer.isView(data)) {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength);\n }\n return Buffer.from(data);\n};\n\n/**\n * SHA-256 (or HMAC-SHA-256 with a secret) for the signer, on Node's own crypto.\n */\nclass Sha256 implements HashInterface {\n private readonly hash;\n\n constructor(secret?: SourceData) {\n this.hash = secret ? createHmac(\"sha256\", toBuffer(secret)) : createHash(\"sha256\");\n }\n\n update(data: SourceData): void {\n this.hash.update(toBuffer(data));\n }\n\n async digest(): Promise<Uint8Array> {\n return new Uint8Array(this.hash.digest());\n }\n}\n"],"names":["SERVICE","TARGET","adminDeleteSoftwareToken","params","hostname","signer","SignatureV4","Sha256","request","JSON","response","fetch","error","toCognitoError","isNoSoftwareTokenError","text","body","type","Error","toBuffer","data","Buffer","ArrayBuffer","secret","createHmac","createHash","Uint8Array"],"mappings":";;AAoBA,MAAMA,UAAU;AAChB,MAAMC,SAAS;AAER,MAAMC,2BAA2B,OACpCC;IAEA,MAAMC,WAAW,GAAGJ,QAAQ,CAAC,EAAEG,OAAO,MAAM,CAAC,cAAc,CAAC;IAE5D,MAAME,SAAS,IAAIC,YAAY;QAC3B,SAASN;QACT,QAAQG,OAAO,MAAM;QACrB,aAAaA,OAAO,WAAW;QAC/B,QAAQI;IACZ;IAEA,MAAMC,UAAU,MAAMH,OAAO,IAAI,CAAC;QAC9B,QAAQ;QACR,UAAU;QACVD;QACA,MAAM;QACN,OAAO,CAAC;QACR,SAAS;YACL,MAAMA;YACN,gBAAgB;YAChB,gBAAgBH;QACpB;QACA,MAAMQ,KAAK,SAAS,CAAC;YAAE,YAAYN,OAAO,UAAU;YAAE,UAAUA,OAAO,QAAQ;QAAC;IACpF;IAEA,MAAMO,WAAW,MAAMC,MAAM,CA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C,OAAO,IAAIM,WAAW,IAAI,CAAC,IAAI,CAAC,MAAM;IAC1C;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api/features/CognitoService/adminDeleteSoftwareToken.test.js","sources":["../../../../src/api/features/CognitoService/adminDeleteSoftwareToken.test.ts"],"sourcesContent":["import { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport { adminDeleteSoftwareToken } from \"./adminDeleteSoftwareToken.js\";\n\nconst params = {\n region: \"eu-central-1\",\n userPoolId: \"eu-central-1_pool\",\n username: \"user-1\",\n credentials: async () => ({\n accessKeyId: \"AKIDEXAMPLE\",\n secretAccessKey: \"secret\",\n sessionToken: \"session-token\"\n })\n};\n\ndescribe(\"adminDeleteSoftwareToken\", () => {\n const fetchMock = vi.fn();\n\n beforeEach(() => {\n vi.useFakeTimers({ now: new Date(\"2026-11-07T10:00:00Z\"), toFake: [\"Date\"] });\n fetchMock.mockReset();\n vi.stubGlobal(\"fetch\", fetchMock);\n });\n\n afterEach(() => {\n vi.useRealTimers();\n vi.unstubAllGlobals();\n });\n\n it(\"sends a signed AdminDeleteSoftwareToken request to the pool's region\", async () => {\n fetchMock.mockResolvedValue(new Response(\"{}\", { status: 200 }));\n\n await adminDeleteSoftwareToken(params);\n\n expect(fetchMock).toHaveBeenCalledTimes(1);\n const [url, init] = fetchMock.mock.calls[0];\n expect(url).toBe(\"https://cognito-idp.eu-central-1.amazonaws.com/\");\n expect(init.method).toBe(\"POST\");\n expect(JSON.parse(init.body)).toEqual({\n UserPoolId: \"eu-central-1_pool\",\n Username: \"user-1\"\n });\n\n const headers = init.headers as Record<string, string>;\n expect(headers[\"x-amz-target\"]).toBe(\n \"AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken\"\n );\n expect(headers[\"content-type\"]).toBe(\"application/x-amz-json-1.1\");\n expect(headers[\"x-amz-date\"]).toBe(\"20261107T100000Z\");\n expect(headers[\"x-amz-security-token\"]).toBe(\"session-token\");\n expect(headers[\"authorization\"]).toMatch(\n /^AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE\\/20261107\\/eu-central-1\\/cognito-idp\\/aws4_request, SignedHeaders=[^,]*x-amz-target[^,]*, Signature=[0-9a-f]{64}$/\n );\n });\n\n it(\"throws Cognito's error with the exception's name and message\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"com.amazonaws.cognito#UserNotFoundException\",\n message: \"User does not exist.\"\n }),\n { status: 400 }\n )\n );\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error).toBeInstanceOf(Error);\n expect(error.name).toBe(\"UserNotFoundException\");\n expect(error.message).toBe(\"User does not exist.\");\n });\n\n it(\"treats a user without a TOTP token as done\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"ResourceNotFoundException\",\n message: \"Software token MFA has not been configured for this user.\"\n }),\n { status: 400 }\n )\n );\n\n await expect(adminDeleteSoftwareToken(params)).resolves.toBeUndefined();\n });\n\n it(\"still throws other ResourceNotFoundException errors\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"ResourceNotFoundException\",\n message: \"User pool eu-central-1_pool does not exist.\"\n }),\n { status: 400 }\n )\n );\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error.name).toBe(\"ResourceNotFoundException\");\n expect(error.message).toBe(\"User pool eu-central-1_pool does not exist.\");\n });\n\n it(\"keeps the raw text when Cognito's error isn't JSON\", async () => {\n fetchMock.mockResolvedValue(new Response(\"Service Unavailable\", { status: 503 }));\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error.name).toBe(\"HTTP503\");\n expect(error.message).toBe(\"Service Unavailable\");\n });\n});\n"],"names":["params","describe","fetchMock","vi","beforeEach","Date","afterEach","it","Response","adminDeleteSoftwareToken","expect","url","init","JSON","headers","error","e","Error"],"mappings":";;AAGA,MAAMA,SAAS;IACX,QAAQ;IACR,YAAY;IACZ,UAAU;IACV,aAAa,UAAa;YACtB,aAAa;YACb,iBAAiB;YACjB,cAAc;QAClB;
|
|
1
|
+
{"version":3,"file":"api/features/CognitoService/adminDeleteSoftwareToken.test.js","sources":["../../../../src/api/features/CognitoService/adminDeleteSoftwareToken.test.ts"],"sourcesContent":["import { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport { adminDeleteSoftwareToken } from \"./adminDeleteSoftwareToken.js\";\n\nconst params = {\n region: \"eu-central-1\",\n userPoolId: \"eu-central-1_pool\",\n username: \"user-1\",\n credentials: async () => ({\n accessKeyId: \"AKIDEXAMPLE\",\n secretAccessKey: \"secret\",\n sessionToken: \"session-token\"\n })\n};\n\ndescribe(\"adminDeleteSoftwareToken\", () => {\n const fetchMock = vi.fn();\n\n beforeEach(() => {\n vi.useFakeTimers({ now: new Date(\"2026-11-07T10:00:00Z\"), toFake: [\"Date\"] });\n fetchMock.mockReset();\n vi.stubGlobal(\"fetch\", fetchMock);\n });\n\n afterEach(() => {\n vi.useRealTimers();\n vi.unstubAllGlobals();\n });\n\n it(\"sends a signed AdminDeleteSoftwareToken request to the pool's region\", async () => {\n fetchMock.mockResolvedValue(new Response(\"{}\", { status: 200 }));\n\n await adminDeleteSoftwareToken(params);\n\n expect(fetchMock).toHaveBeenCalledTimes(1);\n const [url, init] = fetchMock.mock.calls[0];\n expect(url).toBe(\"https://cognito-idp.eu-central-1.amazonaws.com/\");\n expect(init.method).toBe(\"POST\");\n expect(JSON.parse(init.body)).toEqual({\n UserPoolId: \"eu-central-1_pool\",\n Username: \"user-1\"\n });\n\n const headers = init.headers as Record<string, string>;\n expect(headers[\"x-amz-target\"]).toBe(\n \"AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken\"\n );\n expect(headers[\"content-type\"]).toBe(\"application/x-amz-json-1.1\");\n expect(headers[\"x-amz-date\"]).toBe(\"20261107T100000Z\");\n expect(headers[\"x-amz-security-token\"]).toBe(\"session-token\");\n expect(headers[\"authorization\"]).toMatch(\n /^AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE\\/20261107\\/eu-central-1\\/cognito-idp\\/aws4_request, SignedHeaders=[^,]*x-amz-target[^,]*, Signature=[0-9a-f]{64}$/\n );\n });\n\n it(\"throws Cognito's error with the exception's name and message\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"com.amazonaws.cognito#UserNotFoundException\",\n message: \"User does not exist.\"\n }),\n { status: 400 }\n )\n );\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error).toBeInstanceOf(Error);\n expect(error.name).toBe(\"UserNotFoundException\");\n expect(error.message).toBe(\"User does not exist.\");\n });\n\n it(\"treats a user without a TOTP token as done\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"ResourceNotFoundException\",\n message: \"Software token MFA has not been configured for this user.\"\n }),\n { status: 400 }\n )\n );\n\n await expect(adminDeleteSoftwareToken(params)).resolves.toBeUndefined();\n });\n\n it(\"still throws other ResourceNotFoundException errors\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"ResourceNotFoundException\",\n message: \"User pool eu-central-1_pool does not exist.\"\n }),\n { status: 400 }\n )\n );\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error.name).toBe(\"ResourceNotFoundException\");\n expect(error.message).toBe(\"User pool eu-central-1_pool does not exist.\");\n });\n\n it(\"keeps the raw text when Cognito's error isn't JSON\", async () => {\n fetchMock.mockResolvedValue(new Response(\"Service Unavailable\", { status: 503 }));\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error.name).toBe(\"HTTP503\");\n expect(error.message).toBe(\"Service Unavailable\");\n });\n});\n"],"names":["params","describe","fetchMock","vi","beforeEach","Date","afterEach","it","Response","adminDeleteSoftwareToken","expect","url","init","JSON","headers","error","e","Error"],"mappings":";;AAGA,MAAMA,SAAS;IACX,QAAQ;IACR,YAAY;IACZ,UAAU;IACV,aAAa,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hEN,OAAOK,OAAO,cAAc,CAACE;QAC7BP,OAAOK,MAAM,IAAI,EAAE,IAAI,CAAC;QACxBL,OAAOK,MAAM,OAAO,EAAE,IAAI,CAAC;IAC/B;IAEAR,GAAG,8CAA8C;QAC7CL,UAAU,iBAAiB,CACvB,IAAIM,SACAK,KAAK,SAAS,CAAC;YACX,QAAQ;YACR,SAAS;QACb,IACA;YAAE,QAAQ;QAAI;QAItB,MAAMH,OAAOD,yBAAyBT,SAAS,QAAQ,CAAC,aAAa;IACzE;IAEAO,GAAG,uDAAuD;QACtDL,UAAU,iBAAiB,CACvB,IAAIM,SACAK,KAAK,SAAS,CAAC;YACX,QAAQ;YACR,SAAS;QACb,IACA;YAAE,QAAQ;QAAI;QAItB,MAAME,QAAQ,MAAMN,yBAAyBT,QAAQ,KAAK,CAACgB,CAAAA,IAAKA;QAEhEN,OAAOK,MAAM,IAAI,EAAE,IAAI,CAAC;QACxBL,OAAOK,MAAM,OAAO,EAAE,IAAI,CAAC;IAC/B;IAEAR,GAAG,sDAAsD;QACrDL,UAAU,iBAAiB,CAAC,IAAIM,SAAS,uBAAuB;YAAE,QAAQ;QAAI;QAE9E,MAAMO,QAAQ,MAAMN,yBAAyBT,QAAQ,KAAK,CAACgB,CAAAA,IAAKA;QAEhEN,OAAOK,MAAM,IAAI,EAAE,IAAI,CAAC;QACxBL,OAAOK,MAAM,OAAO,EAAE,IAAI,CAAC;IAC/B;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api/features/UpdateUser/UpdateUserUseCase.js","sources":["../../../../src/api/features/UpdateUser/UpdateUserUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateUserUseCase as CoreUpdateUser } from \"@webiny/api-core/features/users/UpdateUser/index.js\";\nimport { GetUserUseCase } from \"@webiny/api-core/features/users/GetUser/index.js\";\nimport { FindUserRecordsUseCase } from \"@webiny/api-core/features/users/FindUserRecords/index.js\";\nimport { AdminUsersRepository } from \"@webiny/api-core/features/users/shared/abstractions.js\";\nimport {\n EmailTakenError,\n NotAuthorizedError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport type { AdminUser } from \"@webiny/api-core/types/users.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { UpdateUserUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { Username } from \"~/api/domain/Username.js\";\nimport {\n CognitoSharedAccountError,\n CognitoUpdateRollbackError,\n CognitoUpdateUserError\n} from \"~/api/domain/errors.js\";\nimport { updateAdminUserValidation } from \"./schema.js\";\nimport type { UpdateAdminUserInput } from \"./abstractions.js\";\nimport { CognitoService } from \"~/api/features/CognitoService/index.js\";\n\ntype MappedAttrType = (user: AdminUser) => string | keyof AdminUser;\n\nconst defaultUpdateAttributes = {\n family_name: \"lastName\",\n given_name: \"firstName\",\n preferred_username: \"email\"\n};\n\n/**\n * How long to wait, in milliseconds, before each retry of a rollback write that failed.\n */\nconst ROLLBACK_RETRY_DELAYS = [100, 400];\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nclass UpdateUserUseCaseImpl implements UseCaseAbstraction.Interface {\n private updateAttributes: Record<string, string | MappedAttrType>;\n\n constructor(\n private identityContext: IdentityContext.Interface,\n private cognitoService: CognitoService.Interface,\n private updateUserUseCase: CoreUpdateUser.Interface,\n private getUserUseCase: GetUserUseCase.Interface,\n private findUserRecords: FindUserRecordsUseCase.Interface,\n private repository: AdminUsersRepository.Interface\n ) {\n this.updateAttributes = defaultUpdateAttributes;\n }\n\n async execute(\n id: string,\n input: UpdateAdminUserInput\n ): Promise<Result<AdminUser, UseCaseAbstraction.Error>> {\n const permission = await this.identityContext.getPermission(\"adminUsers.user\");\n if (!permission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n // Validate input (including password)\n const validation = updateAdminUserValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new UserValidationError(validation.error.issues[0].message));\n }\n\n const data = validation.data;\n const { password, ...userDataWithoutPassword } = data;\n\n // Get original user to know the email before update\n const getUserResult = await this.getUserUseCase.execute({ id });\n if (getUserResult.isFail()) {\n return Result.fail(getUserResult.error);\n }\n\n const originalUser = getUserResult.value;\n\n /**\n * Name, email and password belong to the person's sign-in account, which all of their\n * tenants share. In a shared account, only the person changes them, and every tenant's\n * record gets the new name and email.\n */\n const profileChanged =\n (data.email !== undefined && data.email !== originalUser.email) ||\n (data.firstName !== undefined && data.firstName !== originalUser.firstName) ||\n (data.lastName !== undefined && data.lastName !== originalUser.lastName);\n\n let otherRecords: AdminUser[] = [];\n if (profileChanged || password) {\n const recordsResult = await this.findUserRecords.execute(id, { exhaustive: true });\n if (recordsResult.isFail()) {\n return Result.fail(recordsResult.error);\n }\n\n otherRecords = recordsResult.value.filter(\n record => record.tenant !== originalUser.tenant\n );\n\n const isSelf = this.identityContext.getIdentity().id === id;\n if (otherRecords.length > 0 && !isSelf) {\n return Result.fail(new CognitoSharedAccountError(id));\n }\n\n // The new email goes to every tenant's record, so it must be free in all of them.\n if (data.email !== undefined && data.email !== originalUser.email) {\n const emailResult = await this.ensureEmailIsFree(id, data.email, otherRecords);\n if (emailResult.isFail()) {\n return Result.fail(emailResult.error);\n }\n }\n }\n\n // Update user in api-core\n const updateUserResult = await this.updateUserUseCase.execute(id, userDataWithoutPassword);\n if (updateUserResult.isFail()) {\n return Result.fail(updateUserResult.error);\n }\n\n const updatedUser = updateUserResult.value;\n\n /**\n * The records are written before Cognito, so a failed write never touches the sign-in\n * account. If the sync or Cognito fails, every record goes back to how it was, so the\n * records keep matching the sign-in account. A record that can't be put back is retried\n * with a backoff; if it still fails, the error names its tenant.\n */\n const writtenRecords = profileChanged ? [originalUser, ...otherRecords] : [originalUser];\n\n if (profileChanged) {\n const syncResult = await this.syncProfile(updatedUser, otherRecords);\n if (syncResult.isFail()) {\n return this.rollback(writtenRecords, syncResult.error);\n }\n }\n\n // Update user in Cognito\n try {\n // Build new attributes\n const attributes: Record<string, string> = {};\n\n Object.keys(this.updateAttributes).forEach(attr => {\n const mappedAttr = this.updateAttributes[\n attr as keyof typeof this.updateAttributes\n ] as MappedAttrType;\n const attrValue =\n typeof mappedAttr === \"function\"\n ? mappedAttr(updatedUser)\n : updatedUser[mappedAttr];\n attributes[attr] = attrValue;\n });\n\n // If email changed, set email_verified to true\n if (originalUser.email !== updatedUser.email) {\n attributes[\"email_verified\"] = \"true\";\n }\n\n await this.cognitoService.updateUserAttributes(\n Username.fromUser(originalUser),\n attributes\n );\n } catch (cognitoError) {\n return this.rollback(writtenRecords, new CognitoUpdateUserError(cognitoError as Error));\n }\n\n // The name and email are now in Cognito, so a failed password change keeps the records.\n try {\n if (password) {\n await this.cognitoService.setPermanentPassword(\n Username.fromUser(updatedUser),\n password\n );\n }\n\n return Result.ok(updatedUser);\n } catch (cognitoError) {\n return Result.fail(new CognitoUpdateUserError(cognitoError as Error));\n }\n }\n\n private async ensureEmailIsFree(\n id: string,\n email: string,\n records: AdminUser[]\n ): Promise<Result<void, UseCaseAbstraction.Error>> {\n const results = await Promise.all(\n records.map(record => this.repository.get({ email, tenant: record.tenant }))\n );\n\n for (const result of results) {\n if (result.isOk()) {\n if (result.value.id !== id) {\n return Result.fail(new EmailTakenError(email));\n }\n continue;\n }\n\n if (result.error.code !== \"AdminUser/NotFound\") {\n return Result.fail(result.error);\n }\n }\n\n return Result.ok();\n }\n\n private async syncProfile(\n user: AdminUser,\n records: AdminUser[]\n ): Promise<Result<void, AdminUsersRepository.Error>> {\n return this.writeRecords(\n records.map(record => ({\n ...record,\n email: user.email,\n firstName: user.firstName,\n lastName: user.lastName,\n displayName: user.displayName\n }))\n );\n }\n\n /**\n * Puts the records back and fails with the original error. A record that can't be put back\n * is tried again after each delay in `ROLLBACK_RETRY_DELAYS`. When some records still can't\n * be put back, the error says which tenants no longer match the Cognito account.\n */\n private async rollback(\n records: AdminUser[],\n error: UseCaseAbstraction.Error\n ): Promise<Result<AdminUser, UseCaseAbstraction.Error>> {\n let pending = records;\n let rollbackErrors: Error[] = [];\n\n for (let attempt = 0; ; attempt++) {\n const results = await Promise.all(\n pending.map(record => this.repository.update(record))\n );\n\n const failed: AdminUser[] = [];\n rollbackErrors = [];\n results.forEach((result, index) => {\n if (result.isFail()) {\n failed.push(pending[index]);\n rollbackErrors.push(result.error);\n }\n });\n\n pending = failed;\n if (pending.length === 0 || attempt >= ROLLBACK_RETRY_DELAYS.length) {\n break;\n }\n\n await sleep(ROLLBACK_RETRY_DELAYS[attempt]);\n }\n\n if (pending.length > 0) {\n return Result.fail(\n new CognitoUpdateRollbackError(\n error,\n pending.map(record => record.tenant),\n rollbackErrors\n )\n );\n }\n\n return Result.fail(error);\n }\n\n private async writeRecords(\n records: AdminUser[]\n ): Promise<Result<void, AdminUsersRepository.Error>> {\n const results = await Promise.all(records.map(record => this.repository.update(record)));\n\n const failed = results.find(result => result.isFail());\n if (failed && failed.isFail()) {\n return Result.fail(failed.error);\n }\n\n return Result.ok();\n }\n}\n\nexport const UpdateUserUseCase = UseCaseAbstraction.createImplementation({\n implementation: UpdateUserUseCaseImpl,\n dependencies: [\n IdentityContext,\n CognitoService,\n CoreUpdateUser,\n GetUserUseCase,\n FindUserRecordsUseCase,\n AdminUsersRepository\n ]\n});\n"],"names":["defaultUpdateAttributes","ROLLBACK_RETRY_DELAYS","sleep","ms","Promise","resolve","setTimeout","UpdateUserUseCaseImpl","identityContext","cognitoService","updateUserUseCase","getUserUseCase","findUserRecords","repository","id","input","permission","Result","NotAuthorizedError","validation","updateAdminUserValidation","UserValidationError","data","password","userDataWithoutPassword","getUserResult","originalUser","profileChanged","undefined","otherRecords","recordsResult","record","isSelf","CognitoSharedAccountError","emailResult","updateUserResult","updatedUser","writtenRecords","syncResult","attributes","Object","attr","mappedAttr","attrValue","Username","cognitoError","CognitoUpdateUserError","email","records","results","result","EmailTakenError","user","error","pending","rollbackErrors","attempt","failed","index","CognitoUpdateRollbackError","UpdateUserUseCase","UseCaseAbstraction","Identity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B,EAC6B;QACjD,MAAMC,UAAU,MAAM7C,QAAQ,GAAG,CAAC4C,QAAQ,GAAG,CAACjB,CAAAA,SAAU,IAAI,CAAC,UAAU,CAAC,MAAM,CAACA;QAE/E,MAAM0B,SAASR,QAAQ,IAAI,CAACC,CAAAA,SAAUA,OAAO,MAAM;QACnD,IAAIO,UAAUA,OAAO,MAAM,IACvB,OAAOxC,OAAO,IAAI,CAACwC,OAAO,KAAK;QAGnC,OAAOxC,OAAO,EAAE;IACpB;AACJ;AAEO,MAAM2C,sCAAoBC,2CAAAA,oBAAuC,CAAC;IACrE,gBAAgBtD;IAChB,cAAc;QACVuD;QACAC;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
|
|
1
|
+
{"version":3,"file":"api/features/UpdateUser/UpdateUserUseCase.js","sources":["../../../../src/api/features/UpdateUser/UpdateUserUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateUserUseCase as CoreUpdateUser } from \"@webiny/api-core/features/users/UpdateUser/index.js\";\nimport { GetUserUseCase } from \"@webiny/api-core/features/users/GetUser/index.js\";\nimport { FindUserRecordsUseCase } from \"@webiny/api-core/features/users/FindUserRecords/index.js\";\nimport { AdminUsersRepository } from \"@webiny/api-core/features/users/shared/abstractions.js\";\nimport {\n EmailTakenError,\n NotAuthorizedError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport type { AdminUser } from \"@webiny/api-core/types/users.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { UpdateUserUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { Username } from \"~/api/domain/Username.js\";\nimport {\n CognitoSharedAccountError,\n CognitoUpdateRollbackError,\n CognitoUpdateUserError\n} from \"~/api/domain/errors.js\";\nimport { updateAdminUserValidation } from \"./schema.js\";\nimport type { UpdateAdminUserInput } from \"./abstractions.js\";\nimport { CognitoService } from \"~/api/features/CognitoService/index.js\";\n\ntype MappedAttrType = (user: AdminUser) => string | keyof AdminUser;\n\nconst defaultUpdateAttributes = {\n family_name: \"lastName\",\n given_name: \"firstName\",\n preferred_username: \"email\"\n};\n\n/**\n * How long to wait, in milliseconds, before each retry of a rollback write that failed.\n */\nconst ROLLBACK_RETRY_DELAYS = [100, 400];\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nclass UpdateUserUseCaseImpl implements UseCaseAbstraction.Interface {\n private updateAttributes: Record<string, string | MappedAttrType>;\n\n constructor(\n private identityContext: IdentityContext.Interface,\n private cognitoService: CognitoService.Interface,\n private updateUserUseCase: CoreUpdateUser.Interface,\n private getUserUseCase: GetUserUseCase.Interface,\n private findUserRecords: FindUserRecordsUseCase.Interface,\n private repository: AdminUsersRepository.Interface\n ) {\n this.updateAttributes = defaultUpdateAttributes;\n }\n\n async execute(\n id: string,\n input: UpdateAdminUserInput\n ): Promise<Result<AdminUser, UseCaseAbstraction.Error>> {\n const permission = await this.identityContext.getPermission(\"adminUsers.user\");\n if (!permission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n // Validate input (including password)\n const validation = updateAdminUserValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new UserValidationError(validation.error.issues[0].message));\n }\n\n const data = validation.data;\n const { password, ...userDataWithoutPassword } = data;\n\n // Get original user to know the email before update\n const getUserResult = await this.getUserUseCase.execute({ id });\n if (getUserResult.isFail()) {\n return Result.fail(getUserResult.error);\n }\n\n const originalUser = getUserResult.value;\n\n /**\n * Name, email and password belong to the person's sign-in account, which all of their\n * tenants share. In a shared account, only the person changes them, and every tenant's\n * record gets the new name and email.\n */\n const profileChanged =\n (data.email !== undefined && data.email !== originalUser.email) ||\n (data.firstName !== undefined && data.firstName !== originalUser.firstName) ||\n (data.lastName !== undefined && data.lastName !== originalUser.lastName);\n\n let otherRecords: AdminUser[] = [];\n if (profileChanged || password) {\n const recordsResult = await this.findUserRecords.execute(id, { exhaustive: true });\n if (recordsResult.isFail()) {\n return Result.fail(recordsResult.error);\n }\n\n otherRecords = recordsResult.value.filter(\n record => record.tenant !== originalUser.tenant\n );\n\n const isSelf = this.identityContext.getIdentity().id === id;\n if (otherRecords.length > 0 && !isSelf) {\n return Result.fail(new CognitoSharedAccountError(id));\n }\n\n // The new email goes to every tenant's record, so it must be free in all of them.\n if (data.email !== undefined && data.email !== originalUser.email) {\n const emailResult = await this.ensureEmailIsFree(id, data.email, otherRecords);\n if (emailResult.isFail()) {\n return Result.fail(emailResult.error);\n }\n }\n }\n\n // Update user in api-core\n const updateUserResult = await this.updateUserUseCase.execute(id, userDataWithoutPassword);\n if (updateUserResult.isFail()) {\n return Result.fail(updateUserResult.error);\n }\n\n const updatedUser = updateUserResult.value;\n\n /**\n * The records are written before Cognito, so a failed write never touches the sign-in\n * account. If the sync or Cognito fails, every record goes back to how it was, so the\n * records keep matching the sign-in account. A record that can't be put back is retried\n * with a backoff; if it still fails, the error names its tenant.\n */\n const writtenRecords = profileChanged ? [originalUser, ...otherRecords] : [originalUser];\n\n if (profileChanged) {\n const syncResult = await this.syncProfile(updatedUser, otherRecords);\n if (syncResult.isFail()) {\n return this.rollback(writtenRecords, syncResult.error);\n }\n }\n\n // Update user in Cognito\n try {\n // Build new attributes\n const attributes: Record<string, string> = {};\n\n Object.keys(this.updateAttributes).forEach(attr => {\n const mappedAttr = this.updateAttributes[\n attr as keyof typeof this.updateAttributes\n ] as MappedAttrType;\n const attrValue =\n typeof mappedAttr === \"function\"\n ? mappedAttr(updatedUser)\n : updatedUser[mappedAttr];\n attributes[attr] = attrValue;\n });\n\n // If email changed, set email_verified to true\n if (originalUser.email !== updatedUser.email) {\n attributes[\"email_verified\"] = \"true\";\n }\n\n await this.cognitoService.updateUserAttributes(\n Username.fromUser(originalUser),\n attributes\n );\n } catch (cognitoError) {\n return this.rollback(writtenRecords, new CognitoUpdateUserError(cognitoError as Error));\n }\n\n // The name and email are now in Cognito, so a failed password change keeps the records.\n try {\n if (password) {\n await this.cognitoService.setPermanentPassword(\n Username.fromUser(updatedUser),\n password\n );\n }\n\n return Result.ok(updatedUser);\n } catch (cognitoError) {\n return Result.fail(new CognitoUpdateUserError(cognitoError as Error));\n }\n }\n\n private async ensureEmailIsFree(\n id: string,\n email: string,\n records: AdminUser[]\n ): Promise<Result<void, UseCaseAbstraction.Error>> {\n const results = await Promise.all(\n records.map(record => this.repository.get({ email, tenant: record.tenant }))\n );\n\n for (const result of results) {\n if (result.isOk()) {\n if (result.value.id !== id) {\n return Result.fail(new EmailTakenError(email));\n }\n continue;\n }\n\n if (result.error.code !== \"AdminUser/NotFound\") {\n return Result.fail(result.error);\n }\n }\n\n return Result.ok();\n }\n\n private async syncProfile(\n user: AdminUser,\n records: AdminUser[]\n ): Promise<Result<void, AdminUsersRepository.Error>> {\n return this.writeRecords(\n records.map(record => ({\n ...record,\n email: user.email,\n firstName: user.firstName,\n lastName: user.lastName,\n displayName: user.displayName\n }))\n );\n }\n\n /**\n * Puts the records back and fails with the original error. A record that can't be put back\n * is tried again after each delay in `ROLLBACK_RETRY_DELAYS`. When some records still can't\n * be put back, the error says which tenants no longer match the Cognito account.\n */\n private async rollback(\n records: AdminUser[],\n error: UseCaseAbstraction.Error\n ): Promise<Result<AdminUser, UseCaseAbstraction.Error>> {\n let pending = records;\n let rollbackErrors: Error[] = [];\n\n for (let attempt = 0; ; attempt++) {\n const results = await Promise.all(\n pending.map(record => this.repository.update(record))\n );\n\n const failed: AdminUser[] = [];\n rollbackErrors = [];\n results.forEach((result, index) => {\n if (result.isFail()) {\n failed.push(pending[index]);\n rollbackErrors.push(result.error);\n }\n });\n\n pending = failed;\n if (pending.length === 0 || attempt >= ROLLBACK_RETRY_DELAYS.length) {\n break;\n }\n\n await sleep(ROLLBACK_RETRY_DELAYS[attempt]);\n }\n\n if (pending.length > 0) {\n return Result.fail(\n new CognitoUpdateRollbackError(\n error,\n pending.map(record => record.tenant),\n rollbackErrors\n )\n );\n }\n\n return Result.fail(error);\n }\n\n private async writeRecords(\n records: AdminUser[]\n ): Promise<Result<void, AdminUsersRepository.Error>> {\n const results = await Promise.all(records.map(record => this.repository.update(record)));\n\n const failed = results.find(result => result.isFail());\n if (failed && failed.isFail()) {\n return Result.fail(failed.error);\n }\n\n return Result.ok();\n }\n}\n\nexport const UpdateUserUseCase = UseCaseAbstraction.createImplementation({\n implementation: UpdateUserUseCaseImpl,\n dependencies: [\n IdentityContext,\n CognitoService,\n CoreUpdateUser,\n GetUserUseCase,\n FindUserRecordsUseCase,\n AdminUsersRepository\n ]\n});\n"],"names":["defaultUpdateAttributes","ROLLBACK_RETRY_DELAYS","sleep","ms","Promise","resolve","setTimeout","UpdateUserUseCaseImpl","identityContext","cognitoService","updateUserUseCase","getUserUseCase","findUserRecords","repository","id","input","permission","Result","NotAuthorizedError","validation","updateAdminUserValidation","UserValidationError","data","password","userDataWithoutPassword","getUserResult","originalUser","profileChanged","undefined","otherRecords","recordsResult","record","isSelf","CognitoSharedAccountError","emailResult","updateUserResult","updatedUser","writtenRecords","syncResult","attributes","Object","attr","mappedAttr","attrValue","Username","cognitoError","CognitoUpdateUserError","email","records","results","result","EmailTakenError","user","error","pending","rollbackErrors","attempt","failed","index","CognitoUpdateRollbackError","UpdateUserUseCase","UseCaseAbstraction","IdentityContext","CognitoService","CoreUpdateUser","GetUserUseCase","FindUserRecordsUseCase","AdminUsersRepository"],"mappings":";;;;;;;;;;;;AAyBA,MAAMA,0BAA0B;IAC5B,aAAa;IACb,YAAY;IACZ,oBAAoB;AACxB;AAKA,MAAMC,wBAAwB;IAAC;IAAK;CAAI;AAExC,MAAMC,QAAQ,CAACC,KAAe,IAAIC,QAAQC,CAAAA,UAAWC,WAAWD,SAASF;AAEzE,MAAMI;IAGF,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,iBAA2C,EAC3CC,cAAwC,EACxCC,eAAiD,EACjDC,UAA0C,CACpD;aANUL,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,iBAAiB,GAAjBA;aACAC,cAAc,GAAdA;aACAC,eAAe,GA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1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webiny/cognito",
|
|
3
|
-
"version": "6.5.4-beta.
|
|
3
|
+
"version": "6.5.4-beta.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -15,36 +15,36 @@
|
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"@smithy/signature-v4": "5.7.5",
|
|
17
17
|
"@smithy/types": "4.20.0",
|
|
18
|
-
"@webiny/admin-ui": "6.5.4-beta.
|
|
19
|
-
"@webiny/api-core": "6.5.4-beta.
|
|
20
|
-
"@webiny/app": "6.5.4-beta.
|
|
21
|
-
"@webiny/app-admin": "6.5.4-beta.
|
|
22
|
-
"@webiny/aws-sdk": "6.5.4-beta.
|
|
18
|
+
"@webiny/admin-ui": "6.5.4-beta.2",
|
|
19
|
+
"@webiny/api-core": "6.5.4-beta.2",
|
|
20
|
+
"@webiny/app": "6.5.4-beta.2",
|
|
21
|
+
"@webiny/app-admin": "6.5.4-beta.2",
|
|
22
|
+
"@webiny/aws-sdk": "6.5.4-beta.2",
|
|
23
23
|
"@webiny/di": "1.1.0",
|
|
24
|
-
"@webiny/feature": "6.5.4-beta.
|
|
25
|
-
"@webiny/form": "6.5.4-beta.
|
|
26
|
-
"@webiny/handler-graphql": "6.5.4-beta.
|
|
27
|
-
"@webiny/icons": "6.5.4-beta.
|
|
28
|
-
"@webiny/project": "6.5.4-beta.
|
|
29
|
-
"@webiny/project-aws": "6.5.4-beta.
|
|
30
|
-
"@webiny/react-properties": "6.5.4-beta.
|
|
31
|
-
"@webiny/validation": "6.5.4-beta.
|
|
24
|
+
"@webiny/feature": "6.5.4-beta.2",
|
|
25
|
+
"@webiny/form": "6.5.4-beta.2",
|
|
26
|
+
"@webiny/handler-graphql": "6.5.4-beta.2",
|
|
27
|
+
"@webiny/icons": "6.5.4-beta.2",
|
|
28
|
+
"@webiny/project": "6.5.4-beta.2",
|
|
29
|
+
"@webiny/project-aws": "6.5.4-beta.2",
|
|
30
|
+
"@webiny/react-properties": "6.5.4-beta.2",
|
|
31
|
+
"@webiny/validation": "6.5.4-beta.2",
|
|
32
32
|
"aws-amplify": "6.22.2",
|
|
33
33
|
"graphql": "16.15.0",
|
|
34
34
|
"jsonwebtoken": "9.0.3",
|
|
35
35
|
"lodash": "4.18.1",
|
|
36
|
-
"mobx": "7.1.
|
|
36
|
+
"mobx": "7.1.8",
|
|
37
37
|
"mobx-react-lite": "5.1.4",
|
|
38
38
|
"qrcode.react": "4.2.0",
|
|
39
39
|
"react": "18.3.1",
|
|
40
40
|
"zod": "4.6.7"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@types/react": "18.3.
|
|
44
|
-
"@webiny/build-tools": "6.5.4-beta.
|
|
45
|
-
"@webiny/project-utils": "6.5.4-beta.
|
|
46
|
-
"@webiny/wcp": "6.5.4-beta.
|
|
47
|
-
"vitest": "5.1.
|
|
43
|
+
"@types/react": "18.3.32",
|
|
44
|
+
"@webiny/build-tools": "6.5.4-beta.2",
|
|
45
|
+
"@webiny/project-utils": "6.5.4-beta.2",
|
|
46
|
+
"@webiny/wcp": "6.5.4-beta.2",
|
|
47
|
+
"vitest": "5.1.2"
|
|
48
48
|
},
|
|
49
49
|
"publishConfig": {
|
|
50
50
|
"access": "public"
|
|
File without changes
|