@webiny/cognito 6.5.0 → 6.5.1-beta.1
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/admin/Extension.js +9 -0
- package/admin/Extension.js.map +1 -1
- package/admin/features/users/checkEmail/CheckEmailGateway.d.ts +11 -0
- package/admin/features/users/checkEmail/CheckEmailGateway.js +44 -0
- package/admin/features/users/checkEmail/CheckEmailGateway.js.map +1 -0
- package/admin/features/users/checkEmail/CheckEmailUseCase.d.ts +10 -0
- package/admin/features/users/checkEmail/CheckEmailUseCase.js +18 -0
- package/admin/features/users/checkEmail/CheckEmailUseCase.js.map +1 -0
- package/admin/features/users/checkEmail/abstractions/CheckEmailGateway.d.ts +14 -0
- package/admin/features/users/checkEmail/abstractions/CheckEmailGateway.js +5 -0
- package/admin/features/users/checkEmail/abstractions/CheckEmailGateway.js.map +1 -0
- package/admin/features/users/checkEmail/abstractions/CheckEmailUseCase.d.ts +9 -0
- package/admin/features/users/checkEmail/abstractions/CheckEmailUseCase.js +5 -0
- package/admin/features/users/checkEmail/abstractions/CheckEmailUseCase.js.map +1 -0
- package/admin/features/users/checkEmail/abstractions/index.d.ts +2 -0
- package/admin/features/users/checkEmail/abstractions/index.js +2 -0
- package/admin/features/users/checkEmail/feature.d.ts +3 -0
- package/admin/features/users/checkEmail/feature.js +19 -0
- package/admin/features/users/checkEmail/feature.js.map +1 -0
- package/admin/features/users/checkEmail/index.d.ts +2 -0
- package/admin/features/users/checkEmail/index.js +2 -0
- package/admin/features/users/createUser/CreateUserGateway.js +2 -1
- package/admin/features/users/createUser/CreateUserGateway.js.map +1 -1
- package/admin/features/users/createUser/CreateUserUseCase.test.d.ts +1 -0
- package/admin/features/users/createUser/CreateUserUseCase.test.js +65 -0
- package/admin/features/users/createUser/CreateUserUseCase.test.js.map +1 -0
- package/admin/features/users/linkUser/LinkUserGateway.d.ts +11 -0
- package/admin/features/users/linkUser/LinkUserGateway.js +50 -0
- package/admin/features/users/linkUser/LinkUserGateway.js.map +1 -0
- package/admin/features/users/linkUser/LinkUserUseCase.d.ts +10 -0
- package/admin/features/users/linkUser/LinkUserUseCase.js +18 -0
- package/admin/features/users/linkUser/LinkUserUseCase.js.map +1 -0
- package/admin/features/users/linkUser/abstractions/LinkUserGateway.d.ts +18 -0
- package/admin/features/users/linkUser/abstractions/LinkUserGateway.js +5 -0
- package/admin/features/users/linkUser/abstractions/LinkUserGateway.js.map +1 -0
- package/admin/features/users/linkUser/abstractions/LinkUserUseCase.d.ts +15 -0
- package/admin/features/users/linkUser/abstractions/LinkUserUseCase.js +5 -0
- package/admin/features/users/linkUser/abstractions/LinkUserUseCase.js.map +1 -0
- package/admin/features/users/linkUser/abstractions/index.d.ts +2 -0
- package/admin/features/users/linkUser/abstractions/index.js +2 -0
- package/admin/features/users/linkUser/feature.d.ts +3 -0
- package/admin/features/users/linkUser/feature.js +19 -0
- package/admin/features/users/linkUser/feature.js.map +1 -0
- package/admin/features/users/linkUser/index.d.ts +2 -0
- package/admin/features/users/linkUser/index.js +2 -0
- package/admin/features/users/shared/AdminUsersError.d.ts +13 -0
- package/admin/features/users/shared/AdminUsersError.js +11 -0
- package/admin/features/users/shared/AdminUsersError.js.map +1 -0
- package/admin/presentation/Cognito/CognitoLoginScreen.js +9 -1
- package/admin/presentation/Cognito/CognitoLoginScreen.js.map +1 -1
- package/admin/presentation/Cognito/CognitoPresenter.d.ts +10 -1
- package/admin/presentation/Cognito/CognitoPresenter.js +50 -4
- package/admin/presentation/Cognito/CognitoPresenter.js.map +1 -1
- package/admin/presentation/Cognito/CognitoPresenter.test.d.ts +1 -0
- package/admin/presentation/Cognito/CognitoPresenter.test.js +180 -0
- package/admin/presentation/Cognito/CognitoPresenter.test.js.map +1 -0
- package/admin/presentation/Cognito/abstractions.d.ts +8 -1
- package/admin/presentation/Cognito/abstractions.js.map +1 -1
- package/admin/presentation/Cognito/components/NoTenantAccess.d.ts +23 -0
- package/admin/presentation/Cognito/components/NoTenantAccess.js +10 -0
- package/admin/presentation/Cognito/components/NoTenantAccess.js.map +1 -0
- package/admin/presentation/Cognito/components/SelectTenant.d.ts +26 -0
- package/admin/presentation/Cognito/components/SelectTenant.js +15 -0
- package/admin/presentation/Cognito/components/SelectTenant.js.map +1 -0
- package/admin/presentation/Cognito/components/index.d.ts +38 -0
- package/admin/presentation/Cognito/components/index.js +4 -0
- package/admin/presentation/Cognito/components/index.js.map +1 -1
- package/admin/presentation/users/UserForm/UserFormPresenter.d.ts +30 -0
- package/admin/presentation/users/UserForm/UserFormPresenter.js +118 -0
- package/admin/presentation/users/UserForm/UserFormPresenter.js.map +1 -0
- package/admin/presentation/users/UserForm/UserFormPresenter.test.d.ts +1 -0
- package/admin/presentation/users/UserForm/UserFormPresenter.test.js +248 -0
- package/admin/presentation/users/UserForm/UserFormPresenter.test.js.map +1 -0
- package/admin/presentation/users/UserForm/abstractions.d.ts +52 -0
- package/admin/presentation/users/UserForm/abstractions.js +5 -0
- package/admin/presentation/users/UserForm/abstractions.js.map +1 -0
- package/admin/presentation/users/UserForm/feature.d.ts +7 -0
- package/admin/presentation/users/UserForm/feature.js +17 -0
- package/admin/presentation/users/UserForm/feature.js.map +1 -0
- package/admin/ui/views/Users/UsersForm.d.ts +3 -1
- package/admin/ui/views/Users/UsersForm.js +43 -20
- package/admin/ui/views/Users/UsersForm.js.map +1 -1
- package/admin/ui/views/Users/components/LinkAccountAlert.d.ts +10 -0
- package/admin/ui/views/Users/components/LinkAccountAlert.js +17 -0
- package/admin/ui/views/Users/components/LinkAccountAlert.js.map +1 -0
- package/admin/ui/views/Users/hooks/useUserForm.d.ts +1 -0
- package/admin/ui/views/Users/hooks/useUserForm.js +32 -18
- package/admin/ui/views/Users/hooks/useUserForm.js.map +1 -1
- package/api/CognitoApiFeature.js +4 -0
- package/api/CognitoApiFeature.js.map +1 -1
- package/api/domain/errors.d.ts +49 -0
- package/api/domain/errors.js +53 -1
- package/api/domain/errors.js.map +1 -1
- package/api/features/CheckEmail/CheckEmailUseCase.d.ts +16 -0
- package/api/features/CheckEmail/CheckEmailUseCase.js +47 -0
- package/api/features/CheckEmail/CheckEmailUseCase.js.map +1 -0
- package/api/features/CheckEmail/abstractions.d.ts +29 -0
- package/api/features/CheckEmail/abstractions.js +5 -0
- package/api/features/CheckEmail/abstractions.js.map +1 -0
- package/api/features/CheckEmail/feature.d.ts +4 -0
- package/api/features/CheckEmail/feature.js +11 -0
- package/api/features/CheckEmail/feature.js.map +1 -0
- package/api/features/CheckEmail/index.d.ts +2 -0
- package/api/features/CheckEmail/index.js +2 -0
- package/api/features/CognitoService/CognitoService.d.ts +1 -1
- package/api/features/CognitoService/CognitoService.js +11 -5
- package/api/features/CognitoService/CognitoService.js.map +1 -1
- package/api/features/CognitoService/abstractions.d.ts +8 -2
- package/api/features/CognitoService/abstractions.js.map +1 -1
- package/api/features/CreateUser/CreateUserUseCase.d.ts +1 -2
- package/api/features/CreateUser/CreateUserUseCase.js +3 -3
- package/api/features/CreateUser/CreateUserUseCase.js.map +1 -1
- package/api/features/CreateUser/abstractions.d.ts +3 -1
- package/api/features/CreateUser/abstractions.js.map +1 -1
- package/api/features/DeleteUser/DeleteUserUseCase.d.ts +3 -1
- package/api/features/DeleteUser/DeleteUserUseCase.js +11 -2
- package/api/features/DeleteUser/DeleteUserUseCase.js.map +1 -1
- package/api/features/DeleteUser/abstractions.d.ts +2 -0
- package/api/features/DeleteUser/abstractions.js.map +1 -1
- package/api/features/LinkUser/LinkUserUseCase.d.ts +22 -0
- package/api/features/LinkUser/LinkUserUseCase.js +83 -0
- package/api/features/LinkUser/LinkUserUseCase.js.map +1 -0
- package/api/features/LinkUser/abstractions.d.ts +36 -0
- package/api/features/LinkUser/abstractions.js +5 -0
- package/api/features/LinkUser/abstractions.js.map +1 -0
- package/api/features/LinkUser/feature.d.ts +4 -0
- package/api/features/LinkUser/feature.js +11 -0
- package/api/features/LinkUser/feature.js.map +1 -0
- package/api/features/LinkUser/index.d.ts +2 -0
- package/api/features/LinkUser/index.js +2 -0
- package/api/features/UpdateUser/UpdateUserUseCase.d.ts +14 -1
- package/api/features/UpdateUser/UpdateUserUseCase.js +93 -4
- package/api/features/UpdateUser/UpdateUserUseCase.js.map +1 -1
- package/api/features/UpdateUser/abstractions.d.ts +7 -1
- package/api/features/UpdateUser/abstractions.js.map +1 -1
- package/api/features/UserInstaller/UserInstaller.d.ts +3 -1
- package/api/features/UserInstaller/UserInstaller.js +18 -3
- package/api/features/UserInstaller/UserInstaller.js.map +1 -1
- package/api/graphql/user.gql.js +68 -0
- package/api/graphql/user.gql.js.map +1 -1
- package/package.json +18 -18
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { Result } from "@webiny/feature/api";
|
|
3
|
+
import { AdminUsersRepository } from "@webiny/api-core/features/users/shared/abstractions.js";
|
|
4
|
+
import { NotAuthorizedError, UserValidationError } from "@webiny/api-core/features/users/shared/errors.js";
|
|
5
|
+
import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
|
|
6
|
+
import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
|
|
7
|
+
import { CreateUserUseCase } from "@webiny/api-core/features/users/CreateUser/index.js";
|
|
8
|
+
import { FindUserRecordsUseCase } from "@webiny/api-core/features/users/FindUserRecords/index.js";
|
|
9
|
+
import { LinkUserUseCase } from "./abstractions.js";
|
|
10
|
+
import { Username } from "../../domain/Username.js";
|
|
11
|
+
import { CognitoAccountExistsError, CognitoAccountNotFoundError, CognitoGetUserError } from "../../domain/errors.js";
|
|
12
|
+
import { CognitoService } from "../CognitoService/index.js";
|
|
13
|
+
const linkAdminUserValidation = z.object({
|
|
14
|
+
email: z.string().email(),
|
|
15
|
+
roles: z.array(z.string()).optional().default([]),
|
|
16
|
+
teams: z.array(z.string()).optional().default([])
|
|
17
|
+
});
|
|
18
|
+
class LinkUserUseCaseImpl {
|
|
19
|
+
constructor(identityContext, tenantContext, cognitoService, createUserUseCase, findUserRecords, repository){
|
|
20
|
+
this.identityContext = identityContext;
|
|
21
|
+
this.tenantContext = tenantContext;
|
|
22
|
+
this.cognitoService = cognitoService;
|
|
23
|
+
this.createUserUseCase = createUserUseCase;
|
|
24
|
+
this.findUserRecords = findUserRecords;
|
|
25
|
+
this.repository = repository;
|
|
26
|
+
}
|
|
27
|
+
async execute(input) {
|
|
28
|
+
const permission = await this.identityContext.getPermission("adminUsers.user");
|
|
29
|
+
if (!permission) return Result.fail(new NotAuthorizedError());
|
|
30
|
+
const validation = linkAdminUserValidation.safeParse(input);
|
|
31
|
+
if (!validation.success) return Result.fail(new UserValidationError(validation.error.issues[0].message));
|
|
32
|
+
const { email, roles, teams } = validation.data;
|
|
33
|
+
const existingUserResult = await this.repository.get({
|
|
34
|
+
email
|
|
35
|
+
});
|
|
36
|
+
if (existingUserResult.isOk()) return Result.fail(new CognitoAccountExistsError(email));
|
|
37
|
+
let cognitoUser;
|
|
38
|
+
try {
|
|
39
|
+
cognitoUser = await this.cognitoService.getUser(Username.fromUser({
|
|
40
|
+
email
|
|
41
|
+
}));
|
|
42
|
+
} catch (error) {
|
|
43
|
+
return Result.fail(new CognitoGetUserError(error));
|
|
44
|
+
}
|
|
45
|
+
if (!cognitoUser) return Result.fail(new CognitoAccountNotFoundError(email));
|
|
46
|
+
const id = cognitoUser.attributes["custom:id"];
|
|
47
|
+
if (!id) return Result.fail(new CognitoAccountExistsError(email));
|
|
48
|
+
const recordsResult = await this.findUserRecords.execute(id, {
|
|
49
|
+
exhaustive: true
|
|
50
|
+
});
|
|
51
|
+
if (recordsResult.isFail()) return Result.fail(recordsResult.error);
|
|
52
|
+
const records = recordsResult.value;
|
|
53
|
+
const currentTenant = this.tenantContext.getTenant().id;
|
|
54
|
+
if (records.some((record)=>record.tenant === currentTenant)) return Result.fail(new CognitoAccountExistsError(email));
|
|
55
|
+
const [existing] = records;
|
|
56
|
+
const firstName = existing?.firstName ?? cognitoUser.attributes["given_name"];
|
|
57
|
+
const lastName = existing?.lastName ?? cognitoUser.attributes["family_name"];
|
|
58
|
+
return this.createUserUseCase.execute({
|
|
59
|
+
id,
|
|
60
|
+
email: existing?.email ?? email,
|
|
61
|
+
firstName,
|
|
62
|
+
lastName,
|
|
63
|
+
displayName: existing?.displayName,
|
|
64
|
+
avatar: existing?.avatar,
|
|
65
|
+
roles,
|
|
66
|
+
teams
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const LinkUserUseCase_LinkUserUseCase = LinkUserUseCase.createImplementation({
|
|
71
|
+
implementation: LinkUserUseCaseImpl,
|
|
72
|
+
dependencies: [
|
|
73
|
+
IdentityContext,
|
|
74
|
+
TenantContext,
|
|
75
|
+
CognitoService,
|
|
76
|
+
CreateUserUseCase,
|
|
77
|
+
FindUserRecordsUseCase,
|
|
78
|
+
AdminUsersRepository
|
|
79
|
+
]
|
|
80
|
+
});
|
|
81
|
+
export { LinkUserUseCase_LinkUserUseCase as LinkUserUseCase };
|
|
82
|
+
|
|
83
|
+
//# sourceMappingURL=LinkUserUseCase.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api/features/LinkUser/LinkUserUseCase.js","sources":["../../../../src/api/features/LinkUser/LinkUserUseCase.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { Result } from \"@webiny/feature/api\";\nimport { AdminUsersRepository } from \"@webiny/api-core/features/users/shared/abstractions.js\";\nimport {\n NotAuthorizedError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { CreateUserUseCase as CoreCreateUser } from \"@webiny/api-core/features/users/CreateUser/index.js\";\nimport { FindUserRecordsUseCase } from \"@webiny/api-core/features/users/FindUserRecords/index.js\";\nimport { LinkUserUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { Username } from \"~/api/domain/Username.js\";\nimport {\n CognitoAccountExistsError,\n CognitoAccountNotFoundError,\n CognitoGetUserError\n} from \"~/api/domain/errors.js\";\nimport { CognitoService } from \"~/api/features/CognitoService/index.js\";\n\nconst linkAdminUserValidation = z.object({\n email: z.string().email(),\n roles: z.array(z.string()).optional().default([]),\n teams: z.array(z.string()).optional().default([])\n});\n\nclass LinkUserUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private tenantContext: TenantContext.Interface,\n private cognitoService: CognitoService.Interface,\n private createUserUseCase: CoreCreateUser.Interface,\n private findUserRecords: FindUserRecordsUseCase.Interface,\n private repository: AdminUsersRepository.Interface\n ) {}\n\n async execute(\n input: UseCaseAbstraction.Input\n ): Promise<Result<UseCaseAbstraction.Output, UseCaseAbstraction.Error>> {\n const permission = await this.identityContext.getPermission(\"adminUsers.user\");\n if (!permission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = linkAdminUserValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new UserValidationError(validation.error.issues[0].message));\n }\n\n const { email, roles, teams } = validation.data;\n\n const existingUserResult = await this.repository.get({ email });\n if (existingUserResult.isOk()) {\n return Result.fail(new CognitoAccountExistsError(email));\n }\n\n let cognitoUser: CognitoService.User | null;\n try {\n cognitoUser = await this.cognitoService.getUser(Username.fromUser({ email }));\n } catch (error) {\n return Result.fail(new CognitoGetUserError(error as Error));\n }\n\n if (!cognitoUser) {\n return Result.fail(new CognitoAccountNotFoundError(email));\n }\n\n const id = cognitoUser.attributes[\"custom:id\"];\n if (!id) {\n // Not an account this app created, so there's no user ID to share.\n return Result.fail(new CognitoAccountExistsError(email));\n }\n\n // Exhaustive, so records from before the user→tenant index get indexed now.\n const recordsResult = await this.findUserRecords.execute(id, { exhaustive: true });\n if (recordsResult.isFail()) {\n return Result.fail(recordsResult.error);\n }\n\n const records = recordsResult.value;\n const currentTenant = this.tenantContext.getTenant().id;\n if (records.some(record => record.tenant === currentTenant)) {\n return Result.fail(new CognitoAccountExistsError(email));\n }\n\n // Name, email and avatar are global per person, so they come from the person's other\n // records, or from the account.\n const [existing] = records;\n const firstName = existing?.firstName ?? cognitoUser.attributes[\"given_name\"];\n const lastName = existing?.lastName ?? cognitoUser.attributes[\"family_name\"];\n\n return this.createUserUseCase.execute({\n id,\n email: existing?.email ?? email,\n firstName,\n lastName,\n displayName: existing?.displayName,\n avatar: existing?.avatar,\n roles,\n teams\n });\n }\n}\n\nexport const LinkUserUseCase = UseCaseAbstraction.createImplementation({\n implementation: LinkUserUseCaseImpl,\n dependencies: [\n IdentityContext,\n TenantContext,\n CognitoService,\n CoreCreateUser,\n FindUserRecordsUseCase,\n AdminUsersRepository\n ]\n});\n"],"names":["linkAdminUserValidation","z","LinkUserUseCaseImpl","identityContext","tenantContext","cognitoService","createUserUseCase","findUserRecords","repository","input","permission","Result","NotAuthorizedError","validation","UserValidationError","email","roles","teams","existingUserResult","CognitoAccountExistsError","cognitoUser","Username","error","CognitoGetUserError","CognitoAccountNotFoundError","id","recordsResult","records","currentTenant","record","existing","firstName","lastName","LinkUserUseCase","UseCaseAbstraction","IdentityContext","TenantContext","CognitoService","CoreCreateUser","FindUserRecordsUseCase","AdminUsersRepository"],"mappings":";;;;;;;;;;;;AAoBA,MAAMA,0BAA0BC,EAAE,MAAM,CAAC;IACrC,OAAOA,EAAE,MAAM,GAAG,KAAK;IACvB,OAAOA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ,GAAG,OAAO,CAAC,EAAE;IAChD,OAAOA,EAAE,KAAK,CAACA,EAAE,MAAM,IAAI,QAAQ,GAAG,OAAO,CAAC,EAAE;AACpD;AAEA,MAAMC;IACF,YACYC,eAA0C,EAC1CC,aAAsC,EACtCC,cAAwC,EACxCC,iBAA2C,EAC3CC,eAAiD,EACjDC,UAA0C,CACpD;aANUL,eAAe,GAAfA;aACAC,aAAa,GAAbA;aACAC,cAAc,GAAdA;aACAC,iBAAiB,GAAjBA;aACAC,eAAe,GAAfA;aACAC,U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AAAA,SAAUA,OAAO,MAAM,KAAKD,gBACzC,OAAOjB,OAAO,IAAI,CAAC,IAAIQ,0BAA0BJ;QAKrD,MAAM,CAACe,SAAS,GAAGH;QACnB,MAAMI,YAAYD,UAAU,aAAaV,YAAY,UAAU,CAAC,aAAa;QAC7E,MAAMY,WAAWF,UAAU,YAAYV,YAAY,UAAU,CAAC,cAAc;QAE5E,OAAO,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC;YAClCK;YACA,OAAOK,UAAU,SAASf;YAC1BgB;YACAC;YACA,aAAaF,UAAU;YACvB,QAAQA,UAAU;YAClBd;YACAC;QACJ;IACJ;AACJ;AAEO,MAAMgB,kCAAkBC,gBAAAA,oBAAuC,CAAC;IACnE,gBAAgBhC;IAChB,cAAc;QACViC;QACAC;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Result } from "@webiny/feature/api";
|
|
2
|
+
import type { AdminUser } from "@webiny/api-core/types/users.js";
|
|
3
|
+
import type { NotAuthorizedError, UserValidationError } from "@webiny/api-core/features/users/shared/errors.js";
|
|
4
|
+
import type { CreateUserUseCase as CoreCreateUser } from "@webiny/api-core/features/users/CreateUser/index.js";
|
|
5
|
+
import type { FindUserRecordsUseCase } from "@webiny/api-core/features/users/FindUserRecords/index.js";
|
|
6
|
+
import type { CognitoAccountExistsError, CognitoAccountNotFoundError, CognitoGetUserError } from "../../../api/domain/errors.js";
|
|
7
|
+
export interface LinkAdminUserInput {
|
|
8
|
+
email: string;
|
|
9
|
+
roles?: string[];
|
|
10
|
+
teams?: string[];
|
|
11
|
+
}
|
|
12
|
+
export interface ILinkUserUseCaseErrors {
|
|
13
|
+
authorization: NotAuthorizedError;
|
|
14
|
+
validation: UserValidationError;
|
|
15
|
+
createUser: CoreCreateUser.Error;
|
|
16
|
+
findUserRecords: FindUserRecordsUseCase.Error;
|
|
17
|
+
cognitoAccountExists: CognitoAccountExistsError;
|
|
18
|
+
cognitoAccountNotFound: CognitoAccountNotFoundError;
|
|
19
|
+
cognitoGetUser: CognitoGetUserError;
|
|
20
|
+
}
|
|
21
|
+
type LinkAdminUserError = ILinkUserUseCaseErrors[keyof ILinkUserUseCaseErrors];
|
|
22
|
+
/**
|
|
23
|
+
* Gives a person whose account already exists in another tenant access to the current tenant,
|
|
24
|
+
* with the given roles and teams. Their account (name, email, password) stays as it is.
|
|
25
|
+
*/
|
|
26
|
+
export interface ILinkUserUseCase {
|
|
27
|
+
execute(input: LinkAdminUserInput): Promise<Result<AdminUser, LinkAdminUserError>>;
|
|
28
|
+
}
|
|
29
|
+
export declare const LinkUserUseCase: import("@webiny/di").Abstraction<ILinkUserUseCase>;
|
|
30
|
+
export declare namespace LinkUserUseCase {
|
|
31
|
+
type Interface = ILinkUserUseCase;
|
|
32
|
+
type Input = LinkAdminUserInput;
|
|
33
|
+
type Output = AdminUser;
|
|
34
|
+
type Error = LinkAdminUserError;
|
|
35
|
+
}
|
|
36
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api/features/LinkUser/abstractions.js","sources":["../../../../src/api/features/LinkUser/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Result } from \"@webiny/feature/api\";\nimport type { AdminUser } from \"@webiny/api-core/types/users.js\";\nimport type {\n NotAuthorizedError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport type { CreateUserUseCase as CoreCreateUser } from \"@webiny/api-core/features/users/CreateUser/index.js\";\nimport type { FindUserRecordsUseCase } from \"@webiny/api-core/features/users/FindUserRecords/index.js\";\nimport type {\n CognitoAccountExistsError,\n CognitoAccountNotFoundError,\n CognitoGetUserError\n} from \"~/api/domain/errors.js\";\n\nexport interface LinkAdminUserInput {\n email: string;\n roles?: string[];\n teams?: string[];\n}\n\nexport interface ILinkUserUseCaseErrors {\n authorization: NotAuthorizedError;\n validation: UserValidationError;\n createUser: CoreCreateUser.Error;\n findUserRecords: FindUserRecordsUseCase.Error;\n cognitoAccountExists: CognitoAccountExistsError;\n cognitoAccountNotFound: CognitoAccountNotFoundError;\n cognitoGetUser: CognitoGetUserError;\n}\n\ntype LinkAdminUserError = ILinkUserUseCaseErrors[keyof ILinkUserUseCaseErrors];\n\n/**\n * Gives a person whose account already exists in another tenant access to the current tenant,\n * with the given roles and teams. Their account (name, email, password) stays as it is.\n */\nexport interface ILinkUserUseCase {\n execute(input: LinkAdminUserInput): Promise<Result<AdminUser, LinkAdminUserError>>;\n}\n\nexport const LinkUserUseCase = createAbstraction<ILinkUserUseCase>(\"LinkUserUseCase\");\n\nexport namespace LinkUserUseCase {\n export type Interface = ILinkUserUseCase;\n export type Input = LinkAdminUserInput;\n export type Output = AdminUser;\n export type Error = LinkAdminUserError;\n}\n"],"names":["LinkUserUseCase","createAbstraction"],"mappings":";AAyCO,MAAMA,kBAAkBC,kBAAoC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createFeature } from "@webiny/feature/api";
|
|
2
|
+
import { LinkUserUseCase } from "./LinkUserUseCase.js";
|
|
3
|
+
const LinkUserFeature = createFeature({
|
|
4
|
+
name: "LinkUserFeature",
|
|
5
|
+
register (container) {
|
|
6
|
+
container.register(LinkUserUseCase);
|
|
7
|
+
}
|
|
8
|
+
});
|
|
9
|
+
export { LinkUserFeature };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=feature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api/features/LinkUser/feature.js","sources":["../../../../src/api/features/LinkUser/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { LinkUserUseCase } from \"./LinkUserUseCase.js\";\n\nexport const LinkUserFeature = createFeature({\n name: \"LinkUserFeature\",\n register(container) {\n container.register(LinkUserUseCase);\n }\n});\n"],"names":["LinkUserFeature","createFeature","container","LinkUserUseCase"],"mappings":";;AAGO,MAAMA,kBAAkBC,cAAc;IACzC,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;IACvB;AACJ"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { Result } from "@webiny/feature/api";
|
|
2
2
|
import { UpdateUserUseCase as CoreUpdateUser } from "@webiny/api-core/features/users/UpdateUser/index.js";
|
|
3
3
|
import { GetUserUseCase } from "@webiny/api-core/features/users/GetUser/index.js";
|
|
4
|
+
import { FindUserRecordsUseCase } from "@webiny/api-core/features/users/FindUserRecords/index.js";
|
|
5
|
+
import { AdminUsersRepository } from "@webiny/api-core/features/users/shared/abstractions.js";
|
|
4
6
|
import type { AdminUser } from "@webiny/api-core/types/users.js";
|
|
5
7
|
import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
|
|
6
8
|
import { UpdateUserUseCase as UseCaseAbstraction } from "./abstractions.js";
|
|
@@ -11,9 +13,20 @@ declare class UpdateUserUseCaseImpl implements UseCaseAbstraction.Interface {
|
|
|
11
13
|
private cognitoService;
|
|
12
14
|
private updateUserUseCase;
|
|
13
15
|
private getUserUseCase;
|
|
16
|
+
private findUserRecords;
|
|
17
|
+
private repository;
|
|
14
18
|
private updateAttributes;
|
|
15
|
-
constructor(identityContext: IdentityContext.Interface, cognitoService: CognitoService.Interface, updateUserUseCase: CoreUpdateUser.Interface, getUserUseCase: GetUserUseCase.Interface);
|
|
19
|
+
constructor(identityContext: IdentityContext.Interface, cognitoService: CognitoService.Interface, updateUserUseCase: CoreUpdateUser.Interface, getUserUseCase: GetUserUseCase.Interface, findUserRecords: FindUserRecordsUseCase.Interface, repository: AdminUsersRepository.Interface);
|
|
16
20
|
execute(id: string, input: UpdateAdminUserInput): Promise<Result<AdminUser, UseCaseAbstraction.Error>>;
|
|
21
|
+
private ensureEmailIsFree;
|
|
22
|
+
private syncProfile;
|
|
23
|
+
/**
|
|
24
|
+
* Puts the records back and fails with the original error. A record that can't be put back
|
|
25
|
+
* is tried again after each delay in `ROLLBACK_RETRY_DELAYS`. When some records still can't
|
|
26
|
+
* be put back, the error says which tenants no longer match the Cognito account.
|
|
27
|
+
*/
|
|
28
|
+
private rollback;
|
|
29
|
+
private writeRecords;
|
|
17
30
|
}
|
|
18
31
|
export declare const UpdateUserUseCase: typeof UpdateUserUseCaseImpl & {
|
|
19
32
|
__abstraction: import("@webiny/di").Abstraction<import("./abstractions.js").IUpdateUserUseCase>;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { Result } from "@webiny/feature/api";
|
|
2
2
|
import { UpdateUserUseCase } from "@webiny/api-core/features/users/UpdateUser/index.js";
|
|
3
3
|
import { GetUserUseCase } from "@webiny/api-core/features/users/GetUser/index.js";
|
|
4
|
-
import {
|
|
4
|
+
import { FindUserRecordsUseCase } from "@webiny/api-core/features/users/FindUserRecords/index.js";
|
|
5
|
+
import { AdminUsersRepository } from "@webiny/api-core/features/users/shared/abstractions.js";
|
|
6
|
+
import { EmailTakenError, NotAuthorizedError, UserValidationError } from "@webiny/api-core/features/users/shared/errors.js";
|
|
5
7
|
import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
|
|
6
8
|
import { UpdateUserUseCase as external_abstractions_js_UpdateUserUseCase } from "./abstractions.js";
|
|
7
9
|
import { Username } from "../../domain/Username.js";
|
|
8
|
-
import { CognitoUpdateUserError } from "../../domain/errors.js";
|
|
10
|
+
import { CognitoSharedAccountError, CognitoUpdateRollbackError, CognitoUpdateUserError } from "../../domain/errors.js";
|
|
9
11
|
import { updateAdminUserValidation } from "./schema.js";
|
|
10
12
|
import { CognitoService } from "../CognitoService/index.js";
|
|
11
13
|
const defaultUpdateAttributes = {
|
|
@@ -13,12 +15,19 @@ const defaultUpdateAttributes = {
|
|
|
13
15
|
given_name: "firstName",
|
|
14
16
|
preferred_username: "email"
|
|
15
17
|
};
|
|
18
|
+
const ROLLBACK_RETRY_DELAYS = [
|
|
19
|
+
100,
|
|
20
|
+
400
|
|
21
|
+
];
|
|
22
|
+
const sleep = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms));
|
|
16
23
|
class UpdateUserUseCaseImpl {
|
|
17
|
-
constructor(identityContext, cognitoService, updateUserUseCase, getUserUseCase){
|
|
24
|
+
constructor(identityContext, cognitoService, updateUserUseCase, getUserUseCase, findUserRecords, repository){
|
|
18
25
|
this.identityContext = identityContext;
|
|
19
26
|
this.cognitoService = cognitoService;
|
|
20
27
|
this.updateUserUseCase = updateUserUseCase;
|
|
21
28
|
this.getUserUseCase = getUserUseCase;
|
|
29
|
+
this.findUserRecords = findUserRecords;
|
|
30
|
+
this.repository = repository;
|
|
22
31
|
this.updateAttributes = defaultUpdateAttributes;
|
|
23
32
|
}
|
|
24
33
|
async execute(id, input) {
|
|
@@ -33,9 +42,34 @@ class UpdateUserUseCaseImpl {
|
|
|
33
42
|
});
|
|
34
43
|
if (getUserResult.isFail()) return Result.fail(getUserResult.error);
|
|
35
44
|
const originalUser = getUserResult.value;
|
|
45
|
+
const profileChanged = void 0 !== data.email && data.email !== originalUser.email || void 0 !== data.firstName && data.firstName !== originalUser.firstName || void 0 !== data.lastName && data.lastName !== originalUser.lastName;
|
|
46
|
+
let otherRecords = [];
|
|
47
|
+
if (profileChanged || password) {
|
|
48
|
+
const recordsResult = await this.findUserRecords.execute(id, {
|
|
49
|
+
exhaustive: true
|
|
50
|
+
});
|
|
51
|
+
if (recordsResult.isFail()) return Result.fail(recordsResult.error);
|
|
52
|
+
otherRecords = recordsResult.value.filter((record)=>record.tenant !== originalUser.tenant);
|
|
53
|
+
const isSelf = this.identityContext.getIdentity().id === id;
|
|
54
|
+
if (otherRecords.length > 0 && !isSelf) return Result.fail(new CognitoSharedAccountError(id));
|
|
55
|
+
if (void 0 !== data.email && data.email !== originalUser.email) {
|
|
56
|
+
const emailResult = await this.ensureEmailIsFree(id, data.email, otherRecords);
|
|
57
|
+
if (emailResult.isFail()) return Result.fail(emailResult.error);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
36
60
|
const updateUserResult = await this.updateUserUseCase.execute(id, userDataWithoutPassword);
|
|
37
61
|
if (updateUserResult.isFail()) return Result.fail(updateUserResult.error);
|
|
38
62
|
const updatedUser = updateUserResult.value;
|
|
63
|
+
const writtenRecords = profileChanged ? [
|
|
64
|
+
originalUser,
|
|
65
|
+
...otherRecords
|
|
66
|
+
] : [
|
|
67
|
+
originalUser
|
|
68
|
+
];
|
|
69
|
+
if (profileChanged) {
|
|
70
|
+
const syncResult = await this.syncProfile(updatedUser, otherRecords);
|
|
71
|
+
if (syncResult.isFail()) return this.rollback(writtenRecords, syncResult.error);
|
|
72
|
+
}
|
|
39
73
|
try {
|
|
40
74
|
const attributes = {};
|
|
41
75
|
Object.keys(this.updateAttributes).forEach((attr)=>{
|
|
@@ -45,12 +79,65 @@ class UpdateUserUseCaseImpl {
|
|
|
45
79
|
});
|
|
46
80
|
if (originalUser.email !== updatedUser.email) attributes["email_verified"] = "true";
|
|
47
81
|
await this.cognitoService.updateUserAttributes(Username.fromUser(originalUser), attributes);
|
|
82
|
+
} catch (cognitoError) {
|
|
83
|
+
return this.rollback(writtenRecords, new CognitoUpdateUserError(cognitoError));
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
48
86
|
if (password) await this.cognitoService.setPermanentPassword(Username.fromUser(updatedUser), password);
|
|
49
87
|
return Result.ok(updatedUser);
|
|
50
88
|
} catch (cognitoError) {
|
|
51
89
|
return Result.fail(new CognitoUpdateUserError(cognitoError));
|
|
52
90
|
}
|
|
53
91
|
}
|
|
92
|
+
async ensureEmailIsFree(id, email, records) {
|
|
93
|
+
const results = await Promise.all(records.map((record)=>this.repository.get({
|
|
94
|
+
email,
|
|
95
|
+
tenant: record.tenant
|
|
96
|
+
})));
|
|
97
|
+
for (const result of results){
|
|
98
|
+
if (result.isOk()) {
|
|
99
|
+
if (result.value.id !== id) return Result.fail(new EmailTakenError(email));
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if ("AdminUser/NotFound" !== result.error.code) return Result.fail(result.error);
|
|
103
|
+
}
|
|
104
|
+
return Result.ok();
|
|
105
|
+
}
|
|
106
|
+
async syncProfile(user, records) {
|
|
107
|
+
return this.writeRecords(records.map((record)=>({
|
|
108
|
+
...record,
|
|
109
|
+
email: user.email,
|
|
110
|
+
firstName: user.firstName,
|
|
111
|
+
lastName: user.lastName,
|
|
112
|
+
displayName: user.displayName
|
|
113
|
+
})));
|
|
114
|
+
}
|
|
115
|
+
async rollback(records, error) {
|
|
116
|
+
let pending = records;
|
|
117
|
+
let rollbackErrors = [];
|
|
118
|
+
for(let attempt = 0;; attempt++){
|
|
119
|
+
const results = await Promise.all(pending.map((record)=>this.repository.update(record)));
|
|
120
|
+
const failed = [];
|
|
121
|
+
rollbackErrors = [];
|
|
122
|
+
results.forEach((result, index)=>{
|
|
123
|
+
if (result.isFail()) {
|
|
124
|
+
failed.push(pending[index]);
|
|
125
|
+
rollbackErrors.push(result.error);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
pending = failed;
|
|
129
|
+
if (0 === pending.length || attempt >= ROLLBACK_RETRY_DELAYS.length) break;
|
|
130
|
+
await sleep(ROLLBACK_RETRY_DELAYS[attempt]);
|
|
131
|
+
}
|
|
132
|
+
if (pending.length > 0) return Result.fail(new CognitoUpdateRollbackError(error, pending.map((record)=>record.tenant), rollbackErrors));
|
|
133
|
+
return Result.fail(error);
|
|
134
|
+
}
|
|
135
|
+
async writeRecords(records) {
|
|
136
|
+
const results = await Promise.all(records.map((record)=>this.repository.update(record)));
|
|
137
|
+
const failed = results.find((result)=>result.isFail());
|
|
138
|
+
if (failed && failed.isFail()) return Result.fail(failed.error);
|
|
139
|
+
return Result.ok();
|
|
140
|
+
}
|
|
54
141
|
}
|
|
55
142
|
const UpdateUserUseCase_UpdateUserUseCase = external_abstractions_js_UpdateUserUseCase.createImplementation({
|
|
56
143
|
implementation: UpdateUserUseCaseImpl,
|
|
@@ -58,7 +145,9 @@ const UpdateUserUseCase_UpdateUserUseCase = external_abstractions_js_UpdateUserU
|
|
|
58
145
|
IdentityContext,
|
|
59
146
|
CognitoService,
|
|
60
147
|
UpdateUserUseCase,
|
|
61
|
-
GetUserUseCase
|
|
148
|
+
GetUserUseCase,
|
|
149
|
+
FindUserRecordsUseCase,
|
|
150
|
+
AdminUsersRepository
|
|
62
151
|
]
|
|
63
152
|
});
|
|
64
153
|
export { UpdateUserUseCase_UpdateUserUseCase as UpdateUserUseCase };
|
|
@@ -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 {\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 { CognitoUpdateUserError } 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\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 ) {\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 // 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 // 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\n // Update password if provided\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\nexport const UpdateUserUseCase = UseCaseAbstraction.createImplementation({\n implementation: UpdateUserUseCaseImpl,\n dependencies: [IdentityContext, CognitoService, CoreUpdateUser, GetUserUseCase]\n});\n"],"names":["defaultUpdateAttributes","UpdateUserUseCaseImpl","identityContext","cognitoService","updateUserUseCase","getUserUseCase","id","input","permission","Result","NotAuthorizedError","validation","updateAdminUserValidation","UserValidationError","data","password","userDataWithoutPassword","getUserResult","originalUser","updateUserResult","updatedUser","attributes","Object","attr","mappedAttr","attrValue","Username","cognitoError","CognitoUpdateUserError","UpdateUserUseCase","UseCaseAbstraction","IdentityContext","CognitoService","CoreUpdateUser","GetUserUseCase"],"mappings":";;;;;;;;;;AAkBA,MAAMA,0BAA0B;IAC5B,aAAa;IACb,YAAY;IACZ,oBAAoB;AACxB;AAEA,MAAMC;IAGF,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,iBAA2C,EAC3CC,cAAwC,CAClD;aAJUH,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,iBAAiB,GAAjBA;aACAC,cAAc,GAAdA;QAER,IAAI,CAAC,gBAAgB,GAAGL;IAC5B;IAEA,MAAM,QACFM,EAAU,EACVC,KAA2B,EACyB;QACpD,MAAMC,aAAa,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAC5D,IAAI,CAACA,YACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAI3B,MAAMC,aAAaC,0BAA0B,SAAS,CAACL;QACvD,IAAI,CAACI,WAAW,OAAO,EACnB,OAAOF,OAAO,IAAI,CAAC,IAAII,oBAAoBF,WAAW,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO;QAGjF,MAAMG,OAAOH,WAAW,IAAI;QAC5B,MAAM,EAAEI,QAAQ,EAAE,GAAGC,yBAAyB,GAAGF;QAGjD,MAAMG,gBAAgB,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC;YAAEX;QAAG;QAC7D,IAAIW,cAAc,MAAM,IACpB,OAAOR,OAAO,IAAI,CAACQ,cAAc,KAAK;QAG1C,MAAMC,eAAeD,cAAc,KAAK;QAGxC,MAAME,mBAAmB,MAAM,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAACb,IAAIU;QAClE,IAAIG,iBAAiB,MAAM,IACvB,OAAOV,OAAO,IAAI,CAACU,iBAAiB,KAAK;QAG7C,MAAMC,cAAcD,iBAAiB,KAAK;QAG1C,IAAI;YAEA,MAAME,aAAqC,CAAC;YAE5CC,OAAO,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,OAAO,CAACC,CAAAA;gBACvC,MAAMC,aAAa,IAAI,CAAC,gBAAgB,CACpCD,KACH;gBACD,MAAME,YACF,AAAsB,cAAtB,OAAOD,aACDA,WAAWJ,eACXA,WAAW,CAACI,WAAW;gBACjCH,UAAU,CAACE,KAAK,GAAGE;YACvB;YAGA,IAAIP,aAAa,KAAK,KAAKE,YAAY,KAAK,EACxCC,UAAU,CAAC,iBAAiB,GAAG;YAGnC,MAAM,IAAI,CAAC,cAAc,CAAC,oBAAoB,CAC1CK,SAAS,QAAQ,CAACR,eAClBG;YAIJ,IAAIN,UACA,MAAM,IAAI,CAAC,cAAc,CAAC,oBAAoB,CAC1CW,SAAS,QAAQ,CAACN,cAClBL;YAIR,OAAON,OAAO,EAAE,CAACW;QACrB,EAAE,OAAOO,cAAc;YACnB,OAAOlB,OAAO,IAAI,CAAC,IAAImB,uBAAuBD;QAClD;IACJ;AACJ;AAEO,MAAME,sCAAoBC,2CAAAA,oBAAuC,CAAC;IACrE,gBAAgB7B;IAChB,cAAc;QAAC8B;QAAiBC;QAAgBC;QAAgBC;KAAe;AACnF"}
|
|
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":";;;;;;;;;;;;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AA,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"}
|
|
@@ -2,7 +2,9 @@ import type { Result } from "@webiny/feature/api";
|
|
|
2
2
|
import type { AdminUser } from "@webiny/api-core/types/users.js";
|
|
3
3
|
import type { NotAuthorizedError, EmailTakenError, UserValidationError } from "@webiny/api-core/features/users/shared/errors.js";
|
|
4
4
|
import { UpdateUserUseCase as CoreUpdateUserUseCase } from "@webiny/api-core/features/users/UpdateUser/index.js";
|
|
5
|
-
import type {
|
|
5
|
+
import type { FindUserRecordsUseCase } from "@webiny/api-core/features/users/FindUserRecords/index.js";
|
|
6
|
+
import type { RepositoryError } from "@webiny/api-core/features/users/shared/abstractions.js";
|
|
7
|
+
import type { CognitoSharedAccountError, CognitoUpdateRollbackError, CognitoUpdateUserError } from "../../../api/domain/errors.js";
|
|
6
8
|
export interface UpdateAdminUserInput {
|
|
7
9
|
displayName?: string;
|
|
8
10
|
email?: string;
|
|
@@ -19,6 +21,10 @@ export interface IUpdateUserUseCaseErrors {
|
|
|
19
21
|
emailTaken: EmailTakenError;
|
|
20
22
|
updateAdminUser: CoreUpdateUserUseCase.Error;
|
|
21
23
|
cognitoUpdateUser: CognitoUpdateUserError;
|
|
24
|
+
updateRollback: CognitoUpdateRollbackError;
|
|
25
|
+
sharedAccount: CognitoSharedAccountError;
|
|
26
|
+
findUserRecords: FindUserRecordsUseCase.Error;
|
|
27
|
+
repository: RepositoryError;
|
|
22
28
|
}
|
|
23
29
|
type IUpdateAdminUserError = IUpdateUserUseCaseErrors[keyof IUpdateUserUseCaseErrors];
|
|
24
30
|
export interface IUpdateUserUseCase {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api/features/UpdateUser/abstractions.js","sources":["../../../../src/api/features/UpdateUser/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Result } from \"@webiny/feature/api\";\nimport type { AdminUser } from \"@webiny/api-core/types/users.js\";\nimport type {\n NotAuthorizedError,\n EmailTakenError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport { UpdateUserUseCase as CoreUpdateUserUseCase } from \"@webiny/api-core/features/users/UpdateUser/index.js\";\nimport type {
|
|
1
|
+
{"version":3,"file":"api/features/UpdateUser/abstractions.js","sources":["../../../../src/api/features/UpdateUser/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Result } from \"@webiny/feature/api\";\nimport type { AdminUser } from \"@webiny/api-core/types/users.js\";\nimport type {\n NotAuthorizedError,\n EmailTakenError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport { UpdateUserUseCase as CoreUpdateUserUseCase } from \"@webiny/api-core/features/users/UpdateUser/index.js\";\nimport type { FindUserRecordsUseCase } from \"@webiny/api-core/features/users/FindUserRecords/index.js\";\nimport type { RepositoryError } from \"@webiny/api-core/features/users/shared/abstractions.js\";\nimport type {\n CognitoSharedAccountError,\n CognitoUpdateRollbackError,\n CognitoUpdateUserError\n} from \"~/api/domain/errors.js\";\n\nexport interface UpdateAdminUserInput {\n displayName?: string;\n email?: string;\n firstName?: string;\n lastName?: string;\n password?: string;\n avatar?: Record<string, any> | null;\n roles?: string[];\n teams?: string[];\n}\n\nexport interface IUpdateUserUseCaseErrors {\n authorization: NotAuthorizedError;\n validation: UserValidationError;\n emailTaken: EmailTakenError;\n updateAdminUser: CoreUpdateUserUseCase.Error;\n cognitoUpdateUser: CognitoUpdateUserError;\n updateRollback: CognitoUpdateRollbackError;\n sharedAccount: CognitoSharedAccountError;\n findUserRecords: FindUserRecordsUseCase.Error;\n repository: RepositoryError;\n}\n\ntype IUpdateAdminUserError = IUpdateUserUseCaseErrors[keyof IUpdateUserUseCaseErrors];\n\nexport interface IUpdateUserUseCase {\n execute(\n id: string,\n input: UpdateAdminUserInput\n ): Promise<Result<AdminUser, IUpdateAdminUserError>>;\n}\n\nexport const UpdateUserUseCase = createAbstraction<IUpdateUserUseCase>(\"UpdateUserUseCase\");\n\nexport namespace UpdateUserUseCase {\n export type Interface = IUpdateUserUseCase;\n export type Input = UpdateAdminUserInput;\n export type Error = IUpdateAdminUserError;\n}\n"],"names":["UpdateUserUseCase","createAbstraction"],"mappings":";AAiDO,MAAMA,oBAAoBC,kBAAsC"}
|
|
@@ -3,6 +3,7 @@ import { AppInstaller } from "@webiny/api-core/features/tenancy/InstallTenant/in
|
|
|
3
3
|
import { GetRoleUseCase } from "@webiny/api-core/features/security/roles/GetRole/index.js";
|
|
4
4
|
import { DeleteUserUseCase } from "../../../api/features/DeleteUser/index.js";
|
|
5
5
|
import { CreateUserUseCase } from "../../../api/features/CreateUser/index.js";
|
|
6
|
+
import { LinkUserUseCase } from "../../../api/features/LinkUser/index.js";
|
|
6
7
|
interface UserInstallationData {
|
|
7
8
|
firstName: string;
|
|
8
9
|
lastName: string;
|
|
@@ -12,12 +13,13 @@ interface UserInstallationData {
|
|
|
12
13
|
declare class UsersInstallerImpl implements AppInstaller.Interface<UserInstallationData> {
|
|
13
14
|
private getRole;
|
|
14
15
|
private createUserUseCase;
|
|
16
|
+
private linkUserUseCase;
|
|
15
17
|
private deleteUserUseCase;
|
|
16
18
|
readonly alwaysRun = false;
|
|
17
19
|
readonly appName = "Cognito";
|
|
18
20
|
readonly dependsOn: string[];
|
|
19
21
|
private createdUser;
|
|
20
|
-
constructor(getRole: GetRoleUseCase.Interface, createUserUseCase: CreateUserUseCase.Interface, deleteUserUseCase: DeleteUserUseCase.Interface);
|
|
22
|
+
constructor(getRole: GetRoleUseCase.Interface, createUserUseCase: CreateUserUseCase.Interface, linkUserUseCase: LinkUserUseCase.Interface, deleteUserUseCase: DeleteUserUseCase.Interface);
|
|
21
23
|
install(_: Tenant, data: UserInstallationData): Promise<void>;
|
|
22
24
|
uninstall(): Promise<void>;
|
|
23
25
|
}
|
|
@@ -2,10 +2,12 @@ import { AppInstaller } from "@webiny/api-core/features/tenancy/InstallTenant/in
|
|
|
2
2
|
import { GetRoleUseCase } from "@webiny/api-core/features/security/roles/GetRole/index.js";
|
|
3
3
|
import { DeleteUserUseCase } from "../DeleteUser/index.js";
|
|
4
4
|
import { CreateUserUseCase } from "../CreateUser/index.js";
|
|
5
|
+
import { LinkUserUseCase } from "../LinkUser/index.js";
|
|
5
6
|
class UsersInstallerImpl {
|
|
6
|
-
constructor(getRole, createUserUseCase, deleteUserUseCase){
|
|
7
|
+
constructor(getRole, createUserUseCase, linkUserUseCase, deleteUserUseCase){
|
|
7
8
|
this.getRole = getRole;
|
|
8
9
|
this.createUserUseCase = createUserUseCase;
|
|
10
|
+
this.linkUserUseCase = linkUserUseCase;
|
|
9
11
|
this.deleteUserUseCase = deleteUserUseCase;
|
|
10
12
|
this.alwaysRun = false;
|
|
11
13
|
this.appName = "Cognito";
|
|
@@ -28,8 +30,20 @@ class UsersInstallerImpl {
|
|
|
28
30
|
teams: []
|
|
29
31
|
};
|
|
30
32
|
const createResult = await this.createUserUseCase.execute(userWithDisplayName);
|
|
31
|
-
if (createResult.
|
|
32
|
-
|
|
33
|
+
if (createResult.isOk()) {
|
|
34
|
+
this.createdUser = createResult.value;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if ("Cognito/Account/ExistsInOtherTenant" !== createResult.error.code) throw new Error(`Failed to create admin user: ${createResult.error.message}`);
|
|
38
|
+
const linkResult = await this.linkUserUseCase.execute({
|
|
39
|
+
email: data.email,
|
|
40
|
+
roles: [
|
|
41
|
+
role.id
|
|
42
|
+
],
|
|
43
|
+
teams: []
|
|
44
|
+
});
|
|
45
|
+
if (linkResult.isFail()) throw new Error(`Failed to link admin user: ${linkResult.error.message}`);
|
|
46
|
+
this.createdUser = linkResult.value;
|
|
33
47
|
}
|
|
34
48
|
async uninstall() {
|
|
35
49
|
if (this.createdUser) await this.deleteUserUseCase.execute(this.createdUser.id);
|
|
@@ -40,6 +54,7 @@ const UserInstaller = AppInstaller.createImplementation({
|
|
|
40
54
|
dependencies: [
|
|
41
55
|
GetRoleUseCase,
|
|
42
56
|
CreateUserUseCase,
|
|
57
|
+
LinkUserUseCase,
|
|
43
58
|
DeleteUserUseCase
|
|
44
59
|
]
|
|
45
60
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api/features/UserInstaller/UserInstaller.js","sources":["../../../../src/api/features/UserInstaller/UserInstaller.ts"],"sourcesContent":["import type { Tenant } from \"@webiny/api-core/types/tenancy.js\";\nimport type { AdminUser } from \"@webiny/api-core/types/users.js\";\nimport { AppInstaller } from \"@webiny/api-core/features/tenancy/InstallTenant/index.js\";\nimport { GetRoleUseCase } from \"@webiny/api-core/features/security/roles/GetRole/index.js\";\nimport { DeleteUserUseCase } from \"~/api/features/DeleteUser/index.js\";\nimport { CreateUserUseCase } from \"~/api/features/CreateUser/index.js\";\n\ninterface UserInstallationData {\n firstName: string;\n lastName: string;\n email: string;\n password: string;\n}\n\nclass UsersInstallerImpl implements AppInstaller.Interface<UserInstallationData> {\n readonly alwaysRun = false;\n readonly appName = \"Cognito\";\n readonly dependsOn = [\"Security\"];\n private createdUser: AdminUser | undefined;\n\n constructor(\n private getRole: GetRoleUseCase.Interface,\n private createUserUseCase: CreateUserUseCase.Interface,\n private deleteUserUseCase: DeleteUserUseCase.Interface\n ) {}\n\n async install(_: Tenant, data: UserInstallationData): Promise<void> {\n // Load `full-access` role and assign it to the new user\n const roleResult = await this.getRole.execute({ slug: \"full-access\" });\n if (roleResult.isFail()) {\n throw new Error(`Failed to get full-access role: ${roleResult.error.message}`);\n }\n\n const role = roleResult.value;\n\n // Create user with displayName and full-access role\n const userWithDisplayName: CreateUserUseCase.Input = {\n ...data,\n displayName: `${data.firstName} ${data.lastName}`,\n roles: [role.id],\n teams: []\n };\n\n const createResult = await this.createUserUseCase.execute(userWithDisplayName);\n if (createResult.
|
|
1
|
+
{"version":3,"file":"api/features/UserInstaller/UserInstaller.js","sources":["../../../../src/api/features/UserInstaller/UserInstaller.ts"],"sourcesContent":["import type { Tenant } from \"@webiny/api-core/types/tenancy.js\";\nimport type { AdminUser } from \"@webiny/api-core/types/users.js\";\nimport { AppInstaller } from \"@webiny/api-core/features/tenancy/InstallTenant/index.js\";\nimport { GetRoleUseCase } from \"@webiny/api-core/features/security/roles/GetRole/index.js\";\nimport { DeleteUserUseCase } from \"~/api/features/DeleteUser/index.js\";\nimport { CreateUserUseCase } from \"~/api/features/CreateUser/index.js\";\nimport { LinkUserUseCase } from \"~/api/features/LinkUser/index.js\";\n\ninterface UserInstallationData {\n firstName: string;\n lastName: string;\n email: string;\n password: string;\n}\n\nclass UsersInstallerImpl implements AppInstaller.Interface<UserInstallationData> {\n readonly alwaysRun = false;\n readonly appName = \"Cognito\";\n readonly dependsOn = [\"Security\"];\n private createdUser: AdminUser | undefined;\n\n constructor(\n private getRole: GetRoleUseCase.Interface,\n private createUserUseCase: CreateUserUseCase.Interface,\n private linkUserUseCase: LinkUserUseCase.Interface,\n private deleteUserUseCase: DeleteUserUseCase.Interface\n ) {}\n\n async install(_: Tenant, data: UserInstallationData): Promise<void> {\n // Load `full-access` role and assign it to the new user\n const roleResult = await this.getRole.execute({ slug: \"full-access\" });\n if (roleResult.isFail()) {\n throw new Error(`Failed to get full-access role: ${roleResult.error.message}`);\n }\n\n const role = roleResult.value;\n\n // Create user with displayName and full-access role\n const userWithDisplayName: CreateUserUseCase.Input = {\n ...data,\n displayName: `${data.firstName} ${data.lastName}`,\n roles: [role.id],\n teams: []\n };\n\n const createResult = await this.createUserUseCase.execute(userWithDisplayName);\n if (createResult.isOk()) {\n this.createdUser = createResult.value;\n return;\n }\n\n if (createResult.error.code !== \"Cognito/Account/ExistsInOtherTenant\") {\n throw new Error(`Failed to create admin user: ${createResult.error.message}`);\n }\n\n // Creating a tenant for someone who already has an account is deliberate, so their\n // account is linked: they keep their name and password, and the given ones aren't used.\n const linkResult = await this.linkUserUseCase.execute({\n email: data.email,\n roles: [role.id],\n teams: []\n });\n if (linkResult.isFail()) {\n throw new Error(`Failed to link admin user: ${linkResult.error.message}`);\n }\n\n this.createdUser = linkResult.value;\n }\n\n async uninstall(): Promise<void> {\n if (this.createdUser) {\n await this.deleteUserUseCase.execute(this.createdUser.id);\n }\n }\n}\n\nexport const UserInstaller = AppInstaller.createImplementation({\n implementation: UsersInstallerImpl,\n dependencies: [GetRoleUseCase, CreateUserUseCase, LinkUserUseCase, DeleteUserUseCase]\n});\n"],"names":["UsersInstallerImpl","getRole","createUserUseCase","linkUserUseCase","deleteUserUseCase","_","data","roleResult","Error","role","userWithDisplayName","createResult","linkResult","UserInstaller","AppInstaller","GetRoleUseCase","CreateUserUseCase","LinkUserUseCase","DeleteUserUseCase"],"mappings":";;;;;AAeA,MAAMA;IAMF,YACYC,OAAiC,EACjCC,iBAA8C,EAC9CC,eAA0C,EAC1CC,iBAA8C,CACxD;aAJUH,OAAO,GAAPA;aACAC,iBAAiB,GAAjBA;aACAC,eAAe,GAAfA;aACAC,iBAAiB,GAAjBA;aATH,SAAS,GAAG;aACZ,OAAO,GAAG;aACV,SAAS,GAAG;YAAC;SAAW;IAQ9B;IAEH,MAAM,QAAQC,CAAS,EAAEC,IAA0B,EAAiB;QAEhE,MAAMC,aAAa,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;YAAE,MAAM;QAAc;QACpE,IAAIA,WAAW,MAAM,IACjB,MAAM,IAAIC,MAAM,CAAC,gCAAgC,EAAED,WAAW,KAAK,CAAC,OAAO,EAAE;QAGjF,MAAME,OAAOF,WAAW,KAAK;QAG7B,MAAMG,sBAA+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