@webiny/api-core 6.4.12-beta.1 → 6.4.12-beta.10
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/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js +8 -0
- package/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js.map +1 -1
- package/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js +9 -0
- package/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js.map +1 -1
- package/features/security/roles/CreateRole/CreateRoleUseCase.js +8 -0
- package/features/security/roles/CreateRole/CreateRoleUseCase.js.map +1 -1
- package/features/security/roles/UpdateRole/UpdateRoleUseCase.js +11 -0
- package/features/security/roles/UpdateRole/UpdateRoleUseCase.js.map +1 -1
- package/features/security/utils/findNotGrantedPermission.d.ts +22 -0
- package/features/security/utils/findNotGrantedPermission.js +18 -0
- package/features/security/utils/findNotGrantedPermission.js.map +1 -0
- package/features/system/InstallSystem/InstallSystemUseCase.d.ts +1 -1
- package/features/task/TaskDefinition/abstractions.js.map +1 -1
- package/features/task/TaskService/abstractions.js.map +1 -1
- package/features/tenancy/CreateTenant/CreateTenantRepository.js +1 -0
- package/features/tenancy/CreateTenant/CreateTenantRepository.js.map +1 -1
- package/features/tenancy/CreateTenant/CreateTenantUseCase.d.ts +5 -3
- package/features/tenancy/CreateTenant/CreateTenantUseCase.js +10 -3
- package/features/tenancy/CreateTenant/CreateTenantUseCase.js.map +1 -1
- package/features/tenancy/CreateTenant/abstractions.d.ts +2 -1
- package/features/tenancy/CreateTenant/abstractions.js.map +1 -1
- package/features/tenancy/CreateTenant/decorators/CreateTenantWithWcpIncrement.d.ts +1 -1
- package/features/tenancy/CreateTenant/errors.d.ts +6 -0
- package/features/tenancy/CreateTenant/errors.js +11 -1
- package/features/tenancy/CreateTenant/errors.js.map +1 -1
- package/features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.js +1 -0
- package/features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.js.map +1 -1
- package/features/users/AdminUsersFeature.js +2 -0
- package/features/users/AdminUsersFeature.js.map +1 -1
- package/features/users/CreateUser/CreateUserUseCase.js +1 -2
- package/features/users/CreateUser/CreateUserUseCase.js.map +1 -1
- package/features/users/GetCurrentUser/GetCurrentUserUseCase.d.ts +13 -0
- package/features/users/GetCurrentUser/GetCurrentUserUseCase.js +29 -0
- package/features/users/GetCurrentUser/GetCurrentUserUseCase.js.map +1 -0
- package/features/users/GetCurrentUser/abstractions.d.ts +18 -0
- package/features/users/GetCurrentUser/abstractions.js +5 -0
- package/features/users/GetCurrentUser/abstractions.js.map +1 -0
- package/features/users/GetCurrentUser/feature.d.ts +4 -0
- package/features/users/GetCurrentUser/feature.js +11 -0
- package/features/users/GetCurrentUser/feature.js.map +1 -0
- package/features/users/GetCurrentUser/index.d.ts +1 -0
- package/features/users/GetCurrentUser/index.js +1 -0
- package/graphql/users/user.gql.js +9 -12
- package/graphql/users/user.gql.js.map +1 -1
- package/legacy/security/LegacyContext.d.ts +1 -1
- package/legacy/security/LegacyContext.js.map +1 -1
- package/legacy/security/plugins/authenticateUsingCookie.d.ts +7 -0
- package/legacy/security/plugins/authenticateUsingCookie.js +7 -1
- package/legacy/security/plugins/authenticateUsingCookie.js.map +1 -1
- package/legacy/security/plugins/secureHeaders.js +5 -2
- package/legacy/security/plugins/secureHeaders.js.map +1 -1
- package/package.json +24 -24
|
@@ -7,6 +7,7 @@ import { IdentityContext } from "../../IdentityContext/abstractions.js";
|
|
|
7
7
|
import { createApiKeyInputSchema } from "../shared/schemas.js";
|
|
8
8
|
import { ApiKeyAfterCreateEvent, ApiKeyBeforeCreateEvent } from "./events.js";
|
|
9
9
|
import { generateToken } from "../shared/generateToken.js";
|
|
10
|
+
import { findNotGrantedPermission } from "../../utils/findNotGrantedPermission.js";
|
|
10
11
|
import { ApiKeyNotAuthorizedError, ApiKeyValidationError } from "../shared/errors.js";
|
|
11
12
|
class CreateApiKeyUseCaseImpl {
|
|
12
13
|
constructor(identityContext, eventPublisher, repository){
|
|
@@ -22,6 +23,13 @@ class CreateApiKeyUseCaseImpl {
|
|
|
22
23
|
const token = generateToken();
|
|
23
24
|
const identity = this.identityContext.getIdentity();
|
|
24
25
|
const data = validation.data;
|
|
26
|
+
const notGranted = await findNotGrantedPermission({
|
|
27
|
+
identityContext: this.identityContext,
|
|
28
|
+
requested: data.permissions
|
|
29
|
+
});
|
|
30
|
+
if (notGranted) return Result.fail(new ApiKeyNotAuthorizedError({
|
|
31
|
+
message: `Not authorized to grant permission "${notGranted.name}".`
|
|
32
|
+
}));
|
|
25
33
|
const apiKey = {
|
|
26
34
|
id: mdbid(),
|
|
27
35
|
name: data.name,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js","sources":["../../../../../src/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { Result } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateApiKeyUseCase as CreateApiKeyUseCaseAbstraction } from \"./abstractions.js\";\nimport { ApiKeysRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { createApiKeyInputSchema } from \"../shared/schemas.js\";\nimport { ApiKeyBeforeCreateEvent, ApiKeyAfterCreateEvent } from \"./events.js\";\nimport type { ApiKey, CreateApiKeyInput } from \"../shared/types.js\";\nimport type { ApiKeyPermission } from \"~/types/security.js\";\nimport { generateToken } from \"../shared/generateToken.js\";\nimport { ApiKeyValidationError, ApiKeyNotAuthorizedError } from \"../shared/errors.js\";\n\nclass CreateApiKeyUseCaseImpl implements CreateApiKeyUseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: ApiKeysRepository.Interface\n ) {}\n\n async execute(\n input: CreateApiKeyInput\n ): Promise<Result<ApiKey, CreateApiKeyUseCaseAbstraction.Error>> {\n const hasPermission =\n await this.identityContext.getPermission<ApiKeyPermission>(\"security.apiKey\");\n\n if (!hasPermission) {\n return Result.fail(new ApiKeyNotAuthorizedError());\n }\n\n const validation = createApiKeyInputSchema.safeParse(input);\n if (!validation.success) {\n return Result.fail(new ApiKeyValidationError(validation.error.issues[0].message));\n }\n\n const token = generateToken();\n const identity = this.identityContext.getIdentity();\n const data = validation.data;\n\n const apiKey: ApiKey = {\n id: mdbid(),\n name: data.name,\n slug: data.slug,\n description: data.description,\n token,\n permissions: data.permissions,\n createdOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n }\n };\n\n await this.eventPublisher.publish(\n new ApiKeyBeforeCreateEvent({ apiKey, input: validation.data })\n );\n\n const result = await this.repository.create(apiKey);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new ApiKeyAfterCreateEvent({ apiKey, input: validation.data })\n );\n\n return Result.ok(apiKey);\n }\n}\n\nexport const CreateApiKeyUseCase = CreateApiKeyUseCaseAbstraction.createImplementation({\n implementation: CreateApiKeyUseCaseImpl,\n dependencies: [IdentityContext, EventPublisher, ApiKeysRepository]\n});\n"],"names":["CreateApiKeyUseCaseImpl","identityContext","eventPublisher","repository","input","hasPermission","Result","ApiKeyNotAuthorizedError","validation","createApiKeyInputSchema","ApiKeyValidationError","token","generateToken","identity","data","apiKey","mdbid","Date","ApiKeyBeforeCreateEvent","result","ApiKeyAfterCreateEvent","CreateApiKeyUseCase","CreateApiKeyUseCaseAbstraction","IdentityContext","EventPublisher","ApiKeysRepository"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js","sources":["../../../../../src/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { Result } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateApiKeyUseCase as CreateApiKeyUseCaseAbstraction } from \"./abstractions.js\";\nimport { ApiKeysRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { createApiKeyInputSchema } from \"../shared/schemas.js\";\nimport { ApiKeyBeforeCreateEvent, ApiKeyAfterCreateEvent } from \"./events.js\";\nimport type { ApiKey, CreateApiKeyInput } from \"../shared/types.js\";\nimport type { ApiKeyPermission } from \"~/types/security.js\";\nimport { generateToken } from \"../shared/generateToken.js\";\nimport { findNotGrantedPermission } from \"../../utils/findNotGrantedPermission.js\";\nimport { ApiKeyValidationError, ApiKeyNotAuthorizedError } from \"../shared/errors.js\";\n\nclass CreateApiKeyUseCaseImpl implements CreateApiKeyUseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: ApiKeysRepository.Interface\n ) {}\n\n async execute(\n input: CreateApiKeyInput\n ): Promise<Result<ApiKey, CreateApiKeyUseCaseAbstraction.Error>> {\n const hasPermission =\n await this.identityContext.getPermission<ApiKeyPermission>(\"security.apiKey\");\n\n if (!hasPermission) {\n return Result.fail(new ApiKeyNotAuthorizedError());\n }\n\n const validation = createApiKeyInputSchema.safeParse(input);\n if (!validation.success) {\n return Result.fail(new ApiKeyValidationError(validation.error.issues[0].message));\n }\n\n const token = generateToken();\n const identity = this.identityContext.getIdentity();\n const data = validation.data;\n\n const notGranted = await findNotGrantedPermission({\n identityContext: this.identityContext,\n requested: data.permissions\n });\n if (notGranted) {\n return Result.fail(\n new ApiKeyNotAuthorizedError({\n message: `Not authorized to grant permission \"${notGranted.name}\".`\n })\n );\n }\n\n const apiKey: ApiKey = {\n id: mdbid(),\n name: data.name,\n slug: data.slug,\n description: data.description,\n token,\n permissions: data.permissions,\n createdOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n }\n };\n\n await this.eventPublisher.publish(\n new ApiKeyBeforeCreateEvent({ apiKey, input: validation.data })\n );\n\n const result = await this.repository.create(apiKey);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new ApiKeyAfterCreateEvent({ apiKey, input: validation.data })\n );\n\n return Result.ok(apiKey);\n }\n}\n\nexport const CreateApiKeyUseCase = CreateApiKeyUseCaseAbstraction.createImplementation({\n implementation: CreateApiKeyUseCaseImpl,\n dependencies: [IdentityContext, EventPublisher, ApiKeysRepository]\n});\n"],"names":["CreateApiKeyUseCaseImpl","identityContext","eventPublisher","repository","input","hasPermission","Result","ApiKeyNotAuthorizedError","validation","createApiKeyInputSchema","ApiKeyValidationError","token","generateToken","identity","data","notGranted","findNotGrantedPermission","apiKey","mdbid","Date","ApiKeyBeforeCreateEvent","result","ApiKeyAfterCreateEvent","CreateApiKeyUseCase","CreateApiKeyUseCaseAbstraction","IdentityContext","EventPublisher","ApiKeysRepository"],"mappings":";;;;;;;;;;;AAcA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,UAAuC,CACjD;aAHUF,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,UAAU,GAAVA;IACT;IAEH,MAAM,QACFC,KAAwB,EACqC;QAC7D,MAAMC,gBACF,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAmB;QAE/D,IAAI,CAACA,eACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3B,MAAMC,aAAaC,wBAAwB,SAAS,CAACL;QACrD,IAAI,CAACI,WAAW,OAAO,EACnB,OAAOF,OAAO,IAAI,CAAC,IAAII,sBAAsBF,WAAW,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO;QAGnF,MAAMG,QAAQC;QACd,MAAMC,WAAW,IAAI,CAAC,eAAe,CAAC,WAAW;QACjD,MAAMC,OAAON,WAAW,IAAI;QAE5B,MAAMO,aAAa,MAAMC,yBAAyB;YAC9C,iBAAiB,IAAI,CAAC,eAAe;YACrC,WAAWF,KAAK,WAAW;QAC/B;QACA,IAAIC,YACA,OAAOT,OAAO,IAAI,CACd,IAAIC,yBAAyB;YACzB,SAAS,CAAC,oCAAoC,EAAEQ,WAAW,IAAI,CAAC,EAAE,CAAC;QACvE;QAIR,MAAME,SAAiB;YACnB,IAAIC;YACJ,MAAMJ,KAAK,IAAI;YACf,MAAMA,KAAK,IAAI;YACf,aAAaA,KAAK,WAAW;YAC7BH;YACA,aAAaG,KAAK,WAAW;YAC7B,WAAW,IAAIK,OAAO,WAAW;YACjC,WAAW;gBACP,IAAIN,SAAS,EAAE;gBACf,aAAaA,SAAS,WAAW;gBACjC,MAAMA,SAAS,IAAI;YACvB;QACJ;QAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIO,wBAAwB;YAAEH;YAAQ,OAAOT,WAAW,IAAI;QAAC;QAGjE,MAAMa,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAACJ;QAE5C,IAAII,OAAO,MAAM,IACb,OAAOf,OAAO,IAAI,CAACe,OAAO,KAAK;QAGnC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,uBAAuB;YAAEL;YAAQ,OAAOT,WAAW,IAAI;QAAC;QAGhE,OAAOF,OAAO,EAAE,CAACW;IACrB;AACJ;AAEO,MAAMM,0CAAsBC,oBAAAA,oBAAmD,CAAC;IACnF,gBAAgBxB;IAChB,cAAc;QAACyB;QAAiBC;QAAgBC;KAAkB;AACtE"}
|
|
@@ -6,6 +6,7 @@ import { EventPublisher } from "../../../eventPublisher/index.js";
|
|
|
6
6
|
import { updateApiKeyInputSchema } from "../shared/schemas.js";
|
|
7
7
|
import { ApiKeyAfterUpdateEvent, ApiKeyBeforeUpdateEvent } from "./events.js";
|
|
8
8
|
import { ApiKeyNotAuthorizedError, ApiKeyValidationError } from "../shared/errors.js";
|
|
9
|
+
import { findNotGrantedPermission } from "../../utils/findNotGrantedPermission.js";
|
|
9
10
|
class UpdateApiKeyUseCaseImpl {
|
|
10
11
|
constructor(repository, identityContext, eventPublisher){
|
|
11
12
|
this.repository = repository;
|
|
@@ -20,6 +21,14 @@ class UpdateApiKeyUseCaseImpl {
|
|
|
20
21
|
const existingResult = await this.repository.get(id);
|
|
21
22
|
if (existingResult.isFail()) return Result.fail(existingResult.error);
|
|
22
23
|
const existingApiKey = existingResult.value;
|
|
24
|
+
const notGranted = await findNotGrantedPermission({
|
|
25
|
+
identityContext: this.identityContext,
|
|
26
|
+
requested: validation.data.permissions,
|
|
27
|
+
existing: existingApiKey.permissions
|
|
28
|
+
});
|
|
29
|
+
if (notGranted) return Result.fail(new ApiKeyNotAuthorizedError({
|
|
30
|
+
message: `Not authorized to grant permission "${notGranted.name}".`
|
|
31
|
+
}));
|
|
23
32
|
const updatedApiKey = {
|
|
24
33
|
...existingApiKey,
|
|
25
34
|
...validation.data
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js","sources":["../../../../../src/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateApiKeyUseCase as UpdateApiKeyUseCaseAbstraction } from \"./abstractions.js\";\nimport { ApiKeysRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { updateApiKeyInputSchema } from \"../shared/schemas.js\";\nimport { ApiKeyBeforeUpdateEvent, ApiKeyAfterUpdateEvent } from \"./events.js\";\nimport type { ApiKey, UpdateApiKeyInput } from \"../shared/types.js\";\nimport { ApiKeyNotAuthorizedError, ApiKeyValidationError } from \"../shared/errors.js\";\n\nclass UpdateApiKeyUseCaseImpl implements UpdateApiKeyUseCaseAbstraction.Interface {\n private repository: ApiKeysRepository.Interface;\n private identityContext: IdentityContext.Interface;\n private eventPublisher: EventPublisher.Interface;\n\n constructor(\n repository: ApiKeysRepository.Interface,\n identityContext: IdentityContext.Interface,\n eventPublisher: EventPublisher.Interface\n ) {\n this.repository = repository;\n this.identityContext = identityContext;\n this.eventPublisher = eventPublisher;\n }\n\n async execute(\n id: string,\n input: UpdateApiKeyInput\n ): Promise<Result<ApiKey, UpdateApiKeyUseCaseAbstraction.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.apiKey\");\n if (!hasPermission) {\n return Result.fail(new ApiKeyNotAuthorizedError());\n }\n\n const validation = updateApiKeyInputSchema.safeParse(input);\n if (!validation.success) {\n return Result.fail(new ApiKeyValidationError(validation.error.issues[0].message));\n }\n\n const existingResult = await this.repository.get(id);\n if (existingResult.isFail()) {\n return Result.fail(existingResult.error);\n }\n\n const existingApiKey = existingResult.value;\n\n const updatedApiKey: ApiKey = {\n ...existingApiKey,\n ...validation.data\n };\n\n await this.eventPublisher.publish(\n new ApiKeyBeforeUpdateEvent({\n original: existingApiKey,\n updated: updatedApiKey,\n input: validation.data\n })\n );\n\n const result = await this.repository.update(updatedApiKey);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new ApiKeyAfterUpdateEvent({\n original: existingApiKey,\n updated: updatedApiKey,\n input: validation.data\n })\n );\n\n return Result.ok(updatedApiKey);\n }\n}\n\nexport const UpdateApiKeyUseCase = UpdateApiKeyUseCaseAbstraction.createImplementation({\n implementation: UpdateApiKeyUseCaseImpl,\n dependencies: [ApiKeysRepository, IdentityContext, EventPublisher]\n});\n"],"names":["UpdateApiKeyUseCaseImpl","repository","identityContext","eventPublisher","id","input","hasPermission","Result","ApiKeyNotAuthorizedError","validation","updateApiKeyInputSchema","ApiKeyValidationError","existingResult","existingApiKey","updatedApiKey","ApiKeyBeforeUpdateEvent","result","ApiKeyAfterUpdateEvent","UpdateApiKeyUseCase","UpdateApiKeyUseCaseAbstraction","ApiKeysRepository","IdentityContext","EventPublisher"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js","sources":["../../../../../src/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateApiKeyUseCase as UpdateApiKeyUseCaseAbstraction } from \"./abstractions.js\";\nimport { ApiKeysRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { updateApiKeyInputSchema } from \"../shared/schemas.js\";\nimport { ApiKeyBeforeUpdateEvent, ApiKeyAfterUpdateEvent } from \"./events.js\";\nimport type { ApiKey, UpdateApiKeyInput } from \"../shared/types.js\";\nimport { ApiKeyNotAuthorizedError, ApiKeyValidationError } from \"../shared/errors.js\";\nimport { findNotGrantedPermission } from \"../../utils/findNotGrantedPermission.js\";\n\nclass UpdateApiKeyUseCaseImpl implements UpdateApiKeyUseCaseAbstraction.Interface {\n private repository: ApiKeysRepository.Interface;\n private identityContext: IdentityContext.Interface;\n private eventPublisher: EventPublisher.Interface;\n\n constructor(\n repository: ApiKeysRepository.Interface,\n identityContext: IdentityContext.Interface,\n eventPublisher: EventPublisher.Interface\n ) {\n this.repository = repository;\n this.identityContext = identityContext;\n this.eventPublisher = eventPublisher;\n }\n\n async execute(\n id: string,\n input: UpdateApiKeyInput\n ): Promise<Result<ApiKey, UpdateApiKeyUseCaseAbstraction.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.apiKey\");\n if (!hasPermission) {\n return Result.fail(new ApiKeyNotAuthorizedError());\n }\n\n const validation = updateApiKeyInputSchema.safeParse(input);\n if (!validation.success) {\n return Result.fail(new ApiKeyValidationError(validation.error.issues[0].message));\n }\n\n const existingResult = await this.repository.get(id);\n if (existingResult.isFail()) {\n return Result.fail(existingResult.error);\n }\n\n const existingApiKey = existingResult.value;\n\n const notGranted = await findNotGrantedPermission({\n identityContext: this.identityContext,\n requested: validation.data.permissions,\n existing: existingApiKey.permissions\n });\n if (notGranted) {\n return Result.fail(\n new ApiKeyNotAuthorizedError({\n message: `Not authorized to grant permission \"${notGranted.name}\".`\n })\n );\n }\n\n const updatedApiKey: ApiKey = {\n ...existingApiKey,\n ...validation.data\n };\n\n await this.eventPublisher.publish(\n new ApiKeyBeforeUpdateEvent({\n original: existingApiKey,\n updated: updatedApiKey,\n input: validation.data\n })\n );\n\n const result = await this.repository.update(updatedApiKey);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new ApiKeyAfterUpdateEvent({\n original: existingApiKey,\n updated: updatedApiKey,\n input: validation.data\n })\n );\n\n return Result.ok(updatedApiKey);\n }\n}\n\nexport const UpdateApiKeyUseCase = UpdateApiKeyUseCaseAbstraction.createImplementation({\n implementation: UpdateApiKeyUseCaseImpl,\n dependencies: [ApiKeysRepository, IdentityContext, EventPublisher]\n});\n"],"names":["UpdateApiKeyUseCaseImpl","repository","identityContext","eventPublisher","id","input","hasPermission","Result","ApiKeyNotAuthorizedError","validation","updateApiKeyInputSchema","ApiKeyValidationError","existingResult","existingApiKey","notGranted","findNotGrantedPermission","updatedApiKey","ApiKeyBeforeUpdateEvent","result","ApiKeyAfterUpdateEvent","UpdateApiKeyUseCase","UpdateApiKeyUseCaseAbstraction","ApiKeysRepository","IdentityContext","EventPublisher"],"mappings":";;;;;;;;;AAWA,MAAMA;IAKF,YACIC,UAAuC,EACvCC,eAA0C,EAC1CC,cAAwC,CAC1C;QACE,IAAI,CAAC,UAAU,GAAGF;QAClB,IAAI,CAAC,eAAe,GAAGC;QACvB,IAAI,CAAC,cAAc,GAAGC;IAC1B;IAEA,MAAM,QACFC,EAAU,EACVC,KAAwB,EACqC;QAC7D,MAAMC,gBAAgB,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAC/D,IAAI,CAACA,eACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3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entityContext } from "../../IdentityContext/abstractions.js";
|
|
|
7
7
|
import { createRoleValidation } from "./schema.js";
|
|
8
8
|
import { RoleAfterCreateEvent, RoleBeforeCreateEvent } from "./events.js";
|
|
9
9
|
import { NotAuthorizedError, RoleExistsError, RoleValidationError } from "../shared/errors.js";
|
|
10
|
+
import { findNotGrantedPermission } from "../../utils/findNotGrantedPermission.js";
|
|
10
11
|
class CreateRoleUseCaseImpl {
|
|
11
12
|
constructor(identityContext, eventPublisher, repository){
|
|
12
13
|
this.identityContext = identityContext;
|
|
@@ -20,6 +21,13 @@ class CreateRoleUseCaseImpl {
|
|
|
20
21
|
if (!validation.success) return Result.fail(new RoleValidationError(validation.error.issues[0].message));
|
|
21
22
|
const identity = this.identityContext.getIdentity();
|
|
22
23
|
const data = validation.data;
|
|
24
|
+
const notGranted = await findNotGrantedPermission({
|
|
25
|
+
identityContext: this.identityContext,
|
|
26
|
+
requested: data.permissions
|
|
27
|
+
});
|
|
28
|
+
if (notGranted) return Result.fail(new NotAuthorizedError({
|
|
29
|
+
message: `Not authorized to grant permission "${notGranted.name}".`
|
|
30
|
+
}));
|
|
23
31
|
const existingRoleResult = await this.repository.get({
|
|
24
32
|
slug: data.slug
|
|
25
33
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/roles/CreateRole/CreateRoleUseCase.js","sources":["../../../../../src/features/security/roles/CreateRole/CreateRoleUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateRoleUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { RolesRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { createRoleValidation } from \"./schema.js\";\nimport { RoleBeforeCreateEvent, RoleAfterCreateEvent } from \"./events.js\";\nimport type { Role, CreateRoleInput } from \"../shared/types.js\";\nimport { NotAuthorizedError, RoleExistsError, RoleValidationError } from \"../shared/errors.js\";\n\nclass CreateRoleUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: RolesRepository.Interface\n ) {}\n\n async execute(input: CreateRoleInput): Promise<Result<Role, UseCaseAbstraction.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.role\");\n\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = createRoleValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new RoleValidationError(validation.error.issues[0].message));\n }\n\n const identity = this.identityContext.getIdentity();\n const data = validation.data;\n\n // Check if role with same slug already exists\n const existingRoleResult = await this.repository.get({ slug: data.slug });\n if (existingRoleResult.isOk()) {\n return Result.fail(new RoleExistsError(data.slug));\n }\n\n const role: Role = {\n id: mdbid(),\n name: data.name,\n slug: data.slug,\n description: data.description,\n permissions: data.permissions,\n system: input.system || false,\n createdOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n },\n plugin: false\n };\n\n await this.eventPublisher.publish(\n new RoleBeforeCreateEvent({ role, input: validation.data })\n );\n\n const result = await this.repository.create(role);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new RoleAfterCreateEvent({ role, input: validation.data })\n );\n\n return Result.ok(role);\n }\n}\n\nexport const CreateRoleUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: CreateRoleUseCaseImpl,\n dependencies: [IdentityContext, EventPublisher, RolesRepository]\n});\n"],"names":["CreateRoleUseCaseImpl","identityContext","eventPublisher","repository","input","hasPermission","Result","NotAuthorizedError","validation","createRoleValidation","RoleValidationError","identity","data","existingRoleResult","RoleExistsError","role","mdbid","Date","RoleBeforeCreateEvent","result","RoleAfterCreateEvent","CreateRoleUseCase","createImplementation","UseCaseAbstraction","IdentityContext","EventPublisher","RolesRepository"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/security/roles/CreateRole/CreateRoleUseCase.js","sources":["../../../../../src/features/security/roles/CreateRole/CreateRoleUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateRoleUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { RolesRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { createRoleValidation } from \"./schema.js\";\nimport { RoleBeforeCreateEvent, RoleAfterCreateEvent } from \"./events.js\";\nimport type { Role, CreateRoleInput } from \"../shared/types.js\";\nimport { NotAuthorizedError, RoleExistsError, RoleValidationError } from \"../shared/errors.js\";\nimport { findNotGrantedPermission } from \"../../utils/findNotGrantedPermission.js\";\n\nclass CreateRoleUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: RolesRepository.Interface\n ) {}\n\n async execute(input: CreateRoleInput): Promise<Result<Role, UseCaseAbstraction.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.role\");\n\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = createRoleValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new RoleValidationError(validation.error.issues[0].message));\n }\n\n const identity = this.identityContext.getIdentity();\n const data = validation.data;\n\n const notGranted = await findNotGrantedPermission({\n identityContext: this.identityContext,\n requested: data.permissions\n });\n if (notGranted) {\n return Result.fail(\n new NotAuthorizedError({\n message: `Not authorized to grant permission \"${notGranted.name}\".`\n })\n );\n }\n\n // Check if role with same slug already exists\n const existingRoleResult = await this.repository.get({ slug: data.slug });\n if (existingRoleResult.isOk()) {\n return Result.fail(new RoleExistsError(data.slug));\n }\n\n const role: Role = {\n id: mdbid(),\n name: data.name,\n slug: data.slug,\n description: data.description,\n permissions: data.permissions,\n system: input.system || false,\n createdOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n },\n plugin: false\n };\n\n await this.eventPublisher.publish(\n new RoleBeforeCreateEvent({ role, input: validation.data })\n );\n\n const result = await this.repository.create(role);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new RoleAfterCreateEvent({ role, input: validation.data })\n );\n\n return Result.ok(role);\n }\n}\n\nexport const CreateRoleUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: CreateRoleUseCaseImpl,\n dependencies: [IdentityContext, EventPublisher, RolesRepository]\n});\n"],"names":["CreateRoleUseCaseImpl","identityContext","eventPublisher","repository","input","hasPermission","Result","NotAuthorizedError","validation","createRoleValidation","RoleValidationError","identity","data","notGranted","findNotGrantedPermission","existingRoleResult","RoleExistsError","role","mdbid","Date","RoleBeforeCreateEvent","result","RoleAfterCreateEvent","CreateRoleUseCase","createImplementation","UseCaseAbstraction","IdentityContext","EventPublisher","RolesRepository"],"mappings":";;;;;;;;;;AAaA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,UAAqC,CAC/C;aAHUF,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,UAAU,GAAVA;IACT;IAEH,MAAM,QAAQC,KAAsB,EAAmD;QACnF,MAAMC,gBAAgB,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAE/D,IAAI,CAACA,eACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3B,MAAMC,aAAaC,qBAAqB,SAAS,CAACL;QAClD,IAAI,CAACI,WAAW,OAAO,EACnB,OAAOF,OAAO,IAAI,CAAC,IAAII,oBAAoBF,WAAW,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO;QAGjF,MAAMG,WAAW,IAAI,CAAC,eAAe,CAAC,WAAW;QACjD,MAAMC,OAAO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
|
|
@@ -6,6 +6,7 @@ import { EventPublisher } from "../../../eventPublisher/index.js";
|
|
|
6
6
|
import { updateRoleValidation } from "./schema.js";
|
|
7
7
|
import { RoleAfterUpdateEvent, RoleBeforeUpdateEvent } from "./events.js";
|
|
8
8
|
import { CannotUpdatePluginRolesError, NotAuthorizedError, RoleValidationError } from "../shared/errors.js";
|
|
9
|
+
import { findNotGrantedPermission } from "../../utils/findNotGrantedPermission.js";
|
|
9
10
|
class UpdateRoleUseCaseImpl {
|
|
10
11
|
constructor(repository, identityContext, eventPublisher){
|
|
11
12
|
this.repository = repository;
|
|
@@ -23,6 +24,16 @@ class UpdateRoleUseCaseImpl {
|
|
|
23
24
|
if (existingResult.isFail()) return Result.fail(existingResult.error);
|
|
24
25
|
const existingRole = existingResult.value;
|
|
25
26
|
if (existingRole.plugin) return Result.fail(new CannotUpdatePluginRolesError());
|
|
27
|
+
if (validation.data.permissions) {
|
|
28
|
+
const notGranted = await findNotGrantedPermission({
|
|
29
|
+
identityContext: this.identityContext,
|
|
30
|
+
requested: validation.data.permissions,
|
|
31
|
+
existing: existingRole.permissions
|
|
32
|
+
});
|
|
33
|
+
if (notGranted) return Result.fail(new NotAuthorizedError({
|
|
34
|
+
message: `Not authorized to grant permission "${notGranted.name}".`
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
26
37
|
const updatedRole = {
|
|
27
38
|
...existingRole,
|
|
28
39
|
...validation.data
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/roles/UpdateRole/UpdateRoleUseCase.js","sources":["../../../../../src/features/security/roles/UpdateRole/UpdateRoleUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateRoleUseCase as UseCase } from \"./abstractions.js\";\nimport { RolesRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { updateRoleValidation } from \"./schema.js\";\nimport { RoleBeforeUpdateEvent, RoleAfterUpdateEvent } from \"./events.js\";\nimport type { Role, UpdateRoleInput } from \"../shared/types.js\";\nimport {\n NotAuthorizedError,\n CannotUpdatePluginRolesError,\n RoleValidationError\n} from \"../shared/errors.js\";\n\nclass UpdateRoleUseCaseImpl implements UseCase.Interface {\n private repository: RolesRepository.Interface;\n private identityContext: IdentityContext.Interface;\n private eventPublisher: EventPublisher.Interface;\n\n constructor(\n repository: RolesRepository.Interface,\n identityContext: IdentityContext.Interface,\n eventPublisher: EventPublisher.Interface\n ) {\n this.repository = repository;\n this.identityContext = identityContext;\n this.eventPublisher = eventPublisher;\n }\n\n async execute(id: string, input: UpdateRoleInput): Promise<Result<Role, UseCase.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.role\");\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = updateRoleValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new RoleValidationError(validation.error.issues[0].message));\n }\n\n const existingResult = await this.repository.get({ id });\n if (existingResult.isFail()) {\n return Result.fail(existingResult.error);\n }\n\n const existingRole = existingResult.value;\n\n // Check if role is created via plugin\n if (existingRole.plugin) {\n return Result.fail(new CannotUpdatePluginRolesError());\n }\n\n const updatedRole: Role = {\n ...existingRole,\n ...validation.data\n };\n\n await this.eventPublisher.publish(\n new RoleBeforeUpdateEvent({\n original: existingRole,\n updated: updatedRole,\n input: validation.data\n })\n );\n\n const result = await this.repository.update(updatedRole);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new RoleAfterUpdateEvent({\n original: existingRole,\n updated: updatedRole,\n input: validation.data\n })\n );\n\n return Result.ok(updatedRole);\n }\n}\n\nexport const UpdateRoleUseCase = UseCase.createImplementation({\n implementation: UpdateRoleUseCaseImpl,\n dependencies: [RolesRepository, IdentityContext, EventPublisher]\n});\n"],"names":["UpdateRoleUseCaseImpl","repository","identityContext","eventPublisher","id","input","hasPermission","Result","NotAuthorizedError","validation","updateRoleValidation","RoleValidationError","existingResult","existingRole","CannotUpdatePluginRolesError","updatedRole","RoleBeforeUpdateEvent","result","RoleAfterUpdateEvent","UpdateRoleUseCase","UseCase","RolesRepository","IdentityContext","EventPublisher"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/security/roles/UpdateRole/UpdateRoleUseCase.js","sources":["../../../../../src/features/security/roles/UpdateRole/UpdateRoleUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateRoleUseCase as UseCase } from \"./abstractions.js\";\nimport { RolesRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { updateRoleValidation } from \"./schema.js\";\nimport { RoleBeforeUpdateEvent, RoleAfterUpdateEvent } from \"./events.js\";\nimport type { Role, UpdateRoleInput } from \"../shared/types.js\";\nimport {\n NotAuthorizedError,\n CannotUpdatePluginRolesError,\n RoleValidationError\n} from \"../shared/errors.js\";\nimport { findNotGrantedPermission } from \"../../utils/findNotGrantedPermission.js\";\n\nclass UpdateRoleUseCaseImpl implements UseCase.Interface {\n private repository: RolesRepository.Interface;\n private identityContext: IdentityContext.Interface;\n private eventPublisher: EventPublisher.Interface;\n\n constructor(\n repository: RolesRepository.Interface,\n identityContext: IdentityContext.Interface,\n eventPublisher: EventPublisher.Interface\n ) {\n this.repository = repository;\n this.identityContext = identityContext;\n this.eventPublisher = eventPublisher;\n }\n\n async execute(id: string, input: UpdateRoleInput): Promise<Result<Role, UseCase.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.role\");\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = updateRoleValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new RoleValidationError(validation.error.issues[0].message));\n }\n\n const existingResult = await this.repository.get({ id });\n if (existingResult.isFail()) {\n return Result.fail(existingResult.error);\n }\n\n const existingRole = existingResult.value;\n\n // Check if role is created via plugin\n if (existingRole.plugin) {\n return Result.fail(new CannotUpdatePluginRolesError());\n }\n\n if (validation.data.permissions) {\n const notGranted = await findNotGrantedPermission({\n identityContext: this.identityContext,\n requested: validation.data.permissions,\n existing: existingRole.permissions\n });\n if (notGranted) {\n return Result.fail(\n new NotAuthorizedError({\n message: `Not authorized to grant permission \"${notGranted.name}\".`\n })\n );\n }\n }\n\n const updatedRole: Role = {\n ...existingRole,\n ...validation.data\n };\n\n await this.eventPublisher.publish(\n new RoleBeforeUpdateEvent({\n original: existingRole,\n updated: updatedRole,\n input: validation.data\n })\n );\n\n const result = await this.repository.update(updatedRole);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new RoleAfterUpdateEvent({\n original: existingRole,\n updated: updatedRole,\n input: validation.data\n })\n );\n\n return Result.ok(updatedRole);\n }\n}\n\nexport const UpdateRoleUseCase = UseCase.createImplementation({\n implementation: UpdateRoleUseCaseImpl,\n dependencies: [RolesRepository, IdentityContext, EventPublisher]\n});\n"],"names":["UpdateRoleUseCaseImpl","repository","identityContext","eventPublisher","id","input","hasPermission","Result","NotAuthorizedError","validation","updateRoleValidation","RoleValidationError","existingResult","existingRole","CannotUpdatePluginRolesError","notGranted","findNotGrantedPermission","updatedRole","RoleBeforeUpdateEvent","result","RoleAfterUpdateEvent","UpdateRoleUseCase","UseCase","RolesRepository","IdentityContext","EventPublisher"],"mappings":";;;;;;;;;AAeA,MAAMA;IAKF,YACIC,UAAqC,EACrCC,eAA0C,EAC1CC,cAAwC,CAC1C;QACE,IAAI,CAAC,UAAU,GAAGF;QAClB,IAAI,CAAC,eAAe,GAAGC;QACvB,IAAI,CAAC,cAAc,GAAGC;IAC1B;IAEA,MAAM,QAAQC,EAAU,EAAEC,KAAsB,EAAwC;QACpF,MAAMC,gBAAgB,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAC/D,IAAI,CAACA,eACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3B,M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oBC,kBAAAA,oBAA4B,CAAC;IAC1D,gBAAgBtB;IAChB,cAAc;QAACuB;QAAiBC;QAAiBC;KAAe;AACpE"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { IdentityContext } from "../IdentityContext/abstractions.js";
|
|
2
|
+
import type { SecurityPermission } from "../../../types/security.js";
|
|
3
|
+
export interface FindNotGrantedPermissionParams {
|
|
4
|
+
identityContext: IdentityContext.Interface;
|
|
5
|
+
/**
|
|
6
|
+
* Permissions the caller wants to store (on an API key, a role...).
|
|
7
|
+
*/
|
|
8
|
+
requested: SecurityPermission[];
|
|
9
|
+
/**
|
|
10
|
+
* Permissions already stored on the record being updated.
|
|
11
|
+
* A requested permission equal to one of these is not a change, so it is not checked.
|
|
12
|
+
*/
|
|
13
|
+
existing?: SecurityPermission[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Returns the first requested permission whose name is not covered by the caller's own permissions,
|
|
17
|
+
* or `null` when every requested permission is covered.
|
|
18
|
+
*
|
|
19
|
+
* Only permission names are compared (with wildcard support, e.g. `cms.*` covers `cms.contentEntry`).
|
|
20
|
+
* Inner permission fields (`rwd`, `own`, `models`...) are not compared.
|
|
21
|
+
*/
|
|
22
|
+
export declare const findNotGrantedPermission: (params: FindNotGrantedPermissionParams) => Promise<SecurityPermission | null>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import isEqual from "lodash/isEqual.js";
|
|
2
|
+
import { minimatch } from "minimatch";
|
|
3
|
+
const findNotGrantedPermission = async (params)=>{
|
|
4
|
+
const { identityContext, requested, existing = [] } = params;
|
|
5
|
+
if (!identityContext.isAuthorizationEnabled()) return null;
|
|
6
|
+
const changed = requested.filter((permission)=>!existing.some((item)=>isEqual(item, permission)));
|
|
7
|
+
if (0 === changed.length) return null;
|
|
8
|
+
const callerPermissions = await identityContext.listPermissions();
|
|
9
|
+
if (callerPermissions.some((permission)=>"*" === permission.name)) return null;
|
|
10
|
+
for (const permission of changed){
|
|
11
|
+
const isGranted = callerPermissions.some((callerPermission)=>callerPermission.name === permission.name || minimatch(permission.name, callerPermission.name));
|
|
12
|
+
if (!isGranted) return permission;
|
|
13
|
+
}
|
|
14
|
+
return null;
|
|
15
|
+
};
|
|
16
|
+
export { findNotGrantedPermission };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=findNotGrantedPermission.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/security/utils/findNotGrantedPermission.js","sources":["../../../../src/features/security/utils/findNotGrantedPermission.ts"],"sourcesContent":["import isEqual from \"lodash/isEqual.js\";\nimport { minimatch } from \"minimatch\";\nimport type { IdentityContext } from \"../IdentityContext/abstractions.js\";\nimport type { SecurityPermission } from \"~/types/security.js\";\n\nexport interface FindNotGrantedPermissionParams {\n identityContext: IdentityContext.Interface;\n /**\n * Permissions the caller wants to store (on an API key, a role...).\n */\n requested: SecurityPermission[];\n /**\n * Permissions already stored on the record being updated.\n * A requested permission equal to one of these is not a change, so it is not checked.\n */\n existing?: SecurityPermission[];\n}\n\n/**\n * Returns the first requested permission whose name is not covered by the caller's own permissions,\n * or `null` when every requested permission is covered.\n *\n * Only permission names are compared (with wildcard support, e.g. `cms.*` covers `cms.contentEntry`).\n * Inner permission fields (`rwd`, `own`, `models`...) are not compared.\n */\nexport const findNotGrantedPermission = async (\n params: FindNotGrantedPermissionParams\n): Promise<SecurityPermission | null> => {\n const { identityContext, requested, existing = [] } = params;\n\n if (!identityContext.isAuthorizationEnabled()) {\n return null;\n }\n\n const changed = requested.filter(permission => {\n return !existing.some(item => isEqual(item, permission));\n });\n if (changed.length === 0) {\n return null;\n }\n\n const callerPermissions = await identityContext.listPermissions();\n if (callerPermissions.some(permission => permission.name === \"*\")) {\n return null;\n }\n\n for (const permission of changed) {\n const isGranted = callerPermissions.some(callerPermission => {\n return (\n callerPermission.name === permission.name ||\n minimatch(permission.name, callerPermission.name)\n );\n });\n if (!isGranted) {\n return permission;\n }\n }\n\n return null;\n};\n"],"names":["findNotGrantedPermission","params","identityContext","requested","existing","changed","permission","item","isEqual","callerPermissions","isGranted","callerPermission","minimatch"],"mappings":";;AAyBO,MAAMA,2BAA2B,OACpCC;IAEA,MAAM,EAAEC,eAAe,EAAEC,SAAS,EAAEC,WAAW,EAAE,EAAE,GAAGH;IAEtD,IAAI,CAACC,gBAAgB,sBAAsB,IACvC,OAAO;IAGX,MAAMG,UAAUF,UAAU,MAAM,CAACG,CAAAA,aACtB,CAACF,SAAS,IAAI,CAACG,CAAAA,OAAQC,QAAQD,MAAMD;IAEhD,IAAID,AAAmB,MAAnBA,QAAQ,MAAM,EACd,OAAO;IAGX,MAAMI,oBAAoB,MAAMP,gBAAgB,eAAe;IAC/D,IAAIO,kBAAkB,IAAI,CAACH,CAAAA,aAAcA,AAAoB,QAApBA,WAAW,IAAI,GACpD,OAAO;IAGX,KAAK,MAAMA,cAAcD,QAAS;QAC9B,MAAMK,YAAYD,kBAAkB,IAAI,CAACE,CAAAA,mBAEjCA,iBAAiB,IAAI,KAAKL,WAAW,IAAI,IACzCM,UAAUN,WAAW,IAAI,EAAEK,iBAAiB,IAAI;QAGxD,IAAI,CAACD,WACD,OAAOJ;IAEf;IAEA,OAAO;AACX"}
|
|
@@ -18,7 +18,7 @@ declare class InstallSystemUseCaseImpl implements UseCaseAbstraction.Interface {
|
|
|
18
18
|
private createTenantUseCase;
|
|
19
19
|
private deleteTenantUseCase;
|
|
20
20
|
constructor(identityContext: IdentityContext.Interface, tenantContext: TenantContext.Interface, eventPublisher: EventPublisher.Interface, installTenantUseCase: InstallTenantUseCase.Interface, getRootTenantUseCase: GetRootTenantUseCase.Interface, createTenantUseCase: CreateTenantUseCase.Interface, deleteTenantUseCase: DeleteTenantUseCase.Interface);
|
|
21
|
-
execute(installationInput: InstallSystemInput): Promise<Result<void, never> | Result<never, import("../../tenancy/CreateTenant/errors.js").CreateTenantError
|
|
21
|
+
execute(installationInput: InstallSystemInput): Promise<Result<void, never> | Result<never, SystemAlreadyInstalledError> | Result<never, import("../../tenancy/CreateTenant/errors.js").CreateTenantError | import("../../tenancy/CreateTenant/errors.js").TenantAlreadyExistsError> | Result<never, import("~/features/tenancy/InstallTenant/index.js").InstallTenantError | import("~/features/tenancy/InstallTenant/index.js").InstallationDependencyError>>;
|
|
22
22
|
}
|
|
23
23
|
export declare const InstallSystemUseCase: import("@webiny/di").Implementation<typeof InstallSystemUseCaseImpl>;
|
|
24
24
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/task/TaskDefinition/abstractions.js","sources":["../../../../src/features/task/TaskDefinition/abstractions.ts"],"sourcesContent":["import zod from \"zod\";\nimport { createAbstraction } from \"@webiny/feature/api\";\nimport type { GenericRecord } from \"@webiny/api/types\";\nimport type { ITask } from \"~/features/task/TaskService/index.js\";\nimport { TaskController } from \"~/features/task/TaskController/index.js\";\n\nexport type ITaskInput = GenericRecord;\n\nexport interface IResponseError {\n message: string;\n code?: string | null;\n data?: GenericRecord | null;\n stack?: string;\n}\n\nexport interface ITaskOutput {\n error?: IResponseError;\n [key: string]: any;\n}\n\n/**\n * Task run params - ONLY the input data\n * All runtime dependencies come from TaskController (injected separately)\n */\nexport interface ITaskRunParams<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> {\n input: I;\n controller: TaskController.Interface<I, O>;\n}\n\n/**\n * Data for creating a new task\n */\nexport interface ITaskCreateData<I = ITaskInput> {\n definitionId: string;\n name: string;\n input: I;\n parentId?: string;\n}\n\n/**\n * Parameters for onBeforeTrigger lifecycle hook\n */\nexport interface ITaskBeforeTriggerParams<I = ITaskInput> {\n data: ITaskCreateData<I>;\n}\n\n/**\n * Task result status enum\n */\nexport enum TaskResultStatus {\n DONE = \"done\",\n CONTINUE = \"continue\",\n ERROR = \"error\",\n ABORTED = \"aborted\"\n}\n\n/**\n * Specific result types\n */\nexport interface ITaskResultDone<O extends ITaskOutput = ITaskOutput> {\n status: TaskResultStatus.DONE;\n message?: string;\n output?: O;\n}\n\nexport interface ITaskResultContinue<I = ITaskInput> {\n status: TaskResultStatus.CONTINUE;\n input: I;\n wait?: number; // seconds to wait before next iteration\n}\n\nexport interface ITaskResultError {\n status: TaskResultStatus.ERROR;\n error: IResponseError;\n}\n\nexport interface ITaskResultAborted {\n status: TaskResultStatus.ABORTED;\n}\n\nexport type ITaskResult<I = ITaskInput, O extends ITaskOutput = ITaskOutput> =\n | ITaskResultDone<O>\n | ITaskResultContinue<I>\n | ITaskResultError\n | ITaskResultAborted;\n\nexport type ISelfCleanupEvent = \"onSuccess\" | \"onError\" | \"onAbort\";\n\nexport type ISelfCleanup = \"always\" | \"never\" | ISelfCleanupEvent | ISelfCleanupEvent[];\n\nexport type ITaskLifecycleHook<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> = {\n task: ITask<I, O>;\n};\n\n/**\n * Core TaskDefinition - minimal interface\n */\nexport interface ITaskDefinition<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> {\n id: string;\n title: string;\n description?: string;\n maxIterations?: number;\n databaseLogs?: boolean;\n isPrivate?: boolean;\n selfCleanup?: ISelfCleanup;\n\n /**\n * Core run method - receives ONLY input params\n * All runtime dependencies (logging, state management, etc.) come from TaskController\n */\n run(params: ITaskRunParams<I, O>): Promise<ITaskResult<I, O>>;\n\n /**\n * Optional lifecycle hooks - receive task data, no context.\n */\n onBeforeTrigger?(params: ITaskBeforeTriggerParams<I>): Promise<void>;\n onDone?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n onError?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n onAbort?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n onMaxIterations?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n /**\n * Create a validation schema for the task input.\n * This will be used to validate the input before the task is triggered.\n */\n createInputValidation?(\n params: ITaskCreateInputValidationParams\n ): GenericRecord<keyof I, zod.Schema> | zod.Schema;\n}\n\nexport interface ITaskCreateInputValidationParams {\n validator: typeof zod;\n}\n\n/** Define a long-running background task with lifecycle hooks. */\nexport const TaskDefinition = createAbstraction<ITaskDefinition>(\"TaskDefinition\");\n\n/**\n * IRunnableTaskDefinition represents a TaskDefinition after decoration/processing.\n * All optional runtime properties are guaranteed to have values (with defaults applied).\n * Used internally by the task runner to ensure consistent behavior.\n */\nexport interface IRunnableTaskDefinition<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> extends ITaskDefinition<I, O> {\n // Override optional properties to be required with guaranteed values\n isPrivate: boolean;\n databaseLogs: boolean;\n maxIterations: number;\n}\n\nexport namespace TaskDefinition {\n export type Interface<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskDefinition<I, O>;\n\n export type TaskInput = ITaskInput;\n\n export type TaskOutput = ITaskOutput;\n\n export type Runnable<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = IRunnableTaskDefinition<I, O>;\n\n export type RunParams<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskRunParams<I, O>;\n\n export type Result<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskResult<I, O>;\n\n export type Task<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITask<I, O>;\n\n export type ResultDone<O extends ITaskOutput = ITaskOutput> = ITaskResultDone<O>;\n export type ResultContinue<I = ITaskInput> = ITaskResultContinue<I>;\n export type ResultError = ITaskResultError;\n export type ResultAborted = ITaskResultAborted;\n export type CreateInputValidationParams = ITaskCreateInputValidationParams;\n export type TaskCreateData<I = ITaskInput> = ITaskCreateData<I>;\n export type BeforeTriggerParams<I = ITaskInput> = ITaskBeforeTriggerParams<I>;\n export type LifecycleHookParams<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskLifecycleHook<I, O>;\n\n export type SelfCleanupEvent = ISelfCleanupEvent;\n export type SelfCleanup = ISelfCleanup;\n}\n"],"names":["TaskResultStatus","TaskDefinition","createAbstraction"],"mappings":";AAoDO,IAAKA,gCAAgBA,WAAAA,GAAAA,
|
|
1
|
+
{"version":3,"file":"features/task/TaskDefinition/abstractions.js","sources":["../../../../src/features/task/TaskDefinition/abstractions.ts"],"sourcesContent":["import zod from \"zod\";\nimport { createAbstraction } from \"@webiny/feature/api\";\nimport type { GenericRecord } from \"@webiny/api/types\";\nimport type { ITask } from \"~/features/task/TaskService/index.js\";\nimport { TaskController } from \"~/features/task/TaskController/index.js\";\n\nexport type ITaskInput = GenericRecord;\n\nexport interface IResponseError {\n message: string;\n code?: string | null;\n data?: GenericRecord | null;\n stack?: string;\n}\n\nexport interface ITaskOutput {\n error?: IResponseError;\n [key: string]: any;\n}\n\n/**\n * Task run params - ONLY the input data\n * All runtime dependencies come from TaskController (injected separately)\n */\nexport interface ITaskRunParams<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> {\n input: I;\n controller: TaskController.Interface<I, O>;\n}\n\n/**\n * Data for creating a new task\n */\nexport interface ITaskCreateData<I = ITaskInput> {\n definitionId: string;\n name: string;\n input: I;\n parentId?: string;\n}\n\n/**\n * Parameters for onBeforeTrigger lifecycle hook\n */\nexport interface ITaskBeforeTriggerParams<I = ITaskInput> {\n data: ITaskCreateData<I>;\n}\n\n/**\n * Task result status enum\n */\nexport enum TaskResultStatus {\n DONE = \"done\",\n CONTINUE = \"continue\",\n ERROR = \"error\",\n ABORTED = \"aborted\"\n}\n\n/**\n * Specific result types\n */\nexport interface ITaskResultDone<O extends ITaskOutput = ITaskOutput> {\n status: TaskResultStatus.DONE;\n message?: string;\n output?: O;\n}\n\nexport interface ITaskResultContinue<I = ITaskInput> {\n status: TaskResultStatus.CONTINUE;\n input: I;\n wait?: number; // seconds to wait before next iteration\n}\n\nexport interface ITaskResultError {\n status: TaskResultStatus.ERROR;\n error: IResponseError;\n}\n\nexport interface ITaskResultAborted {\n status: TaskResultStatus.ABORTED;\n}\n\nexport type ITaskResult<I = ITaskInput, O extends ITaskOutput = ITaskOutput> =\n | ITaskResultDone<O>\n | ITaskResultContinue<I>\n | ITaskResultError\n | ITaskResultAborted;\n\nexport type ISelfCleanupEvent = \"onSuccess\" | \"onError\" | \"onAbort\";\n\nexport type ISelfCleanup = \"always\" | \"never\" | ISelfCleanupEvent | ISelfCleanupEvent[];\n\nexport type ITaskLifecycleHook<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> = {\n task: ITask<I, O>;\n};\n\n/**\n * Core TaskDefinition - minimal interface\n */\nexport interface ITaskDefinition<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> {\n id: string;\n title: string;\n description?: string;\n maxIterations?: number;\n databaseLogs?: boolean;\n isPrivate?: boolean;\n selfCleanup?: ISelfCleanup;\n\n /**\n * Core run method - receives ONLY input params\n * All runtime dependencies (logging, state management, etc.) come from TaskController\n */\n run(params: ITaskRunParams<I, O>): Promise<ITaskResult<I, O>>;\n\n /**\n * Optional lifecycle hooks - receive task data, no context.\n */\n onBeforeTrigger?(params: ITaskBeforeTriggerParams<I>): Promise<void>;\n onDone?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n onError?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n onAbort?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n onMaxIterations?(params: ITaskLifecycleHook<I, O>): Promise<void>;\n /**\n * Create a validation schema for the task input.\n * This will be used to validate the input before the task is triggered.\n */\n createInputValidation?(\n params: ITaskCreateInputValidationParams\n ): GenericRecord<keyof I, zod.Schema> | zod.Schema;\n}\n\nexport interface ITaskCreateInputValidationParams {\n validator: typeof zod;\n}\n\n/** Define a long-running background task with lifecycle hooks. */\nexport const TaskDefinition = createAbstraction<ITaskDefinition>(\"TaskDefinition\");\n\n/**\n * IRunnableTaskDefinition represents a TaskDefinition after decoration/processing.\n * All optional runtime properties are guaranteed to have values (with defaults applied).\n * Used internally by the task runner to ensure consistent behavior.\n */\nexport interface IRunnableTaskDefinition<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n> extends ITaskDefinition<I, O> {\n // Override optional properties to be required with guaranteed values\n isPrivate: boolean;\n databaseLogs: boolean;\n maxIterations: number;\n}\n\nexport namespace TaskDefinition {\n export type Interface<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskDefinition<I, O>;\n\n export type TaskInput = ITaskInput;\n\n export type TaskOutput = ITaskOutput;\n\n export type Runnable<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = IRunnableTaskDefinition<I, O>;\n\n export type RunParams<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskRunParams<I, O>;\n\n export type Result<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskResult<I, O>;\n\n export type Task<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITask<I, O>;\n\n export type ResultDone<O extends ITaskOutput = ITaskOutput> = ITaskResultDone<O>;\n export type ResultContinue<I = ITaskInput> = ITaskResultContinue<I>;\n export type ResultError = ITaskResultError;\n export type ResultAborted = ITaskResultAborted;\n export type CreateInputValidationParams = ITaskCreateInputValidationParams;\n export type TaskCreateData<I = ITaskInput> = ITaskCreateData<I>;\n export type BeforeTriggerParams<I = ITaskInput> = ITaskBeforeTriggerParams<I>;\n export type LifecycleHookParams<\n I extends ITaskInput = ITaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITaskLifecycleHook<I, O>;\n\n export type SelfCleanupEvent = ISelfCleanupEvent;\n export type SelfCleanup = ISelfCleanup;\n}\n"],"names":["TaskResultStatus","TaskDefinition","createAbstraction"],"mappings":";AAoDO,IAAKA,gCAAgBA,WAAAA,GAAAA,SAAAA,gBAAAA;;;;;;;AA2FrB,MAAMC,iBAAiBC,kBAAmC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/task/TaskService/abstractions.js","sources":["../../../../src/features/task/TaskService/abstractions.ts"],"sourcesContent":["import { BaseError, createAbstraction, Result } from \"@webiny/feature/api\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\nimport { type ITaskOutput, TaskDefinition } from \"~/features/task/TaskDefinition/index.js\";\n\n/** Trigger and manage long-running background tasks. */\nexport const TaskService = createAbstraction<ITaskService>(\"TaskService\");\n\nexport namespace TaskService {\n export type Interface = ITaskService;\n /**\n * This is the output of `trigger` and `abort` actions.\n */\n export type GenericOutput = IGenericOutput;\n\n export type TaskInput = TaskDefinition.TaskInput;\n\n export type Task<\n I extends TaskDefinition.TaskInput = TaskDefinition.TaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITask<I, O>;\n}\n\n// The service info depends on the implementation.\n// We cannot have a more precise type here, since implementation can be anything (AWS, Azure, etc.).\nexport type IServiceInfo = GenericRecord;\n\nexport interface IResponseError {\n message: string;\n code?: string | null;\n data?: GenericRecord | null;\n stack?: string;\n}\n\nexport interface ITaskAbortParams {\n id: string;\n message?: string;\n}\n\nexport interface ITaskService {\n trigger: <\n T extends TaskDefinition.TaskInput = TaskDefinition.TaskInput,\n O extends IGenericOutput = IGenericOutput\n >(\n params: ITaskTriggerParams<T>\n ) => Promise<Result<ITask<T, O>, BaseError>>;\n abort: <\n T extends TaskDefinition.TaskInput = TaskDefinition.TaskInput,\n O extends IGenericOutput = IGenericOutput\n >(\n params: ITaskAbortParams\n ) => Promise<Result<ITask<T, O>, BaseError>>;\n fetchServiceInfo: (input: ITask<any, any> | string) => Promise<Result<IServiceInfo, BaseError>>;\n}\n\nexport interface IGenericOutput {\n error?: IResponseError;\n [key: string]:\n | string\n | string[]\n | number\n | boolean\n | undefined\n | Record<string, any>\n | IResponseError;\n}\n\nexport interface ITaskTriggerParams<I = TaskDefinition.TaskInput> {\n parent?: Pick<ITask, \"id\">;\n definition: string;\n name?: string;\n input?: I;\n delay?: number;\n}\n\nexport interface ITaskValues<T = GenericRecord, O extends ITaskOutput = ITaskOutput> {\n startedOn?: string;\n finishedOn?: string;\n eventResponse: GenericRecord | undefined;\n iterations: number;\n parentId?: string;\n name: string;\n taskStatus: TaskDataStatus;\n definitionId: string;\n executionName: string;\n input: T;\n output?: O;\n}\n\nexport interface ITask<T = GenericRecord, O extends ITaskOutput = ITaskOutput> extends ITaskValues<\n T,\n O\n> {\n /**\n * ID without the revision number (for example: #0001).\n */\n id: string;\n createdOn: string;\n savedOn: string;\n createdBy: ITaskIdentity;\n}\n\nexport enum TaskDataStatus {\n PENDING = \"pending\",\n RUNNING = \"running\",\n FAILED = \"failed\",\n SUCCESS = \"success\",\n ABORTED = \"aborted\"\n}\n\nexport interface ITaskIdentity {\n id: string;\n displayName: string;\n type: string;\n}\n"],"names":["TaskService","createAbstraction","TaskDataStatus"],"mappings":";AAKO,MAAMA,cAAcC,kBAAgC;AAgGpD,IAAKC,8BAAcA,WAAAA,GAAAA,
|
|
1
|
+
{"version":3,"file":"features/task/TaskService/abstractions.js","sources":["../../../../src/features/task/TaskService/abstractions.ts"],"sourcesContent":["import { BaseError, createAbstraction, Result } from \"@webiny/feature/api\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\nimport { type ITaskOutput, TaskDefinition } from \"~/features/task/TaskDefinition/index.js\";\n\n/** Trigger and manage long-running background tasks. */\nexport const TaskService = createAbstraction<ITaskService>(\"TaskService\");\n\nexport namespace TaskService {\n export type Interface = ITaskService;\n /**\n * This is the output of `trigger` and `abort` actions.\n */\n export type GenericOutput = IGenericOutput;\n\n export type TaskInput = TaskDefinition.TaskInput;\n\n export type Task<\n I extends TaskDefinition.TaskInput = TaskDefinition.TaskInput,\n O extends ITaskOutput = ITaskOutput\n > = ITask<I, O>;\n}\n\n// The service info depends on the implementation.\n// We cannot have a more precise type here, since implementation can be anything (AWS, Azure, etc.).\nexport type IServiceInfo = GenericRecord;\n\nexport interface IResponseError {\n message: string;\n code?: string | null;\n data?: GenericRecord | null;\n stack?: string;\n}\n\nexport interface ITaskAbortParams {\n id: string;\n message?: string;\n}\n\nexport interface ITaskService {\n trigger: <\n T extends TaskDefinition.TaskInput = TaskDefinition.TaskInput,\n O extends IGenericOutput = IGenericOutput\n >(\n params: ITaskTriggerParams<T>\n ) => Promise<Result<ITask<T, O>, BaseError>>;\n abort: <\n T extends TaskDefinition.TaskInput = TaskDefinition.TaskInput,\n O extends IGenericOutput = IGenericOutput\n >(\n params: ITaskAbortParams\n ) => Promise<Result<ITask<T, O>, BaseError>>;\n fetchServiceInfo: (input: ITask<any, any> | string) => Promise<Result<IServiceInfo, BaseError>>;\n}\n\nexport interface IGenericOutput {\n error?: IResponseError;\n [key: string]:\n | string\n | string[]\n | number\n | boolean\n | undefined\n | Record<string, any>\n | IResponseError;\n}\n\nexport interface ITaskTriggerParams<I = TaskDefinition.TaskInput> {\n parent?: Pick<ITask, \"id\">;\n definition: string;\n name?: string;\n input?: I;\n delay?: number;\n}\n\nexport interface ITaskValues<T = GenericRecord, O extends ITaskOutput = ITaskOutput> {\n startedOn?: string;\n finishedOn?: string;\n eventResponse: GenericRecord | undefined;\n iterations: number;\n parentId?: string;\n name: string;\n taskStatus: TaskDataStatus;\n definitionId: string;\n executionName: string;\n input: T;\n output?: O;\n}\n\nexport interface ITask<T = GenericRecord, O extends ITaskOutput = ITaskOutput> extends ITaskValues<\n T,\n O\n> {\n /**\n * ID without the revision number (for example: #0001).\n */\n id: string;\n createdOn: string;\n savedOn: string;\n createdBy: ITaskIdentity;\n}\n\nexport enum TaskDataStatus {\n PENDING = \"pending\",\n RUNNING = \"running\",\n FAILED = \"failed\",\n SUCCESS = \"success\",\n ABORTED = \"aborted\"\n}\n\nexport interface ITaskIdentity {\n id: string;\n displayName: string;\n type: string;\n}\n"],"names":["TaskService","createAbstraction","TaskDataStatus"],"mappings":";AAKO,MAAMA,cAAcC,kBAAgC;AAgGpD,IAAKC,8BAAcA,WAAAA,GAAAA,SAAAA,cAAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/tenancy/CreateTenant/CreateTenantRepository.js","sources":["../../../../src/features/tenancy/CreateTenant/CreateTenantRepository.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { CreateTenantRepository as RepositoryAbstraction } from \"./abstractions.js\";\nimport { CreateTenantGateway } from \"./abstractions.js\";\nimport { TenantCache } from \"../shared/abstractions.js\";\nimport type { Tenant } from \"~/types/tenancy.js\";\n\nclass CreateTenantRepositoryImpl implements RepositoryAbstraction.Interface {\n constructor(\n private gateway: CreateTenantGateway.Interface,\n private cache: TenantCache.Interface\n ) {}\n\n async create(tenant: Tenant) {\n const created = await this.gateway.createTenant(tenant);\n this.cache.prime(created.id, created);\n return created;\n }\n}\n\nexport const CreateTenantRepository = createImplementation({\n abstraction: RepositoryAbstraction,\n implementation: CreateTenantRepositoryImpl,\n dependencies: [CreateTenantGateway, TenantCache]\n});\n"],"names":["CreateTenantRepositoryImpl","gateway","cache","tenant","created","CreateTenantRepository","createImplementation","RepositoryAbstraction","CreateTenantGateway","TenantCache"],"mappings":";;;AAMA,MAAMA;IACF,YACYC,OAAsC,EACtCC,KAA4B,CACtC;aAFUD,OAAO,GAAPA;aACAC,KAAK,GAALA;IACT;IAEH,MAAM,OAAOC,MAAc,EAAE;QACzB,MAAMC,UAAU,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAACD;
|
|
1
|
+
{"version":3,"file":"features/tenancy/CreateTenant/CreateTenantRepository.js","sources":["../../../../src/features/tenancy/CreateTenant/CreateTenantRepository.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { CreateTenantRepository as RepositoryAbstraction } from \"./abstractions.js\";\nimport { CreateTenantGateway } from \"./abstractions.js\";\nimport { TenantCache } from \"../shared/abstractions.js\";\nimport type { Tenant } from \"~/types/tenancy.js\";\n\nclass CreateTenantRepositoryImpl implements RepositoryAbstraction.Interface {\n constructor(\n private gateway: CreateTenantGateway.Interface,\n private cache: TenantCache.Interface\n ) {}\n\n async create(tenant: Tenant) {\n const created = await this.gateway.createTenant(tenant);\n // The id may already be cached as \"not found\" (the existence check), and prime() doesn't\n // overwrite a cached key.\n this.cache.clear(created.id);\n this.cache.prime(created.id, created);\n return created;\n }\n}\n\nexport const CreateTenantRepository = createImplementation({\n abstraction: RepositoryAbstraction,\n implementation: CreateTenantRepositoryImpl,\n dependencies: [CreateTenantGateway, TenantCache]\n});\n"],"names":["CreateTenantRepositoryImpl","gateway","cache","tenant","created","CreateTenantRepository","createImplementation","RepositoryAbstraction","CreateTenantGateway","TenantCache"],"mappings":";;;AAMA,MAAMA;IACF,YACYC,OAAsC,EACtCC,KAA4B,CACtC;aAFUD,OAAO,GAAPA;aACAC,KAAK,GAALA;IACT;IAEH,MAAM,OAAOC,MAAc,EAAE;QACzB,MAAMC,UAAU,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAACD;QAGhD,IAAI,CAAC,KAAK,CAAC,KAAK,CAACC,QAAQ,EAAE;QAC3B,IAAI,CAAC,KAAK,CAAC,KAAK,CAACA,QAAQ,EAAE,EAAEA;QAC7B,OAAOA;IACX;AACJ;AAEO,MAAMC,gDAAyBC,qBAAqB;IACvD,aAAaC;IACb,gBAAgBP;IAChB,cAAc;QAACQ;QAAqBC;KAAY;AACpD"}
|
|
@@ -3,12 +3,14 @@ import { EventPublisher } from "../../../features/eventPublisher/index.js";
|
|
|
3
3
|
import { CreateTenantUseCase as UseCaseAbstraction } from "./abstractions.js";
|
|
4
4
|
import { CreateTenantRepository } from "./abstractions.js";
|
|
5
5
|
import type { Tenant, CreateTenantInput } from "../../../types/tenancy.js";
|
|
6
|
-
import { CreateTenantError } from "../../../features/tenancy/CreateTenant/errors.js";
|
|
6
|
+
import { CreateTenantError, TenantAlreadyExistsError } from "../../../features/tenancy/CreateTenant/errors.js";
|
|
7
|
+
import { GetTenantByIdUseCase } from "../../../features/tenancy/GetTenantById/abstractions.js";
|
|
7
8
|
declare class CreateTenantUseCaseImpl implements UseCaseAbstraction.Interface {
|
|
8
9
|
private eventPublisher;
|
|
9
10
|
private repository;
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
private getTenantById;
|
|
12
|
+
constructor(eventPublisher: EventPublisher.Interface, repository: CreateTenantRepository.Interface, getTenantById: GetTenantByIdUseCase.Interface);
|
|
13
|
+
execute(data: CreateTenantInput): Promise<Result<Tenant, never> | Result<never, TenantAlreadyExistsError> | Result<never, CreateTenantError>>;
|
|
12
14
|
}
|
|
13
15
|
export declare const CreateTenantUseCase: import("@webiny/di").Implementation<typeof CreateTenantUseCaseImpl>;
|
|
14
16
|
export {};
|
|
@@ -3,13 +3,19 @@ import { EventPublisher } from "../../eventPublisher/index.js";
|
|
|
3
3
|
import { mdbid } from "@webiny/utils";
|
|
4
4
|
import { CreateTenantRepository, CreateTenantUseCase } from "./abstractions.js";
|
|
5
5
|
import { TenantAfterCreateEvent, TenantBeforeCreateEvent } from "./events.js";
|
|
6
|
-
import { CreateTenantError } from "./errors.js";
|
|
6
|
+
import { CreateTenantError, TenantAlreadyExistsError } from "./errors.js";
|
|
7
|
+
import { GetTenantByIdUseCase } from "../GetTenantById/abstractions.js";
|
|
7
8
|
class CreateTenantUseCaseImpl {
|
|
8
|
-
constructor(eventPublisher, repository){
|
|
9
|
+
constructor(eventPublisher, repository, getTenantById){
|
|
9
10
|
this.eventPublisher = eventPublisher;
|
|
10
11
|
this.repository = repository;
|
|
12
|
+
this.getTenantById = getTenantById;
|
|
11
13
|
}
|
|
12
14
|
async execute(data) {
|
|
15
|
+
if (data.id) {
|
|
16
|
+
const existing = await this.getTenantById.execute(data.id);
|
|
17
|
+
if (existing.isOk()) return Result.fail(new TenantAlreadyExistsError(data.id));
|
|
18
|
+
}
|
|
13
19
|
const tenant = {
|
|
14
20
|
...data,
|
|
15
21
|
id: data.id ?? mdbid(),
|
|
@@ -46,7 +52,8 @@ const CreateTenantUseCase_CreateTenantUseCase = createImplementation({
|
|
|
46
52
|
implementation: CreateTenantUseCaseImpl,
|
|
47
53
|
dependencies: [
|
|
48
54
|
EventPublisher,
|
|
49
|
-
CreateTenantRepository
|
|
55
|
+
CreateTenantRepository,
|
|
56
|
+
GetTenantByIdUseCase
|
|
50
57
|
]
|
|
51
58
|
});
|
|
52
59
|
export { CreateTenantUseCase_CreateTenantUseCase as CreateTenantUseCase };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/tenancy/CreateTenant/CreateTenantUseCase.js","sources":["../../../../src/features/tenancy/CreateTenant/CreateTenantUseCase.ts"],"sourcesContent":["import { Result, createImplementation } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { mdbid } from \"@webiny/utils\";\nimport { CreateTenantUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { CreateTenantRepository } from \"./abstractions.js\";\nimport { TenantBeforeCreateEvent, TenantAfterCreateEvent } from \"./events.js\";\nimport type { Tenant, CreateTenantInput } from \"~/types/tenancy.js\";\nimport {
|
|
1
|
+
{"version":3,"file":"features/tenancy/CreateTenant/CreateTenantUseCase.js","sources":["../../../../src/features/tenancy/CreateTenant/CreateTenantUseCase.ts"],"sourcesContent":["import { Result, createImplementation } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { mdbid } from \"@webiny/utils\";\nimport { CreateTenantUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { CreateTenantRepository } from \"./abstractions.js\";\nimport { TenantBeforeCreateEvent, TenantAfterCreateEvent } from \"./events.js\";\nimport type { Tenant, CreateTenantInput } from \"~/types/tenancy.js\";\nimport {\n CreateTenantError,\n TenantAlreadyExistsError\n} from \"~/features/tenancy/CreateTenant/errors.js\";\nimport { GetTenantByIdUseCase } from \"~/features/tenancy/GetTenantById/abstractions.js\";\n\nclass CreateTenantUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private eventPublisher: EventPublisher.Interface,\n private repository: CreateTenantRepository.Interface,\n private getTenantById: GetTenantByIdUseCase.Interface\n ) {}\n\n async execute(data: CreateTenantInput) {\n /* Never overwrite an existing tenant: its data is keyed by the tenant id. */\n if (data.id) {\n const existing = await this.getTenantById.execute(data.id);\n if (existing.isOk()) {\n return Result.fail(new TenantAlreadyExistsError(data.id));\n }\n }\n\n const tenant: Tenant = {\n ...data,\n id: data.id ?? mdbid(),\n status: \"disabled\",\n isInstalled: false,\n settings: {\n ...(data.settings || {})\n },\n savedOn: new Date().toISOString(),\n createdOn: new Date().toISOString(),\n parent: data.parent || null\n };\n\n await this.eventPublisher.publish(new TenantBeforeCreateEvent({ tenant, input: data }));\n\n let createdTenant: Tenant;\n try {\n createdTenant = await this.repository.create(tenant);\n } catch (e) {\n return Result.fail(new CreateTenantError({ reason: e.message }));\n }\n\n await this.eventPublisher.publish(\n new TenantAfterCreateEvent({ tenant: createdTenant, input: data })\n );\n\n return Result.ok(createdTenant);\n }\n}\n\nexport const CreateTenantUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: CreateTenantUseCaseImpl,\n dependencies: [EventPublisher, CreateTenantRepository, GetTenantByIdUseCase]\n});\n"],"names":["CreateTenantUseCaseImpl","eventPublisher","repository","getTenantById","data","existing","Result","TenantAlreadyExistsError","tenant","mdbid","Date","TenantBeforeCreateEvent","createdTenant","e","CreateTenantError","TenantAfterCreateEvent","CreateTenantUseCase","createImplementation","UseCaseAbstraction","EventPublisher","CreateTenantRepository","GetTenantByIdUseCase"],"mappings":";;;;;;;AAaA,MAAMA;IACF,YACYC,cAAwC,EACxCC,UAA4C,EAC5CC,aAA6C,CACvD;aAHUF,cAAc,GAAdA;aACAC,UAAU,GAAVA;aACAC,aAAa,GAAbA;IACT;IAEH,MAAM,QAAQC,IAAuB,EAAE;QAEnC,IAAIA,KAAK,EAAE,EAAE;YACT,MAAMC,WAAW,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAACD,KAAK,EAAE;YACzD,IAAIC,SAAS,IAAI,IACb,OAAOC,OAAO,IAAI,CAAC,IAAIC,yBAAyBH,KAAK,EAAE;QAE/D;QAEA,MAAMI,SAAiB;YACnB,GAAGJ,IAAI;YACP,IAAIA,KAAK,EAAE,IAAIK;YACf,QAAQ;YACR,aAAa;YACb,UAAU;gBACN,GAAIL,KAAK,QAAQ,IAAI,CAAC,CAAC;YAC3B;YACA,SAAS,IAAIM,OAAO,WAAW;YAC/B,WAAW,IAAIA,OAAO,WAAW;YACjC,QAAQN,KAAK,MAAM,IAAI;QAC3B;QAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,IAAIO,wBAAwB;YAAEH;YAAQ,OAAOJ;QAAK;QAEpF,IAAIQ;QACJ,IAAI;YACAA,gBAAgB,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAACJ;QACjD,EAAE,OAAOK,GAAG;YACR,OAAOP,OAAO,IAAI,CAAC,IAAIQ,kBAAkB;gBAAE,QAAQD,EAAE,OAAO;YAAC;QACjE;QAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIE,uBAAuB;YAAE,QAAQH;YAAe,OAAOR;QAAK;QAGpE,OAAOE,OAAO,EAAE,CAACM;IACrB;AACJ;AAEO,MAAMI,0CAAsBC,qBAAqB;IACpD,aAAaC;IACb,gBAAgBlB;IAChB,cAAc;QAACmB;QAAgBC;QAAwBC;KAAqB;AAChF"}
|
|
@@ -2,12 +2,13 @@ import { Result } from "@webiny/feature/api";
|
|
|
2
2
|
import type { IEventHandler, DomainEvent } from "../../../features/eventPublisher/index.js";
|
|
3
3
|
import type { Tenant, CreateTenantInput } from "../../../types/tenancy.js";
|
|
4
4
|
import type { TenantBeforeCreatePayload, TenantAfterCreatePayload } from "./events.js";
|
|
5
|
-
import { CreateTenantError } from "./errors.js";
|
|
5
|
+
import type { CreateTenantError, TenantAlreadyExistsError } from "./errors.js";
|
|
6
6
|
/**
|
|
7
7
|
* Errors
|
|
8
8
|
*/
|
|
9
9
|
export interface ICreateTenantErrors {
|
|
10
10
|
base: CreateTenantError;
|
|
11
|
+
alreadyExists: TenantAlreadyExistsError;
|
|
11
12
|
}
|
|
12
13
|
/**
|
|
13
14
|
* Use Case
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/tenancy/CreateTenant/abstractions.js","sources":["../../../../src/features/tenancy/CreateTenant/abstractions.ts"],"sourcesContent":["import { createAbstraction, Result } from \"@webiny/feature/api\";\nimport type { IEventHandler, DomainEvent } from \"~/features/eventPublisher/index.js\";\nimport type { Tenant, CreateTenantInput } from \"~/types/tenancy.js\";\nimport type { TenantBeforeCreatePayload, TenantAfterCreatePayload } from \"./events.js\";\nimport { CreateTenantError } from \"./errors.js\";\n\n/**\n * Errors\n */\nexport interface ICreateTenantErrors {\n base: CreateTenantError;\n}\n\n/**\n * Use Case\n */\nexport interface ICreateTenantUseCase {\n execute(\n data: CreateTenantInput\n ): Promise<Result<Tenant, ICreateTenantErrors[keyof ICreateTenantErrors]>>;\n}\n\n/** Create a new tenant. */\nexport const CreateTenantUseCase = createAbstraction<ICreateTenantUseCase>(\"CreateTenantUseCase\");\n\nexport namespace CreateTenantUseCase {\n export type Interface = ICreateTenantUseCase;\n export type Errors = ICreateTenantErrors[keyof ICreateTenantErrors];\n}\n\n/**\n * Repository\n */\nexport interface ICreateTenantRepository {\n create(tenant: Tenant): Promise<Tenant>;\n}\n\n/** Persist a newly created tenant. */\nexport const CreateTenantRepository =\n createAbstraction<ICreateTenantRepository>(\"CreateTenantRepository\");\n\nexport namespace CreateTenantRepository {\n export type Interface = ICreateTenantRepository;\n}\n\n/**\n * Gateway\n */\nexport interface ICreateTenantGateway {\n createTenant(data: Tenant): Promise<Tenant>;\n}\n\n/** Storage gateway for tenant creation. */\nexport const CreateTenantGateway = createAbstraction<ICreateTenantGateway>(\"CreateTenantGateway\");\n\nexport namespace CreateTenantGateway {\n export type Interface = ICreateTenantGateway;\n}\n\n/** Hook into tenant lifecycle before a tenant is created. */\nexport const TenantBeforeCreateEventHandler = createAbstraction<\n IEventHandler<DomainEvent<TenantBeforeCreatePayload>>\n>(\"TenantBeforeCreateEventHandler\");\n\nexport namespace TenantBeforeCreateEventHandler {\n export type Interface = IEventHandler<DomainEvent<TenantBeforeCreatePayload>>;\n export type Event = DomainEvent<TenantBeforeCreatePayload>;\n}\n\n/** Hook into tenant lifecycle after a tenant is created. */\nexport const TenantAfterCreateEventHandler = createAbstraction<\n IEventHandler<DomainEvent<TenantAfterCreatePayload>>\n>(\"TenantAfterCreateEventHandler\");\n\nexport namespace TenantAfterCreateEventHandler {\n export type Interface = IEventHandler<DomainEvent<TenantAfterCreatePayload>>;\n export type Event = DomainEvent<TenantAfterCreatePayload>;\n}\n"],"names":["CreateTenantUseCase","createAbstraction","CreateTenantRepository","CreateTenantGateway","TenantBeforeCreateEventHandler","TenantAfterCreateEventHandler"],"mappings":";
|
|
1
|
+
{"version":3,"file":"features/tenancy/CreateTenant/abstractions.js","sources":["../../../../src/features/tenancy/CreateTenant/abstractions.ts"],"sourcesContent":["import { createAbstraction, Result } from \"@webiny/feature/api\";\nimport type { IEventHandler, DomainEvent } from \"~/features/eventPublisher/index.js\";\nimport type { Tenant, CreateTenantInput } from \"~/types/tenancy.js\";\nimport type { TenantBeforeCreatePayload, TenantAfterCreatePayload } from \"./events.js\";\nimport type { CreateTenantError, TenantAlreadyExistsError } from \"./errors.js\";\n\n/**\n * Errors\n */\nexport interface ICreateTenantErrors {\n base: CreateTenantError;\n alreadyExists: TenantAlreadyExistsError;\n}\n\n/**\n * Use Case\n */\nexport interface ICreateTenantUseCase {\n execute(\n data: CreateTenantInput\n ): Promise<Result<Tenant, ICreateTenantErrors[keyof ICreateTenantErrors]>>;\n}\n\n/** Create a new tenant. */\nexport const CreateTenantUseCase = createAbstraction<ICreateTenantUseCase>(\"CreateTenantUseCase\");\n\nexport namespace CreateTenantUseCase {\n export type Interface = ICreateTenantUseCase;\n export type Errors = ICreateTenantErrors[keyof ICreateTenantErrors];\n}\n\n/**\n * Repository\n */\nexport interface ICreateTenantRepository {\n create(tenant: Tenant): Promise<Tenant>;\n}\n\n/** Persist a newly created tenant. */\nexport const CreateTenantRepository =\n createAbstraction<ICreateTenantRepository>(\"CreateTenantRepository\");\n\nexport namespace CreateTenantRepository {\n export type Interface = ICreateTenantRepository;\n}\n\n/**\n * Gateway\n */\nexport interface ICreateTenantGateway {\n createTenant(data: Tenant): Promise<Tenant>;\n}\n\n/** Storage gateway for tenant creation. */\nexport const CreateTenantGateway = createAbstraction<ICreateTenantGateway>(\"CreateTenantGateway\");\n\nexport namespace CreateTenantGateway {\n export type Interface = ICreateTenantGateway;\n}\n\n/** Hook into tenant lifecycle before a tenant is created. */\nexport const TenantBeforeCreateEventHandler = createAbstraction<\n IEventHandler<DomainEvent<TenantBeforeCreatePayload>>\n>(\"TenantBeforeCreateEventHandler\");\n\nexport namespace TenantBeforeCreateEventHandler {\n export type Interface = IEventHandler<DomainEvent<TenantBeforeCreatePayload>>;\n export type Event = DomainEvent<TenantBeforeCreatePayload>;\n}\n\n/** Hook into tenant lifecycle after a tenant is created. */\nexport const TenantAfterCreateEventHandler = createAbstraction<\n IEventHandler<DomainEvent<TenantAfterCreatePayload>>\n>(\"TenantAfterCreateEventHandler\");\n\nexport namespace TenantAfterCreateEventHandler {\n export type Interface = IEventHandler<DomainEvent<TenantAfterCreatePayload>>;\n export type Event = DomainEvent<TenantAfterCreatePayload>;\n}\n"],"names":["CreateTenantUseCase","createAbstraction","CreateTenantRepository","CreateTenantGateway","TenantBeforeCreateEventHandler","TenantAfterCreateEventHandler"],"mappings":";AAwBO,MAAMA,sBAAsBC,kBAAwC;AAepE,MAAMC,yBACTD,kBAA2C;AAcxC,MAAME,sBAAsBF,kBAAwC;AAOpE,MAAMG,iCAAiCH,kBAE5C;AAQK,MAAMI,gCAAgCJ,kBAE3C"}
|
|
@@ -5,7 +5,7 @@ declare class CreateTenantWithWcpIncrementImpl implements CreateTenantUseCase.In
|
|
|
5
5
|
private wcp;
|
|
6
6
|
private decoratee;
|
|
7
7
|
constructor(wcp: WcpContext.Interface, decoratee: CreateTenantUseCase.Interface);
|
|
8
|
-
execute(data: CreateTenantInput): Promise<import("@webiny/feature/api").Result<import("~/types/tenancy.js").Tenant, import("../errors.js").CreateTenantError>>;
|
|
8
|
+
execute(data: CreateTenantInput): Promise<import("@webiny/feature/api").Result<import("~/types/tenancy.js").Tenant, import("../errors.js").CreateTenantError | import("../errors.js").TenantAlreadyExistsError>>;
|
|
9
9
|
}
|
|
10
10
|
export declare const CreateTenantWithWcpIncrement: typeof CreateTenantWithWcpIncrementImpl;
|
|
11
11
|
export {};
|
|
@@ -3,3 +3,9 @@ export declare class CreateTenantError extends BaseError {
|
|
|
3
3
|
readonly code: "CREATE_TENANT";
|
|
4
4
|
constructor(data: any);
|
|
5
5
|
}
|
|
6
|
+
export declare class TenantAlreadyExistsError extends BaseError<{
|
|
7
|
+
id: string;
|
|
8
|
+
}> {
|
|
9
|
+
readonly code: "TENANT_ALREADY_EXISTS";
|
|
10
|
+
constructor(id: string);
|
|
11
|
+
}
|
|
@@ -7,6 +7,16 @@ class CreateTenantError extends BaseError {
|
|
|
7
7
|
}), this.code = "CREATE_TENANT";
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
|
|
10
|
+
class TenantAlreadyExistsError extends BaseError {
|
|
11
|
+
constructor(id){
|
|
12
|
+
super({
|
|
13
|
+
message: `Tenant "${id}" already exists.`,
|
|
14
|
+
data: {
|
|
15
|
+
id
|
|
16
|
+
}
|
|
17
|
+
}), this.code = "TENANT_ALREADY_EXISTS";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export { CreateTenantError, TenantAlreadyExistsError };
|
|
11
21
|
|
|
12
22
|
//# sourceMappingURL=errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/tenancy/CreateTenant/errors.js","sources":["../../../../src/features/tenancy/CreateTenant/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\nexport class CreateTenantError extends BaseError {\n override readonly code = \"CREATE_TENANT\" as const;\n\n constructor(data: any) {\n super({\n message: `Failed to create tenant`,\n data\n });\n }\n}\n"],"names":["CreateTenantError","BaseError","data"],"mappings":";AAEO,MAAMA,0BAA0BC;IAGnC,YAAYC,IAAS,CAAE;QACnB,KAAK,CAAC;YACF,SAAS;YACTA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ"}
|
|
1
|
+
{"version":3,"file":"features/tenancy/CreateTenant/errors.js","sources":["../../../../src/features/tenancy/CreateTenant/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\nexport class CreateTenantError extends BaseError {\n override readonly code = \"CREATE_TENANT\" as const;\n\n constructor(data: any) {\n super({\n message: `Failed to create tenant`,\n data\n });\n }\n}\n\nexport class TenantAlreadyExistsError extends BaseError<{ id: string }> {\n override readonly code = \"TENANT_ALREADY_EXISTS\" as const;\n\n constructor(id: string) {\n super({\n message: `Tenant \"${id}\" already exists.`,\n data: { id }\n });\n }\n}\n"],"names":["CreateTenantError","BaseError","data","TenantAlreadyExistsError","id"],"mappings":";AAEO,MAAMA,0BAA0BC;IAGnC,YAAYC,IAAS,CAAE;QACnB,KAAK,CAAC;YACF,SAAS;YACTA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ;AAEO,MAAMC,iCAAiCF;IAG1C,YAAYG,EAAU,CAAE;QACpB,KAAK,CAAC;YACF,SAAS,CAAC,QAAQ,EAAEA,GAAG,iBAAiB,CAAC;YACzC,MAAM;gBAAEA;YAAG;QACf,SANc,IAAI,GAAG;IAOzB;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.js","sources":["../../../../../src/features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.ts"],"sourcesContent":["import { createDecorator } from \"@webiny/feature/api\";\nimport { DeleteTenantUseCase } from \"../abstractions.js\";\nimport { WcpContext } from \"~/features/wcp/WcpContext/index.js\";\n\nclass DeleteTenantWithWcpDecrementImpl implements DeleteTenantUseCase.Interface {\n constructor(\n private wcp: WcpContext.Interface,\n private decoratee: DeleteTenantUseCase.Interface\n ) {}\n\n async execute(id: string): Promise<boolean> {\n const result = await this.decoratee.execute(id);\n await this.wcp.decrementTenants();\n return result;\n }\n}\n\nexport const DeleteTenantWithWcpDecrement = createDecorator({\n abstraction: DeleteTenantUseCase,\n decorator: DeleteTenantWithWcpDecrementImpl,\n dependencies: [WcpContext]\n});\n"],"names":["DeleteTenantWithWcpDecrementImpl","wcp","decoratee","id","result","DeleteTenantWithWcpDecrement","createDecorator","DeleteTenantUseCase","WcpContext"],"mappings":";;;AAIA,MAAMA;IACF,YACYC,GAAyB,EACzBC,SAAwC,CAClD;aAFUD,GAAG,GAAHA;aACAC,SAAS,GAATA;IACT;IAEH,MAAM,QAAQC,EAAU,EAAoB;QACxC,MAAMC,SAAS,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAACD;QAC5C,MAAM,IAAI,CAAC,GAAG,CAAC,gBAAgB;QAC/B,
|
|
1
|
+
{"version":3,"file":"features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.js","sources":["../../../../../src/features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.ts"],"sourcesContent":["import { createDecorator } from \"@webiny/feature/api\";\nimport { DeleteTenantUseCase } from \"../abstractions.js\";\nimport { WcpContext } from \"~/features/wcp/WcpContext/index.js\";\n\nclass DeleteTenantWithWcpDecrementImpl implements DeleteTenantUseCase.Interface {\n constructor(\n private wcp: WcpContext.Interface,\n private decoratee: DeleteTenantUseCase.Interface\n ) {}\n\n async execute(id: string): Promise<boolean> {\n const result = await this.decoratee.execute(id);\n if (!result) {\n return result;\n }\n await this.wcp.decrementTenants();\n return result;\n }\n}\n\nexport const DeleteTenantWithWcpDecrement = createDecorator({\n abstraction: DeleteTenantUseCase,\n decorator: DeleteTenantWithWcpDecrementImpl,\n dependencies: [WcpContext]\n});\n"],"names":["DeleteTenantWithWcpDecrementImpl","wcp","decoratee","id","result","DeleteTenantWithWcpDecrement","createDecorator","DeleteTenantUseCase","WcpContext"],"mappings":";;;AAIA,MAAMA;IACF,YACYC,GAAyB,EACzBC,SAAwC,CAClD;aAFUD,GAAG,GAAHA;aACAC,SAAS,GAATA;IACT;IAEH,MAAM,QAAQC,EAAU,EAAoB;QACxC,MAAMC,SAAS,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAACD;QAC5C,IAAI,CAACC,QACD,OAAOA;QAEX,MAAM,IAAI,CAAC,GAAG,CAAC,gBAAgB;QAC/B,OAAOA;IACX;AACJ;AAEO,MAAMC,+BAA+BC,gBAAgB;IACxD,aAAaC;IACb,WAAWP;IACX,cAAc;QAACQ;KAAW;AAC9B"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createFeature } from "@webiny/feature/api";
|
|
2
2
|
import { AdminUsersRepository } from "./shared/AdminUsersRepository.js";
|
|
3
3
|
import { GetUserFeature } from "./GetUser/feature.js";
|
|
4
|
+
import { GetCurrentUserFeature } from "./GetCurrentUser/feature.js";
|
|
4
5
|
import { GetIdentityProfileFeature } from "./GetIdentityProfile/feature.js";
|
|
5
6
|
import { ListUsersFeature } from "./ListUsers/feature.js";
|
|
6
7
|
import { CreateUserFeature } from "./CreateUser/feature.js";
|
|
@@ -14,6 +15,7 @@ const AdminUsersFeature = createFeature({
|
|
|
14
15
|
register (container, storageOperations) {
|
|
15
16
|
container.register(AdminUsersRepository).inSingletonScope();
|
|
16
17
|
GetUserFeature.register(container);
|
|
18
|
+
GetCurrentUserFeature.register(container);
|
|
17
19
|
GetIdentityProfileFeature.register(container);
|
|
18
20
|
ListUsersFeature.register(container);
|
|
19
21
|
ListUserTeamsFeature.register(container);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/users/AdminUsersFeature.js","sources":["../../../src/features/users/AdminUsersFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { AdminUsersRepository } from \"./shared/AdminUsersRepository.js\";\nimport { GetUserFeature } from \"./GetUser/feature.js\";\nimport { GetIdentityProfileFeature } from \"./GetIdentityProfile/feature.js\";\nimport { ListUsersFeature } from \"./ListUsers/feature.js\";\nimport { CreateUserFeature } from \"./CreateUser/feature.js\";\nimport { UpdateUserFeature } from \"./UpdateUser/feature.js\";\nimport { DeleteUserFeature } from \"./DeleteUser/feature.js\";\nimport { ListUserTeamsFeature } from \"./ListUserTeams/feature.js\";\nimport { AdminUsersStorageOperations } from \"./shared/storageAbstractions.js\";\nimport { ExternalIdpUserSyncFeature } from \"./ExternalIdpUserSync/index.js\";\n\nexport const AdminUsersFeature = createFeature<AdminUsersStorageOperations.Interface>({\n name: \"AdminUsers\",\n register(container, storageOperations) {\n // Register repository in singleton scope\n container.register(AdminUsersRepository).inSingletonScope();\n\n // Register all use cases\n GetUserFeature.register(container);\n GetIdentityProfileFeature.register(container);\n ListUsersFeature.register(container);\n ListUserTeamsFeature.register(container);\n CreateUserFeature.register(container);\n UpdateUserFeature.register(container);\n DeleteUserFeature.register(container);\n ExternalIdpUserSyncFeature.register(container);\n\n // Legacy storage ops\n container.registerInstance(AdminUsersStorageOperations, storageOperations);\n }\n});\n"],"names":["AdminUsersFeature","createFeature","container","storageOperations","AdminUsersRepository","GetUserFeature","GetIdentityProfileFeature","ListUsersFeature","ListUserTeamsFeature","CreateUserFeature","UpdateUserFeature","DeleteUserFeature","ExternalIdpUserSyncFeature","AdminUsersStorageOperations"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/users/AdminUsersFeature.js","sources":["../../../src/features/users/AdminUsersFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { AdminUsersRepository } from \"./shared/AdminUsersRepository.js\";\nimport { GetUserFeature } from \"./GetUser/feature.js\";\nimport { GetCurrentUserFeature } from \"./GetCurrentUser/feature.js\";\nimport { GetIdentityProfileFeature } from \"./GetIdentityProfile/feature.js\";\nimport { ListUsersFeature } from \"./ListUsers/feature.js\";\nimport { CreateUserFeature } from \"./CreateUser/feature.js\";\nimport { UpdateUserFeature } from \"./UpdateUser/feature.js\";\nimport { DeleteUserFeature } from \"./DeleteUser/feature.js\";\nimport { ListUserTeamsFeature } from \"./ListUserTeams/feature.js\";\nimport { AdminUsersStorageOperations } from \"./shared/storageAbstractions.js\";\nimport { ExternalIdpUserSyncFeature } from \"./ExternalIdpUserSync/index.js\";\n\nexport const AdminUsersFeature = createFeature<AdminUsersStorageOperations.Interface>({\n name: \"AdminUsers\",\n register(container, storageOperations) {\n // Register repository in singleton scope\n container.register(AdminUsersRepository).inSingletonScope();\n\n // Register all use cases\n GetUserFeature.register(container);\n GetCurrentUserFeature.register(container);\n GetIdentityProfileFeature.register(container);\n ListUsersFeature.register(container);\n ListUserTeamsFeature.register(container);\n CreateUserFeature.register(container);\n UpdateUserFeature.register(container);\n DeleteUserFeature.register(container);\n ExternalIdpUserSyncFeature.register(container);\n\n // Legacy storage ops\n container.registerInstance(AdminUsersStorageOperations, storageOperations);\n }\n});\n"],"names":["AdminUsersFeature","createFeature","container","storageOperations","AdminUsersRepository","GetUserFeature","GetCurrentUserFeature","GetIdentityProfileFeature","ListUsersFeature","ListUserTeamsFeature","CreateUserFeature","UpdateUserFeature","DeleteUserFeature","ExternalIdpUserSyncFeature","AdminUsersStorageOperations"],"mappings":";;;;;;;;;;;;AAaO,MAAMA,oBAAoBC,cAAqD;IAClF,MAAM;IACN,UAASC,SAAS,EAAEC,iBAAiB;QAEjCD,UAAU,QAAQ,CAACE,sBAAsB,gBAAgB;QAGzDC,eAAe,QAAQ,CAACH;QACxBI,sBAAsB,QAAQ,CAACJ;QAC/BK,0BAA0B,QAAQ,CAACL;QACnCM,iBAAiB,QAAQ,CAACN;QAC1BO,qBAAqB,QAAQ,CAACP;QAC9BQ,kBAAkB,QAAQ,CAACR;QAC3BS,kBAAkB,QAAQ,CAACT;QAC3BU,kBAAkB,QAAQ,CAACV;QAC3BW,2BAA2B,QAAQ,CAACX;QAGpCA,UAAU,gBAAgB,CAACY,6BAA6BX;IAC5D;AACJ"}
|
|
@@ -30,8 +30,7 @@ class CreateUserUseCaseImpl {
|
|
|
30
30
|
const displayName = this.getDisplayName(data);
|
|
31
31
|
const tenant = this.tenantContext.getTenant().id;
|
|
32
32
|
const identity = this.identityContext.getIdentity();
|
|
33
|
-
|
|
34
|
-
if (identity) createdBy = {
|
|
33
|
+
const createdBy = {
|
|
35
34
|
id: identity.id,
|
|
36
35
|
displayName: identity.displayName,
|
|
37
36
|
type: identity.type
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/users/CreateUser/CreateUserUseCase.js","sources":["../../../../src/features/users/CreateUser/CreateUserUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { TenantContext } from \"~/features/tenancy/TenantContext/index.js\";\nimport { IdentityContext } from \"~/features/security/IdentityContext/index.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateUserUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { AdminUsersRepository } from \"~/features/users/shared/abstractions.js\";\nimport { createUserValidation } from \"./schema.js\";\nimport {\n NotAuthorizedError,\n EmailTakenError,\n UserValidationError\n} from \"~/features/users/shared/errors.js\";\nimport { UserBeforeCreateEvent, UserAfterCreateEvent } from \"./events.js\";\nimport type { AdminUser } from \"~/features/users/shared/types.js\";\nimport type { CreateUserInput } from \"~/features/users/shared/types.js\";\nimport type { CreatedBy } from \"~/types/users.js\";\n\nclass CreateUserUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private tenantContext: TenantContext.Interface,\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: AdminUsersRepository.Interface\n ) {}\n\n async execute(input: CreateUserInput): Promise<Result<AdminUser, UseCaseAbstraction.Error>> {\n // 1. Check permission\n const permission = await this.identityContext.getPermission(\"adminUsers.user\");\n if (!permission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n // 2. Validate input\n const validation = createUserValidation.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\n // 3. Check email uniqueness\n const existingUserResult = await this.repository.get({ email: data.email });\n if (existingUserResult.isOk()) {\n // This means the email is taken!\n return Result.fail(new EmailTakenError(data.email));\n }\n\n if (existingUserResult.error.code !== \"AdminUser/NotFound\") {\n return Result.fail(existingUserResult.error);\n }\n\n // 4. Generate ID if not provided\n const id = data.id || mdbid();\n\n // 5. Generate display name\n const displayName = this.getDisplayName(data);\n\n // 6. Get tenant and identity\n const tenant = this.tenantContext.getTenant().id;\n const identity = this.identityContext.getIdentity();\n\n
|
|
1
|
+
{"version":3,"file":"features/users/CreateUser/CreateUserUseCase.js","sources":["../../../../src/features/users/CreateUser/CreateUserUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { TenantContext } from \"~/features/tenancy/TenantContext/index.js\";\nimport { IdentityContext } from \"~/features/security/IdentityContext/index.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateUserUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { AdminUsersRepository } from \"~/features/users/shared/abstractions.js\";\nimport { createUserValidation } from \"./schema.js\";\nimport {\n NotAuthorizedError,\n EmailTakenError,\n UserValidationError\n} from \"~/features/users/shared/errors.js\";\nimport { UserBeforeCreateEvent, UserAfterCreateEvent } from \"./events.js\";\nimport type { AdminUser } from \"~/features/users/shared/types.js\";\nimport type { CreateUserInput } from \"~/features/users/shared/types.js\";\nimport type { CreatedBy } from \"~/types/users.js\";\n\nclass CreateUserUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private tenantContext: TenantContext.Interface,\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: AdminUsersRepository.Interface\n ) {}\n\n async execute(input: CreateUserInput): Promise<Result<AdminUser, UseCaseAbstraction.Error>> {\n // 1. Check permission\n const permission = await this.identityContext.getPermission(\"adminUsers.user\");\n if (!permission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n // 2. Validate input\n const validation = createUserValidation.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\n // 3. Check email uniqueness\n const existingUserResult = await this.repository.get({ email: data.email });\n if (existingUserResult.isOk()) {\n // This means the email is taken!\n return Result.fail(new EmailTakenError(data.email));\n }\n\n if (existingUserResult.error.code !== \"AdminUser/NotFound\") {\n return Result.fail(existingUserResult.error);\n }\n\n // 4. Generate ID if not provided\n const id = data.id || mdbid();\n\n // 5. Generate display name\n const displayName = this.getDisplayName(data);\n\n // 6. Get tenant and identity\n const tenant = this.tenantContext.getTenant().id;\n const identity = this.identityContext.getIdentity();\n\n const createdBy: CreatedBy = {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n };\n\n // 7. Create user entity\n const user: AdminUser = {\n ...data,\n id,\n email: data.email,\n displayName,\n createdOn: new Date().toISOString(),\n createdBy,\n tenant\n };\n\n // 8. Publish before event\n await this.eventPublisher.publish(new UserBeforeCreateEvent({ user, input: data }));\n\n // 10. Create user via repository\n const result = await this.repository.create(user);\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n // 11. Publish after event\n await this.eventPublisher.publish(\n new UserAfterCreateEvent({ user: result.value, input: data })\n );\n\n return Result.ok(result.value);\n }\n\n private getDisplayName(data: CreateUserInput): string {\n // If display name is not set, try to get it from the first name and last name.\n // If first name and last name are not set, use the e-mail address.\n if (data.displayName) {\n return data.displayName;\n }\n\n if (data.firstName || data.lastName) {\n return `${data.firstName || \"\"} ${data.lastName || \"\"}`.trim();\n }\n\n if (data.email) {\n return data.email;\n }\n\n return \"Missing display name\";\n }\n}\n\nexport const CreateUserUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: CreateUserUseCaseImpl,\n dependencies: [TenantContext, IdentityContext, EventPublisher, AdminUsersRepository]\n});\n"],"names":["CreateUserUseCaseImpl","tenantContext","identityContext","eventPublisher","repository","input","permission","Result","NotAuthorizedError","validation","createUserValidation","UserValidationError","data","existingUserResult","EmailTakenError","id","mdbid","displayName","tenant","identity","createdBy","user","Date","UserBeforeCreateEvent","result","UserAfterCreateEvent","CreateUserUseCase","createImplementation","UseCaseAbstraction","TenantContext","IdentityContext","EventPublisher","AdminUsersRepository"],"mappings":";;;;;;;;;;AAmBA,MAAMA;IACF,YACYC,aAAsC,EACtCC,eAA0C,EAC1CC,cAAwC,EACxCC,UAA0C,CACpD;aAJUH,aAAa,GAAbA;aACAC,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,UAAU,GAAVA;IACT;IAEH,MAAM,QAAQC,KAAsB,EAAwD;QAExF,MAAMC,aAAa,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAC5D,IAAI,CAACA,YACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAI3B,MAAMC,aAAaC,qBAAqB,SAAS,CAACL;QAClD,IAAI,CAACI,WAAW,OAAO,EACnB,OAAOF,OAAO,IAAI,CAAC,IAAII,oBAAoBF,WAAW,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO;QAGjF,MAAMG,OAAOH,WAAW,IAAI;QAG5B,MAAMI,qBAAqB,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,OAAOD,KAAK,KAAK;QAAC;QACzE,IAAIC,mBAAmB,IAAI,IAEvB,OAAON,OAAO,IAAI,CAAC,IAAIO,gBAAgBF,KAAK,KAAK;QAGrD,IAAIC,AAAkC,yBAAlCA,mBAAmB,KAAK,CAAC,IAAI,EAC7B,OAAON,OAAO,IAAI,CAACM,mBAAmB,KAAK;QAI/C,MAAME,KAAKH,KA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
1
|
+
import { Result } from "@webiny/feature/api";
|
|
2
|
+
import { IdentityContext } from "../../../features/security/IdentityContext/index.js";
|
|
3
|
+
import { GetCurrentUserUseCase as UseCaseAbstraction } from "./abstractions.js";
|
|
4
|
+
import { AdminUsersRepository } from "../../../features/users/shared/abstractions.js";
|
|
5
|
+
import type { AdminUser } from "../../../features/users/shared/types.js";
|
|
6
|
+
declare class GetCurrentUserUseCaseImpl implements UseCaseAbstraction.Interface {
|
|
7
|
+
private identityContext;
|
|
8
|
+
private repository;
|
|
9
|
+
constructor(identityContext: IdentityContext.Interface, repository: AdminUsersRepository.Interface);
|
|
10
|
+
execute(): Promise<Result<AdminUser, UseCaseAbstraction.Error>>;
|
|
11
|
+
}
|
|
12
|
+
export declare const GetCurrentUserUseCase: import("@webiny/di").Implementation<typeof GetCurrentUserUseCaseImpl>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Result, createImplementation } from "@webiny/feature/api";
|
|
2
|
+
import { IdentityContext } from "../../security/IdentityContext/index.js";
|
|
3
|
+
import { GetCurrentUserUseCase } from "./abstractions.js";
|
|
4
|
+
import { AdminUsersRepository } from "../shared/abstractions.js";
|
|
5
|
+
import { NotAuthorizedError } from "../shared/errors.js";
|
|
6
|
+
class GetCurrentUserUseCaseImpl {
|
|
7
|
+
constructor(identityContext, repository){
|
|
8
|
+
this.identityContext = identityContext;
|
|
9
|
+
this.repository = repository;
|
|
10
|
+
}
|
|
11
|
+
async execute() {
|
|
12
|
+
const identity = this.identityContext.getIdentity();
|
|
13
|
+
if (identity.isAnonymous() || !identity.isAdmin()) return Result.fail(new NotAuthorizedError());
|
|
14
|
+
return this.repository.get({
|
|
15
|
+
id: identity.id
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const GetCurrentUserUseCase_GetCurrentUserUseCase = createImplementation({
|
|
20
|
+
abstraction: GetCurrentUserUseCase,
|
|
21
|
+
implementation: GetCurrentUserUseCaseImpl,
|
|
22
|
+
dependencies: [
|
|
23
|
+
IdentityContext,
|
|
24
|
+
AdminUsersRepository
|
|
25
|
+
]
|
|
26
|
+
});
|
|
27
|
+
export { GetCurrentUserUseCase_GetCurrentUserUseCase as GetCurrentUserUseCase };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=GetCurrentUserUseCase.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/users/GetCurrentUser/GetCurrentUserUseCase.js","sources":["../../../../src/features/users/GetCurrentUser/GetCurrentUserUseCase.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { IdentityContext } from \"~/features/security/IdentityContext/index.js\";\nimport { GetCurrentUserUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { AdminUsersRepository } from \"~/features/users/shared/abstractions.js\";\nimport { NotAuthorizedError } from \"~/features/users/shared/errors.js\";\nimport type { AdminUser } from \"~/features/users/shared/types.js\";\n\nclass GetCurrentUserUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private repository: AdminUsersRepository.Interface\n ) {}\n\n async execute(): Promise<Result<AdminUser, UseCaseAbstraction.Error>> {\n const identity = this.identityContext.getIdentity();\n if (identity.isAnonymous() || !identity.isAdmin()) {\n return Result.fail(new NotAuthorizedError());\n }\n\n /**\n * An admin may always load their own user record. The `adminUsers.user` permission,\n * which allows loading any user, is not required here.\n */\n return this.repository.get({ id: identity.id });\n }\n}\n\nexport const GetCurrentUserUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: GetCurrentUserUseCaseImpl,\n dependencies: [IdentityContext, AdminUsersRepository]\n});\n"],"names":["GetCurrentUserUseCaseImpl","identityContext","repository","identity","Result","NotAuthorizedError","GetCurrentUserUseCase","createImplementation","UseCaseAbstraction","IdentityContext","AdminUsersRepository"],"mappings":";;;;;AAQA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,UAA0C,CACpD;aAFUD,eAAe,GAAfA;aACAC,UAAU,GAAVA;IACT;IAEH,MAAM,UAAgE;QAClE,MAAMC,WAAW,IAAI,CAAC,eAAe,CAAC,WAAW;QACjD,IAAIA,SAAS,WAAW,MAAM,CAACA,SAAS,OAAO,IAC3C,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAO3B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,IAAIF,SAAS,EAAE;QAAC;IACjD;AACJ;AAEO,MAAMG,8CAAwBC,qBAAqB;IACtD,aAAaC;IACb,gBAAgBR;IAChB,cAAc;QAACS;QAAiBC;KAAqB;AACzD"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Result } from "@webiny/feature/api";
|
|
2
|
+
import type { AdminUser } from "../../../features/users/shared/types.js";
|
|
3
|
+
import { AdminUsersRepository } from "../../../features/users/shared/abstractions.js";
|
|
4
|
+
import { NotAuthorizedError } from "../../../features/users/shared/errors.js";
|
|
5
|
+
export interface IGetCurrentUserErrors {
|
|
6
|
+
notAuthorized: NotAuthorizedError;
|
|
7
|
+
}
|
|
8
|
+
type GetCurrentUserError = IGetCurrentUserErrors[keyof IGetCurrentUserErrors] | AdminUsersRepository.Error;
|
|
9
|
+
export interface IGetCurrentUser {
|
|
10
|
+
execute(): Promise<Result<AdminUser, GetCurrentUserError>>;
|
|
11
|
+
}
|
|
12
|
+
/** Retrieve the admin user of the current identity. */
|
|
13
|
+
export declare const GetCurrentUserUseCase: import("@webiny/di").Abstraction<IGetCurrentUser>;
|
|
14
|
+
export declare namespace GetCurrentUserUseCase {
|
|
15
|
+
type Interface = IGetCurrentUser;
|
|
16
|
+
type Error = GetCurrentUserError;
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/users/GetCurrentUser/abstractions.js","sources":["../../../../src/features/users/GetCurrentUser/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport type { AdminUser } from \"~/features/users/shared/types.js\";\nimport { AdminUsersRepository } from \"~/features/users/shared/abstractions.js\";\nimport { NotAuthorizedError } from \"~/features/users/shared/errors.js\";\n\n// Use case specific errors\nexport interface IGetCurrentUserErrors {\n notAuthorized: NotAuthorizedError;\n}\n\n// Combined error type (use case errors + repository errors)\ntype GetCurrentUserError =\n | IGetCurrentUserErrors[keyof IGetCurrentUserErrors]\n | AdminUsersRepository.Error;\n\n// Use case interface\nexport interface IGetCurrentUser {\n execute(): Promise<Result<AdminUser, GetCurrentUserError>>;\n}\n\n/** Retrieve the admin user of the current identity. */\nexport const GetCurrentUserUseCase = createAbstraction<IGetCurrentUser>(\"GetCurrentUserUseCase\");\n\n// Namespace exports\nexport namespace GetCurrentUserUseCase {\n export type Interface = IGetCurrentUser;\n export type Error = GetCurrentUserError;\n}\n"],"names":["GetCurrentUserUseCase","createAbstraction"],"mappings":";AAsBO,MAAMA,wBAAwBC,kBAAmC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createFeature } from "@webiny/feature/api";
|
|
2
|
+
import { GetCurrentUserUseCase } from "./GetCurrentUserUseCase.js";
|
|
3
|
+
const GetCurrentUserFeature = createFeature({
|
|
4
|
+
name: "GetCurrentUser",
|
|
5
|
+
register (container) {
|
|
6
|
+
container.register(GetCurrentUserUseCase);
|
|
7
|
+
}
|
|
8
|
+
});
|
|
9
|
+
export { GetCurrentUserFeature };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=feature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/users/GetCurrentUser/feature.js","sources":["../../../../src/features/users/GetCurrentUser/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { GetCurrentUserUseCase } from \"./GetCurrentUserUseCase.js\";\n\nexport const GetCurrentUserFeature = createFeature({\n name: \"GetCurrentUser\",\n register(container) {\n container.register(GetCurrentUserUseCase);\n }\n});\n"],"names":["GetCurrentUserFeature","createFeature","container","GetCurrentUserUseCase"],"mappings":";;AAGO,MAAMA,wBAAwBC,cAAc;IAC/C,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;IACvB;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./abstractions.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./abstractions.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ErrorResponse, ListErrorResponse, ListResponse, NotFoundResponse, Response } from "@webiny/handler-graphql/responses.js";
|
|
2
2
|
import { GraphQLSchemaPlugin } from "@webiny/handler-graphql/plugins/GraphQLSchemaPlugin.js";
|
|
3
3
|
import { GetUserUseCase } from "../../features/users/GetUser/index.js";
|
|
4
|
-
import
|
|
4
|
+
import { GetCurrentUserUseCase } from "../../features/users/GetCurrentUser/index.js";
|
|
5
5
|
import { ListUsersUseCase } from "../../features/users/ListUsers/index.js";
|
|
6
6
|
const emptyResolver = ()=>({});
|
|
7
7
|
const createUsersGraphQL = ()=>[
|
|
@@ -97,7 +97,8 @@ const createUsersGraphQL = ()=>[
|
|
|
97
97
|
}
|
|
98
98
|
},
|
|
99
99
|
AdminUsersQuery: {
|
|
100
|
-
getUser: async (_,
|
|
100
|
+
getUser: async (_, args, context)=>{
|
|
101
|
+
const where = args.where ?? {};
|
|
101
102
|
const getUser = context.container.resolve(GetUserUseCase);
|
|
102
103
|
const userResult = await getUser.execute({
|
|
103
104
|
id: where.id,
|
|
@@ -115,22 +116,18 @@ const createUsersGraphQL = ()=>[
|
|
|
115
116
|
return new Response(userResult.value);
|
|
116
117
|
},
|
|
117
118
|
getCurrentUser: async (_, __, context)=>{
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}));
|
|
124
|
-
if (userResponse.isFail()) {
|
|
125
|
-
const error = userResponse.error;
|
|
126
|
-
if ("AdminUser/NotFound" === error.code) return new NotFoundResponse(`User with ID ${identity.id} was not found!`);
|
|
119
|
+
const getCurrentUser = context.container.resolve(GetCurrentUserUseCase);
|
|
120
|
+
const userResult = await getCurrentUser.execute();
|
|
121
|
+
if (userResult.isFail()) {
|
|
122
|
+
const error = userResult.error;
|
|
123
|
+
if ("AdminUser/NotFound" === error.code) return new NotFoundResponse("Current user was not found!");
|
|
127
124
|
return new ErrorResponse({
|
|
128
125
|
message: error.message,
|
|
129
126
|
code: error.code,
|
|
130
127
|
data: error.data
|
|
131
128
|
});
|
|
132
129
|
}
|
|
133
|
-
return new Response(
|
|
130
|
+
return new Response(userResult.value);
|
|
134
131
|
},
|
|
135
132
|
listUsers: async (_, __, context)=>{
|
|
136
133
|
const listUsers = context.container.resolve(ListUsersUseCase);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql/users/user.gql.js","sources":["../../../src/graphql/users/user.gql.ts"],"sourcesContent":["import {\n ErrorResponse,\n ListErrorResponse,\n ListResponse,\n NotFoundResponse,\n Response\n} from \"@webiny/handler-graphql/responses.js\";\nimport { GraphQLSchemaPlugin } from \"@webiny/handler-graphql/plugins/GraphQLSchemaPlugin.js\";\nimport type { ApiCoreContext } from \"~/types/core.js\";\nimport { AdminUser } from \"~/types/users.js\";\nimport { GetUserUseCase } from \"~/features/users/GetUser/index.js\";\nimport NotAuthorizedResponse from \"~/graphql/security/NotAuthorizedResponse.js\";\nimport { ListUsersUseCase } from \"~/features/users/ListUsers/index.js\";\n\nconst emptyResolver = () => ({});\n\nexport const createUsersGraphQL = () => {\n return [\n new GraphQLSchemaPlugin<ApiCoreContext>({\n typeDefs: /* GraphQL */ `\n type AdminUsersQuery {\n _empty: String\n }\n\n type AdminUsersMutation {\n _empty: String\n }\n\n extend type Query {\n adminUsers: AdminUsersQuery\n }\n\n extend type Mutation {\n adminUsers: AdminUsersMutation\n }\n\n type AdminUsersCreatedBy {\n id: ID\n displayName: String\n }\n\n type AdminUsersError {\n code: String\n message: String\n data: JSON\n stack: String\n }\n\n type AdminUsersBooleanResponse {\n data: Boolean\n error: AdminUsersError\n }\n `,\n resolvers: {\n Query: {\n adminUsers: emptyResolver\n },\n Mutation: {\n adminUsers: emptyResolver\n }\n }\n }),\n new GraphQLSchemaPlugin<ApiCoreContext>({\n typeDefs: /* GraphQL */ `\n type AdminUser {\n id: ID!\n displayName: String!\n email: String!\n\n roles: [SecurityRole]\n firstName: String\n lastName: String\n avatar: JSON\n external: Boolean\n createdOn: DateTime\n }\n\n type AdminUsersResponse {\n data: AdminUser\n error: AdminUsersError\n }\n\n type AdminUsersListResponse {\n data: [AdminUser]\n error: AdminUsersError\n }\n\n input AdminUsersGetUserWhereInput {\n id: ID\n email: String\n }\n\n extend type AdminUsersQuery {\n getUser(where: AdminUsersGetUserWhereInput): AdminUsersResponse\n getCurrentUser: AdminUsersResponse\n listUsers: AdminUsersListResponse\n }\n `,\n resolvers: {\n AdminUser: {\n roles(user: AdminUser, _, context) {\n if (!user.roles) {\n return null;\n }\n\n return context.security.listRoles({ where: { id_in: user.roles } });\n }\n },\n AdminUsersQuery: {\n getUser: async (_, { where }: any, context) => {\n const getUser = context.container.resolve(GetUserUseCase);\n\n const userResult = await getUser.execute({\n id: where.id,\n email: where.email\n });\n\n if (userResult.isFail()) {\n const error = userResult.error;\n if (error.code === \"AdminUser/NotFound\") {\n return new NotFoundResponse(\n `User \"${JSON.stringify(where)}\" was not found!`\n );\n }\n\n return new ErrorResponse({\n message: error.message,\n code: error.code,\n data: error.data\n });\n }\n\n return new Response(userResult.value);\n },\n getCurrentUser: async (_, __, context) => {\n const identity = context.security.getIdentity();\n\n if (!identity.isAdmin()) {\n throw new NotAuthorizedResponse();\n }\n\n // Current user might not have permissions to execute `getUser` (this method can load any user in the system),\n // but loading your own user record should be allowed. For that reason, let's temporarily disable authorization.\n\n const getUser = context.container.resolve(GetUserUseCase);\n\n const userResponse = await context.security.withoutAuthorization(\n async () => {\n // Get user record using the identity ID.\n return await getUser.execute({ id: identity.id });\n }\n );\n\n if (userResponse.isFail()) {\n const error = userResponse.error;\n if (error.code === \"AdminUser/NotFound\") {\n return new NotFoundResponse(\n `User with ID ${identity.id} was not found!`\n );\n }\n\n return new ErrorResponse({\n message: error.message,\n code: error.code,\n data: error.data\n });\n }\n\n return new Response(userResponse.value);\n },\n listUsers: async (_, __, context) => {\n const listUsers = context.container.resolve(ListUsersUseCase);\n const users = await listUsers.execute();\n\n if (users.isFail()) {\n return new ListErrorResponse(users.error);\n }\n\n return new ListResponse(users.value);\n }\n }\n }\n }),\n new GraphQLSchemaPlugin<ApiCoreContext>({\n typeDefs: /* GraphQL */ `\n extend type AdminUser {\n teams: [SecurityTeam]\n }\n `,\n resolvers: {\n AdminUser: {\n teams(user: AdminUser, _, context) {\n const hasTeams = Array.isArray(user.teams) && user.teams.length > 0;\n if (!hasTeams) {\n return [];\n }\n\n return context.security.listTeams({ where: { id_in: user.teams } });\n }\n }\n }\n })\n ].filter(Boolean);\n};\n"],"names":["emptyResolver","createUsersGraphQL","GraphQLSchemaPlugin","user","_","context","where","getUser","GetUserUseCase","userResult","error","NotFoundResponse","JSON","ErrorResponse","Response","__","identity","NotAuthorizedResponse","userResponse","listUsers","ListUsersUseCase","users","ListErrorResponse","ListResponse","hasTeams","Array","Boolean"],"mappings":";;;;;AAcA,MAAMA,gBAAgB,IAAO,EAAC;AAEvB,MAAMC,qBAAqB,IACvB;QACH,IAAIC,oBAAoC;YACpC,UAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAiCzB,CAAC;YACD,WAAW;gBACP,OAAO;oBACH,YAAYF;gBAChB;gBACA,UAAU;oBACN,YAAYA;gBAChB;YACJ;QACJ;QACA,IAAIE,oBAAoC;YACpC,UAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAkCzB,CAAC;YACD,WAAW;gBACP,WAAW;oBACP,OAAMC,IAAe,EAAEC,CAAC,EAAEC,OAAO;wBAC7B,I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4BAIpD,OAAO,IAAIH,cAAc;gCACrB,SAASH,MAAM,OAAO;gCACtB,MAAMA,MAAM,IAAI;gCAChB,MAAMA,MAAM,IAAI;4BACpB;wBACJ;wBAEA,OAAO,IAAII,SAASI,aAAa,KAAK;oBAC1C;oBACA,WAAW,OAAOd,GAAGW,IAAIV;wBACrB,MAAMc,YAAYd,QAAQ,SAAS,CAAC,OAAO,CAACe;wBAC5C,MAAMC,QAAQ,MAAMF,UAAU,OAAO;wBAErC,IAAIE,MAAM,MAAM,IACZ,OAAO,IAAIC,kBAAkBD,MAAM,KAAK;wBAG5C,OAAO,IAAIE,aAAaF,MAAM,KAAK;oBACvC;gBACJ;YACJ;QACJ;QACA,IAAInB,oBAAoC;YACpC,UAAwB,CAAC;;;;YAIzB,CAAC;YACD,WAAW;gBACP,WAAW;oBACP,OAAMC,IAAe,EAAEC,CAAC,EAAEC,OAAO;wBAC7B,MAAMmB,WAAWC,MAAM,OAAO,CAACtB,KAAK,KAAK,KAAKA,KAAK,KAAK,CAAC,MAAM,GAAG;wBAClE,IAAI,CAACqB,UACD,OAAO,EAAE;wBAGb,OAAOnB,QAAQ,QAAQ,CAAC,SAAS,CAAC;4BAAE,OAAO;gCAAE,OAAOF,KAAK,KAAK;4BAAC;wBAAE;oBACrE;gBACJ;YACJ;QACJ;KACH,CAAC,MAAM,CAACuB"}
|
|
1
|
+
{"version":3,"file":"graphql/users/user.gql.js","sources":["../../../src/graphql/users/user.gql.ts"],"sourcesContent":["import {\n ErrorResponse,\n ListErrorResponse,\n ListResponse,\n NotFoundResponse,\n Response\n} from \"@webiny/handler-graphql/responses.js\";\nimport { GraphQLSchemaPlugin } from \"@webiny/handler-graphql/plugins/GraphQLSchemaPlugin.js\";\nimport type { ApiCoreContext } from \"~/types/core.js\";\nimport { AdminUser } from \"~/types/users.js\";\nimport { GetUserUseCase } from \"~/features/users/GetUser/index.js\";\nimport { GetCurrentUserUseCase } from \"~/features/users/GetCurrentUser/index.js\";\nimport { ListUsersUseCase } from \"~/features/users/ListUsers/index.js\";\n\nconst emptyResolver = () => ({});\n\nexport const createUsersGraphQL = () => {\n return [\n new GraphQLSchemaPlugin<ApiCoreContext>({\n typeDefs: /* GraphQL */ `\n type AdminUsersQuery {\n _empty: String\n }\n\n type AdminUsersMutation {\n _empty: String\n }\n\n extend type Query {\n adminUsers: AdminUsersQuery\n }\n\n extend type Mutation {\n adminUsers: AdminUsersMutation\n }\n\n type AdminUsersCreatedBy {\n id: ID\n displayName: String\n }\n\n type AdminUsersError {\n code: String\n message: String\n data: JSON\n stack: String\n }\n\n type AdminUsersBooleanResponse {\n data: Boolean\n error: AdminUsersError\n }\n `,\n resolvers: {\n Query: {\n adminUsers: emptyResolver\n },\n Mutation: {\n adminUsers: emptyResolver\n }\n }\n }),\n new GraphQLSchemaPlugin<ApiCoreContext>({\n typeDefs: /* GraphQL */ `\n type AdminUser {\n id: ID!\n displayName: String!\n email: String!\n\n roles: [SecurityRole]\n firstName: String\n lastName: String\n avatar: JSON\n external: Boolean\n createdOn: DateTime\n }\n\n type AdminUsersResponse {\n data: AdminUser\n error: AdminUsersError\n }\n\n type AdminUsersListResponse {\n data: [AdminUser]\n error: AdminUsersError\n }\n\n input AdminUsersGetUserWhereInput {\n id: ID\n email: String\n }\n\n extend type AdminUsersQuery {\n getUser(where: AdminUsersGetUserWhereInput): AdminUsersResponse\n getCurrentUser: AdminUsersResponse\n listUsers: AdminUsersListResponse\n }\n `,\n resolvers: {\n AdminUser: {\n roles(user: AdminUser, _, context) {\n if (!user.roles) {\n return null;\n }\n\n return context.security.listRoles({ where: { id_in: user.roles } });\n }\n },\n AdminUsersQuery: {\n getUser: async (_, args: any, context) => {\n // `where` is optional in the schema.\n const where = args.where ?? {};\n const getUser = context.container.resolve(GetUserUseCase);\n\n const userResult = await getUser.execute({\n id: where.id,\n email: where.email\n });\n\n if (userResult.isFail()) {\n const error = userResult.error;\n if (error.code === \"AdminUser/NotFound\") {\n return new NotFoundResponse(\n `User \"${JSON.stringify(where)}\" was not found!`\n );\n }\n\n return new ErrorResponse({\n message: error.message,\n code: error.code,\n data: error.data\n });\n }\n\n return new Response(userResult.value);\n },\n getCurrentUser: async (_, __, context) => {\n const getCurrentUser = context.container.resolve(GetCurrentUserUseCase);\n\n const userResult = await getCurrentUser.execute();\n\n if (userResult.isFail()) {\n const error = userResult.error;\n if (error.code === \"AdminUser/NotFound\") {\n return new NotFoundResponse(\"Current user was not found!\");\n }\n\n return new ErrorResponse({\n message: error.message,\n code: error.code,\n data: error.data\n });\n }\n\n return new Response(userResult.value);\n },\n listUsers: async (_, __, context) => {\n const listUsers = context.container.resolve(ListUsersUseCase);\n const users = await listUsers.execute();\n\n if (users.isFail()) {\n return new ListErrorResponse(users.error);\n }\n\n return new ListResponse(users.value);\n }\n }\n }\n }),\n new GraphQLSchemaPlugin<ApiCoreContext>({\n typeDefs: /* GraphQL */ `\n extend type AdminUser {\n teams: [SecurityTeam]\n }\n `,\n resolvers: {\n AdminUser: {\n teams(user: AdminUser, _, context) {\n const hasTeams = Array.isArray(user.teams) && user.teams.length > 0;\n if (!hasTeams) {\n return [];\n }\n\n return context.security.listTeams({ where: { id_in: user.teams } });\n }\n }\n }\n })\n ].filter(Boolean);\n};\n"],"names":["emptyResolver","createUsersGraphQL","GraphQLSchemaPlugin","user","_","context","args","where","getUser","GetUserUseCase","userResult","error","NotFoundResponse","JSON","ErrorResponse","Response","__","getCurrentUser","GetCurrentUserUseCase","listUsers","ListUsersUseCase","users","ListErrorResponse","ListResponse","hasTeams","Array","Boolean"],"mappings":";;;;;AAcA,MAAMA,gBAAgB,IAAO,EAAC;AAEvB,MAAMC,qBAAqB,IACvB;QACH,IAAIC,oBAAoC;YACpC,UAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAiCzB,CAAC;YACD,WAAW;gBACP,OAAO;oBACH,YAAYF;gBAChB;gBACA,UAAU;oBACN,YAAYA;gBAChB;YACJ;QACJ;QACA,IAAIE,oBAAoC;YACp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tB,MAAMA,MAAM,IAAI;gCAChB,MAAMA,MAAM,IAAI;4BACpB;wBACJ;wBAEA,OAAO,IAAII,SAASL,WAAW,KAAK;oBACxC;oBACA,WAAW,OAAON,GAAGY,IAAIX;wBACrB,MAAMc,YAAYd,QAAQ,SAAS,CAAC,OAAO,CAACe;wBAC5C,MAAMC,QAAQ,MAAMF,UAAU,OAAO;wBAErC,IAAIE,MAAM,MAAM,IACZ,OAAO,IAAIC,kBAAkBD,MAAM,KAAK;wBAG5C,OAAO,IAAIE,aAAaF,MAAM,KAAK;oBACvC;gBACJ;YACJ;QACJ;QACA,IAAInB,oBAAoC;YACpC,UAAwB,CAAC;;;;YAIzB,CAAC;YACD,WAAW;gBACP,WAAW;oBACP,OAAMC,IAAe,EAAEC,CAAC,EAAEC,OAAO;wBAC7B,MAAMmB,WAAWC,MAAM,OAAO,CAACtB,KAAK,KAAK,KAAKA,KAAK,KAAK,CAAC,MAAM,GAAG;wBAClE,IAAI,CAACqB,UACD,OAAO,EAAE;wBAGb,OAAOnB,QAAQ,QAAQ,CAAC,SAAS,CAAC;4BAAE,OAAO;gCAAE,OAAOF,KAAK,KAAK;4BAAC;wBAAE;oBACrE;gBACJ;YACJ;QACJ;KACH,CAAC,MAAM,CAACuB"}
|
|
@@ -13,7 +13,7 @@ export declare class LegacyContext {
|
|
|
13
13
|
addAuthenticator(authenticator: Authenticator.Interface["authenticate"]): void;
|
|
14
14
|
authenticate(token: string): Promise<void>;
|
|
15
15
|
getIdentity(): SecurityIdentity;
|
|
16
|
-
setIdentity(identity: SecurityIdentity): void;
|
|
16
|
+
setIdentity(identity: SecurityIdentity | undefined | null): void;
|
|
17
17
|
getToken(): string | undefined;
|
|
18
18
|
isAuthorizationEnabled(): boolean;
|
|
19
19
|
withoutAuthorization<T = any>(cb: () => Promise<T>): Promise<T>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legacy/security/LegacyContext.js","sources":["../../../src/legacy/security/LegacyContext.ts"],"sourcesContent":["import { type Container } from \"@webiny/di\";\nimport type { SecurityIdentity, SecurityPermission } from \"~/types/security.js\";\nimport { AuthenticationContext } from \"~/features/security/authentication/AuthenticationContext/index.js\";\nimport { Authenticator } from \"~/features/security/authentication/Authenticator/index.js\";\nimport { Authorizer } from \"~/features/security/authorization/Authorizer/abstractions.js\";\nimport {\n AuthenticatedIdentity,\n IdentityContext,\n IdentityData\n} from \"~/features/security/IdentityContext/index.js\";\nimport { GetRoleUseCase } from \"~/features/security/roles/GetRole/index.js\";\nimport { ListRolesUseCase } from \"~/features/security/roles/ListRoles/index.js\";\nimport { CreateRoleUseCase } from \"~/features/security/roles/CreateRole/index.js\";\nimport { UpdateRoleUseCase } from \"~/features/security/roles/UpdateRole/index.js\";\nimport { DeleteRoleUseCase } from \"~/features/security/roles/DeleteRole/index.js\";\nimport { GetTeamUseCase } from \"~/features/security/teams/GetTeam/index.js\";\nimport { ListTeamsUseCase } from \"~/features/security/teams/ListTeams/index.js\";\nimport { CreateTeam } from \"~/features/security/teams/CreateTeam/index.js\";\nimport { UpdateTeam } from \"~/features/security/teams/UpdateTeam/index.js\";\nimport { DeleteTeam } from \"~/features/security/teams/DeleteTeam/index.js\";\n\n/**\n * Legacy bridge that implements the old Security interface.\n * As we implement each phase, we'll replace forwarding with delegation.\n */\nexport class LegacyContext {\n constructor(private container: Container) {}\n\n private get identityContext() {\n return this.container.resolve(IdentityContext);\n }\n\n private get authenticationContext() {\n return this.container.resolve(AuthenticationContext);\n }\n\n addAuthenticator(authenticator: Authenticator.Interface[\"authenticate\"]): void {\n this.container.registerFactory(Authenticator, () => {\n return {\n authenticate(token: string): Promise<IdentityData | null> {\n return authenticator(token);\n }\n };\n });\n }\n\n async authenticate(token: string): Promise<void> {\n // Authenticate using new context\n const identity = await this.authenticationContext.authenticate(token);\n\n // Set identity in IdentityContext\n this.identityContext.setIdentity(identity);\n }\n\n getIdentity(): SecurityIdentity {\n const identity = this.identityContext.getIdentity();\n\n // Convert our Identity class to old SecurityIdentity format\n if (identity.isAnonymous()) {\n return undefined as any;\n }\n\n return identity;\n }\n\n setIdentity(identity: SecurityIdentity): void {\n if (!identity) {\n this.identityContext.setIdentity(undefined);\n return;\n }\n\n // Wrap old identity format in AuthenticatedIdentity\n const { id, displayName, type, ...rest } = identity;\n const authenticatedIdentity = new AuthenticatedIdentity({\n id,\n displayName,\n type,\n ...rest\n });\n\n this.identityContext.setIdentity(authenticatedIdentity);\n }\n\n getToken() {\n return this.authenticationContext.getAuthToken();\n }\n\n isAuthorizationEnabled(): boolean {\n return this.identityContext.isAuthorizationEnabled();\n }\n\n withoutAuthorization<T = any>(cb: () => Promise<T>): Promise<T> {\n return this.identityContext.withoutAuthorization(cb);\n }\n\n withIdentity<T = any>(\n identity: SecurityIdentity | undefined,\n cb: () => Promise<T>\n ): Promise<T> {\n if (!identity) {\n return this.identityContext.withIdentity(undefined, cb);\n }\n\n const { id, displayName, type, ...rest } = identity;\n const authenticatedIdentity = new AuthenticatedIdentity({\n id,\n displayName,\n type,\n ...rest\n });\n\n return this.identityContext.withIdentity(authenticatedIdentity, cb);\n }\n\n async getPermission<TPermission extends SecurityPermission = SecurityPermission>(\n permission: string\n ) {\n return this.identityContext.getPermission<TPermission>(permission);\n }\n\n async getPermissions<TPermission extends SecurityPermission = SecurityPermission>(\n permission: string\n ) {\n return this.identityContext.getPermissions<TPermission>(permission);\n }\n\n async listPermissions() {\n return this.identityContext.listPermissions();\n }\n\n async hasFullAccess(): Promise<boolean> {\n return this.identityContext.hasFullAccess();\n }\n\n async getRole(params: any) {\n const useCase = this.container.resolve(GetRoleUseCase);\n const result = await useCase.execute(params.where);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async listRoles(params?: any) {\n const useCase = this.container.resolve(ListRolesUseCase);\n const result = await useCase.execute(params);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async createRole(input: any) {\n const useCase = this.container.resolve(CreateRoleUseCase);\n const result = await useCase.execute(input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async updateRole(id: string, input: any) {\n const useCase = this.container.resolve(UpdateRoleUseCase);\n const result = await useCase.execute(id, input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async deleteRole(id: string) {\n const useCase = this.container.resolve(DeleteRoleUseCase);\n const result = await useCase.execute(id);\n\n if (result.isFail()) {\n throw result.error;\n }\n }\n\n addAuthorizer(authorizer: any) {\n // @ts-expect-error\n this.container.registerFactory(Authorizer, () => {\n return {\n authorize(): Promise<Permissions[]> {\n return authorizer();\n }\n };\n });\n }\n\n async getTeam(params: any) {\n const useCase = this.container.resolve(GetTeamUseCase);\n const result = await useCase.execute(params.where);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async listTeams(params?: any) {\n const useCase = this.container.resolve(ListTeamsUseCase);\n const result = await useCase.execute(params);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async createTeam(input: any) {\n const useCase = this.container.resolve(CreateTeam);\n const result = await useCase.execute(input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async updateTeam(id: string, input: any) {\n const useCase = this.container.resolve(UpdateTeam);\n const result = await useCase.execute(id, input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async deleteTeam(id: string) {\n const useCase = this.container.resolve(DeleteTeam);\n const result = await useCase.execute(id);\n\n if (result.isFail()) {\n throw result.error;\n }\n }\n}\n"],"names":["LegacyContext","container","IdentityContext","AuthenticationContext","authenticator","Authenticator","token","identity","undefined","id","displayName","type","rest","authenticatedIdentity","AuthenticatedIdentity","cb","permission","params","useCase","GetRoleUseCase","result","ListRolesUseCase","input","CreateRoleUseCase","UpdateRoleUseCase","DeleteRoleUseCase","authorizer","Authorizer","GetTeamUseCase","ListTeamsUseCase","CreateTeam","UpdateTeam","DeleteTeam"],"mappings":";;;;;;;;;;;;;;AAyBO,MAAMA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AAU,IAAI,CAAC,SAAS,CAAC,OAAO,CAACa;QACvC,MAAMX,SAAS,MAAMF,QAAQ,OAAO,CAACT,IAAIa;QAEzC,IAAIF,OAAO,MAAM,IACb,MAAMA,OAAO,KAAK;QAGtB,OAAOA,OAAO,KAAK;IACvB;IAEA,MAAM,WAAWX,EAAU,EAAE;QACzB,MAAMS,UAAU,IAAI,CAAC,SAAS,CAAC,OAAO,CAACc;QACvC,MAAMZ,SAAS,MAAMF,QAAQ,OAAO,CAACT;QAErC,IAAIW,OAAO,MAAM,IACb,MAAMA,OAAO,KAAK;IAE1B;AACJ"}
|
|
1
|
+
{"version":3,"file":"legacy/security/LegacyContext.js","sources":["../../../src/legacy/security/LegacyContext.ts"],"sourcesContent":["import { type Container } from \"@webiny/di\";\nimport type { SecurityIdentity, SecurityPermission } from \"~/types/security.js\";\nimport { AuthenticationContext } from \"~/features/security/authentication/AuthenticationContext/index.js\";\nimport { Authenticator } from \"~/features/security/authentication/Authenticator/index.js\";\nimport { Authorizer } from \"~/features/security/authorization/Authorizer/abstractions.js\";\nimport {\n AuthenticatedIdentity,\n IdentityContext,\n IdentityData\n} from \"~/features/security/IdentityContext/index.js\";\nimport { GetRoleUseCase } from \"~/features/security/roles/GetRole/index.js\";\nimport { ListRolesUseCase } from \"~/features/security/roles/ListRoles/index.js\";\nimport { CreateRoleUseCase } from \"~/features/security/roles/CreateRole/index.js\";\nimport { UpdateRoleUseCase } from \"~/features/security/roles/UpdateRole/index.js\";\nimport { DeleteRoleUseCase } from \"~/features/security/roles/DeleteRole/index.js\";\nimport { GetTeamUseCase } from \"~/features/security/teams/GetTeam/index.js\";\nimport { ListTeamsUseCase } from \"~/features/security/teams/ListTeams/index.js\";\nimport { CreateTeam } from \"~/features/security/teams/CreateTeam/index.js\";\nimport { UpdateTeam } from \"~/features/security/teams/UpdateTeam/index.js\";\nimport { DeleteTeam } from \"~/features/security/teams/DeleteTeam/index.js\";\n\n/**\n * Legacy bridge that implements the old Security interface.\n * As we implement each phase, we'll replace forwarding with delegation.\n */\nexport class LegacyContext {\n constructor(private container: Container) {}\n\n private get identityContext() {\n return this.container.resolve(IdentityContext);\n }\n\n private get authenticationContext() {\n return this.container.resolve(AuthenticationContext);\n }\n\n addAuthenticator(authenticator: Authenticator.Interface[\"authenticate\"]): void {\n this.container.registerFactory(Authenticator, () => {\n return {\n authenticate(token: string): Promise<IdentityData | null> {\n return authenticator(token);\n }\n };\n });\n }\n\n async authenticate(token: string): Promise<void> {\n // Authenticate using new context\n const identity = await this.authenticationContext.authenticate(token);\n\n // Set identity in IdentityContext\n this.identityContext.setIdentity(identity);\n }\n\n getIdentity(): SecurityIdentity {\n const identity = this.identityContext.getIdentity();\n\n // Convert our Identity class to old SecurityIdentity format\n if (identity.isAnonymous()) {\n return undefined as any;\n }\n\n return identity;\n }\n\n setIdentity(identity: SecurityIdentity | undefined | null): void {\n if (!identity) {\n this.identityContext.setIdentity(undefined);\n return;\n }\n\n // Wrap old identity format in AuthenticatedIdentity\n const { id, displayName, type, ...rest } = identity;\n const authenticatedIdentity = new AuthenticatedIdentity({\n id,\n displayName,\n type,\n ...rest\n });\n\n this.identityContext.setIdentity(authenticatedIdentity);\n }\n\n getToken() {\n return this.authenticationContext.getAuthToken();\n }\n\n isAuthorizationEnabled(): boolean {\n return this.identityContext.isAuthorizationEnabled();\n }\n\n withoutAuthorization<T = any>(cb: () => Promise<T>): Promise<T> {\n return this.identityContext.withoutAuthorization(cb);\n }\n\n withIdentity<T = any>(\n identity: SecurityIdentity | undefined,\n cb: () => Promise<T>\n ): Promise<T> {\n if (!identity) {\n return this.identityContext.withIdentity(undefined, cb);\n }\n\n const { id, displayName, type, ...rest } = identity;\n const authenticatedIdentity = new AuthenticatedIdentity({\n id,\n displayName,\n type,\n ...rest\n });\n\n return this.identityContext.withIdentity(authenticatedIdentity, cb);\n }\n\n async getPermission<TPermission extends SecurityPermission = SecurityPermission>(\n permission: string\n ) {\n return this.identityContext.getPermission<TPermission>(permission);\n }\n\n async getPermissions<TPermission extends SecurityPermission = SecurityPermission>(\n permission: string\n ) {\n return this.identityContext.getPermissions<TPermission>(permission);\n }\n\n async listPermissions() {\n return this.identityContext.listPermissions();\n }\n\n async hasFullAccess(): Promise<boolean> {\n return this.identityContext.hasFullAccess();\n }\n\n async getRole(params: any) {\n const useCase = this.container.resolve(GetRoleUseCase);\n const result = await useCase.execute(params.where);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async listRoles(params?: any) {\n const useCase = this.container.resolve(ListRolesUseCase);\n const result = await useCase.execute(params);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async createRole(input: any) {\n const useCase = this.container.resolve(CreateRoleUseCase);\n const result = await useCase.execute(input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async updateRole(id: string, input: any) {\n const useCase = this.container.resolve(UpdateRoleUseCase);\n const result = await useCase.execute(id, input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async deleteRole(id: string) {\n const useCase = this.container.resolve(DeleteRoleUseCase);\n const result = await useCase.execute(id);\n\n if (result.isFail()) {\n throw result.error;\n }\n }\n\n addAuthorizer(authorizer: any) {\n // @ts-expect-error\n this.container.registerFactory(Authorizer, () => {\n return {\n authorize(): Promise<Permissions[]> {\n return authorizer();\n }\n };\n });\n }\n\n async getTeam(params: any) {\n const useCase = this.container.resolve(GetTeamUseCase);\n const result = await useCase.execute(params.where);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async listTeams(params?: any) {\n const useCase = this.container.resolve(ListTeamsUseCase);\n const result = await useCase.execute(params);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async createTeam(input: any) {\n const useCase = this.container.resolve(CreateTeam);\n const result = await useCase.execute(input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async updateTeam(id: string, input: any) {\n const useCase = this.container.resolve(UpdateTeam);\n const result = await useCase.execute(id, input);\n\n if (result.isFail()) {\n throw result.error;\n }\n\n return result.value;\n }\n\n async deleteTeam(id: string) {\n const useCase = this.container.resolve(DeleteTeam);\n const result = await useCase.execute(id);\n\n if (result.isFail()) {\n throw result.error;\n }\n }\n}\n"],"names":["LegacyContext","container","IdentityContext","AuthenticationContext","authenticator","Authenticator","token","identity","undefined","id","displayName","type","rest","authenticatedIdentity","AuthenticatedIdentity","cb","permission","params","useCase","GetRoleUseCase","result","ListRolesUseCase","input","CreateRoleUseCase","UpdateRoleUseCase","DeleteRoleUseCase","authorizer","Authorizer","GetTeamUseCase","ListTeamsUseCase","CreateTeam","UpdateTeam","DeleteTeam"],"mappings":";;;;;;;;;;;;;;AAyBO,MAAMA;IACT,YAAoBC,SAAoB,CAAE;aAAtBA,SAAS,GAATA;IAAuB;IAE3C,IAAY,kBAAkB;QAC1B,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAACC;IAClC;IAEA,IAAY,wBAAwB;QAChC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAACC;IAClC;IAEA,iBAAiBC,aAAsD,EAAQ;QAC3E,IAAI,CAAC,SAAS,CAAC,eAAe,CAACC,eAAe,IACnC;gBACH,cAAaC,KAAa;oBACtB,OAAOF,cAAcE;gBACzB;YACJ;IAER;IAEA,MAAM,aAAaA,KAAa,EAAiB;QAE7C,MAAMC,WAAW,MAAM,IAAI,CAAC,qBAAqB,CAAC,YAAY,CAACD;QAG/D,IAAI,CAAC,eAAe,CAAC,WAAW,CAACC;IACrC;IAEA,cAAgC;QAC5B,MAAMA,WAAW,IAAI,CAAC,eAAe,CAAC,WAAW;QAGjD,IAAIA,SAAS,WAAW,IACpB;QAGJ,OAAOA;IACX;IAEA,YAAYA,QAA6C,EAAQ;QAC7D,IAAI,CAACA,UAAU,YACX,IAAI,CAAC,eAAe,CAAC,WAAW,CAACC;QAKrC,MAAM,EAAEC,EAAE,EAAEC,WAAW,EAAEC,IAAI,EAAE,GAAGC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QAC1B,MAAMC,UAAU,IAAI,CAAC,SAAS,CAAC,OAAO,CAACW;QACvC,MAAMT,SAAS,MAAMF,QAAQ,OAAO,CAACD;QAErC,IAAIG,OAAO,MAAM,IACb,MAAMA,OAAO,KAAK;QAGtB,OAAOA,OAAO,KAAK;IACvB;IAEA,MAAM,WAAWE,KAAU,EAAE;QACzB,MAAMJ,UAAU,IAAI,CAAC,SAAS,CAAC,OAAO,CAACY;QACvC,MAAMV,SAAS,MAAMF,QAAQ,OAAO,CAACI;QAErC,IAAIF,OAAO,MAAM,IACb,MAAMA,OAAO,KAAK;QAGtB,OAAOA,OAAO,KAAK;IACvB;IAEA,MAAM,WAAWX,EAAU,EAAEa,KAAU,EAAE;QACrC,MAAMJ,UAAU,IAAI,CAAC,SAAS,CAAC,OAAO,CAACa;QACvC,MAAMX,SAAS,MAAMF,QAAQ,OAAO,CAACT,IAAIa;QAEzC,IAAIF,OAAO,MAAM,IACb,MAAMA,OAAO,KAAK;QAGtB,OAAOA,OAAO,KAAK;IACvB;IAEA,MAAM,WAAWX,EAAU,EAAE;QACzB,MAAMS,UAAU,IAAI,CAAC,SAAS,CAAC,OAAO,CAACc;QACvC,MAAMZ,SAAS,MAAMF,QAAQ,OAAO,CAACT;QAErC,IAAIW,OAAO,MAAM,IACb,MAAMA,OAAO,KAAK;IAE1B;AACJ"}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
+
import { Request } from "@webiny/handler";
|
|
1
2
|
import type { ApiCoreContext } from "../../../types/core.js";
|
|
3
|
+
/**
|
|
4
|
+
* The `wby-id-token` cookie exists only for private file delivery: an `<img src>` cannot send an
|
|
5
|
+
* `Authorization` header. It must not log users in anywhere else, because the browser attaches it
|
|
6
|
+
* to cross-site requests too (`SameSite=None`), which would let any website call the API as the user.
|
|
7
|
+
*/
|
|
8
|
+
export declare const isCookieAuthenticationAllowed: (request: Pick<Request.Interface, "method" | "url">) => boolean;
|
|
2
9
|
/**
|
|
3
10
|
* @internal
|
|
4
11
|
*/
|
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import { createContextPlugin } from "@webiny/api";
|
|
2
2
|
import { Request, createBeforeHandlerPlugin } from "@webiny/handler";
|
|
3
3
|
import { SetIdTokenCookie } from "../../../features/security/authentication/AuthenticationContext/SetIdTokenCookie.js";
|
|
4
|
+
const isCookieAuthenticationAllowed = (request)=>{
|
|
5
|
+
const method = request.method.toUpperCase();
|
|
6
|
+
if ("GET" !== method && "HEAD" !== method) return false;
|
|
7
|
+
return request.url.startsWith("/private/");
|
|
8
|
+
};
|
|
4
9
|
function authenticateUsingCookie() {
|
|
5
10
|
return [
|
|
6
11
|
createBeforeHandlerPlugin(async (context)=>{
|
|
7
12
|
const request = context.container.resolve(Request);
|
|
13
|
+
if (!isCookieAuthenticationAllowed(request)) return;
|
|
8
14
|
const { cookies } = request;
|
|
9
15
|
const token = cookies["wby-id-token"];
|
|
10
16
|
if (!context.security.getIdentity() && token) try {
|
|
@@ -18,6 +24,6 @@ function authenticateUsingCookie() {
|
|
|
18
24
|
})
|
|
19
25
|
];
|
|
20
26
|
}
|
|
21
|
-
export { authenticateUsingCookie };
|
|
27
|
+
export { authenticateUsingCookie, isCookieAuthenticationAllowed };
|
|
22
28
|
|
|
23
29
|
//# sourceMappingURL=authenticateUsingCookie.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legacy/security/plugins/authenticateUsingCookie.js","sources":["../../../../src/legacy/security/plugins/authenticateUsingCookie.ts"],"sourcesContent":["import { createContextPlugin } from \"@webiny/api\";\nimport { createBeforeHandlerPlugin, Request } from \"@webiny/handler\";\nimport type { ApiCoreContext } from \"~/types/core.js\";\nimport { SetIdTokenCookie } from \"~/features/security/authentication/AuthenticationContext/SetIdTokenCookie.js\";\n\n/**\n * @internal\n */\nexport function authenticateUsingCookie() {\n return [\n createBeforeHandlerPlugin<ApiCoreContext>(async context => {\n const request = context.container.resolve(Request);\n const { cookies } = request;\n const token = cookies[\"wby-id-token\"];\n\n if (!context.security.getIdentity() && token) {\n try {\n await context.security.authenticate(token);\n } catch (err) {\n console.log(err);\n }\n }\n }),\n\n createContextPlugin<ApiCoreContext>(context => {\n context.container.register(SetIdTokenCookie);\n })\n ];\n}\n"],"names":["authenticateUsingCookie","createBeforeHandlerPlugin","context","
|
|
1
|
+
{"version":3,"file":"legacy/security/plugins/authenticateUsingCookie.js","sources":["../../../../src/legacy/security/plugins/authenticateUsingCookie.ts"],"sourcesContent":["import { createContextPlugin } from \"@webiny/api\";\nimport { createBeforeHandlerPlugin, Request } from \"@webiny/handler\";\nimport type { ApiCoreContext } from \"~/types/core.js\";\nimport { SetIdTokenCookie } from \"~/features/security/authentication/AuthenticationContext/SetIdTokenCookie.js\";\n\n/**\n * The `wby-id-token` cookie exists only for private file delivery: an `<img src>` cannot send an\n * `Authorization` header. It must not log users in anywhere else, because the browser attaches it\n * to cross-site requests too (`SameSite=None`), which would let any website call the API as the user.\n */\nexport const isCookieAuthenticationAllowed = (\n request: Pick<Request.Interface, \"method\" | \"url\">\n) => {\n const method = request.method.toUpperCase();\n if (method !== \"GET\" && method !== \"HEAD\") {\n return false;\n }\n return request.url.startsWith(\"/private/\");\n};\n\n/**\n * @internal\n */\nexport function authenticateUsingCookie() {\n return [\n createBeforeHandlerPlugin<ApiCoreContext>(async context => {\n const request = context.container.resolve(Request);\n if (!isCookieAuthenticationAllowed(request)) {\n return;\n }\n const { cookies } = request;\n const token = cookies[\"wby-id-token\"];\n\n if (!context.security.getIdentity() && token) {\n try {\n await context.security.authenticate(token);\n } catch (err) {\n console.log(err);\n }\n }\n }),\n\n createContextPlugin<ApiCoreContext>(context => {\n context.container.register(SetIdTokenCookie);\n })\n ];\n}\n"],"names":["isCookieAuthenticationAllowed","request","method","authenticateUsingCookie","createBeforeHandlerPlugin","context","Request","cookies","token","err","console","createContextPlugin","SetIdTokenCookie"],"mappings":";;;AAUO,MAAMA,gCAAgC,CACzCC;IAEA,MAAMC,SAASD,QAAQ,MAAM,CAAC,WAAW;IACzC,IAAIC,AAAW,UAAXA,UAAoBA,AAAW,WAAXA,QACpB,OAAO;IAEX,OAAOD,QAAQ,GAAG,CAAC,UAAU,CAAC;AAClC;AAKO,SAASE;IACZ,OAAO;QACHC,0BAA0C,OAAMC;YAC5C,MAAMJ,UAAUI,QAAQ,SAAS,CAAC,OAAO,CAACC;YAC1C,IAAI,CAACN,8BAA8BC,UAC/B;YAEJ,MAAM,EAAEM,OAAO,EAAE,GAAGN;YACpB,MAAMO,QAAQD,OAAO,CAAC,eAAe;YAErC,IAAI,CAACF,QAAQ,QAAQ,CAAC,WAAW,MAAMG,OACnC,IAAI;gBACA,MAAMH,QAAQ,QAAQ,CAAC,YAAY,CAACG;YACxC,EAAE,OAAOC,KAAK;gBACVC,QAAQ,GAAG,CAACD;YAChB;QAER;QAEAE,oBAAoCN,CAAAA;YAChCA,QAAQ,SAAS,CAAC,QAAQ,CAACO;QAC/B;KACH;AACL"}
|
|
@@ -12,8 +12,11 @@ const whitelistedHeaders = [
|
|
|
12
12
|
const setupSecureHeaders = ()=>createHandlerOnRequest(async (request, reply)=>{
|
|
13
13
|
const isOptions = "OPTIONS" === request.method;
|
|
14
14
|
const headers = ResponseHeaders.create();
|
|
15
|
-
headers.set("access-control-allow-origin",
|
|
16
|
-
|
|
15
|
+
if (request.url.startsWith("/private/")) headers.set("access-control-allow-origin", "*");
|
|
16
|
+
else {
|
|
17
|
+
headers.set("access-control-allow-origin", request.headers["origin"]);
|
|
18
|
+
headers.set("access-control-allow-credentials", "true");
|
|
19
|
+
}
|
|
17
20
|
if (isOptions) {
|
|
18
21
|
headers.set("cache-control", "public, max-age=86400");
|
|
19
22
|
headers.set("content-type", "application/json; charset=utf-8");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legacy/security/plugins/secureHeaders.js","sources":["../../../../src/legacy/security/plugins/secureHeaders.ts"],"sourcesContent":["import { createHandlerOnRequest, ResponseHeaders } from \"@webiny/handler\";\n\nconst whitelistedHeaders = [\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"content-type\",\n \"x-tenant\",\n \"x-apollo-tracing\",\n \"x-webiny-debug\",\n \"apollo-query-plan-experimental\"\n];\n\nexport const setupSecureHeaders = () => {\n return createHandlerOnRequest(async (request, reply) => {\n const isOptions = request.method === \"OPTIONS\";\n\n const headers = ResponseHeaders.create();\n headers.set(\"access-control-allow-origin\", request.headers[\"origin\"]);\n
|
|
1
|
+
{"version":3,"file":"legacy/security/plugins/secureHeaders.js","sources":["../../../../src/legacy/security/plugins/secureHeaders.ts"],"sourcesContent":["import { createHandlerOnRequest, ResponseHeaders } from \"@webiny/handler\";\n\nconst whitelistedHeaders = [\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"content-type\",\n \"x-tenant\",\n \"x-apollo-tracing\",\n \"x-webiny-debug\",\n \"apollo-query-plan-experimental\"\n];\n\nexport const setupSecureHeaders = () => {\n return createHandlerOnRequest(async (request, reply) => {\n const isOptions = request.method === \"OPTIONS\";\n\n const headers = ResponseHeaders.create();\n /**\n * Private files are authenticated with the `wby-id-token` cookie. Their responses must not\n * be readable by other websites through a credentialed `fetch`, so they get a wildcard origin\n * without credentials. `<img src>`, links and plain `fetch` calls are not affected.\n */\n if (request.url.startsWith(\"/private/\")) {\n headers.set(\"access-control-allow-origin\", \"*\");\n } else {\n headers.set(\"access-control-allow-origin\", request.headers[\"origin\"]);\n headers.set(\"access-control-allow-credentials\", \"true\");\n }\n\n if (isOptions) {\n headers.set(\"cache-control\", \"public, max-age=86400\");\n headers.set(\"content-type\", \"application/json; charset=utf-8\");\n headers.set(\"access-control-max-age\", \"86400\");\n headers.set(\"access-control-allow-methods\", \"OPTIONS,POST,GET,DELETE,PUT,PATCH\");\n headers.set(\"access-control-allow-headers\", whitelistedHeaders.join(\", \"));\n } else {\n headers.set(\"x-tenant\", request.headers[\"x-tenant\"] || \"root\");\n headers.set(\"vary\", \"origin\");\n }\n\n reply.headers(headers.getHeaders());\n });\n};\n"],"names":["whitelistedHeaders","setupSecureHeaders","createHandlerOnRequest","request","reply","isOptions","headers","ResponseHeaders"],"mappings":";AAEA,MAAMA,qBAAqB;IACvB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACH;AAEM,MAAMC,qBAAqB,IACvBC,uBAAuB,OAAOC,SAASC;QAC1C,MAAMC,YAAYF,AAAmB,cAAnBA,QAAQ,MAAM;QAEhC,MAAMG,UAAUC,gBAAgB,MAAM;QAMtC,IAAIJ,QAAQ,GAAG,CAAC,UAAU,CAAC,cACvBG,QAAQ,GAAG,CAAC,+BAA+B;aACxC;YACHA,QAAQ,GAAG,CAAC,+BAA+BH,QAAQ,OAAO,CAAC,SAAS;YACpEG,QAAQ,GAAG,CAAC,oCAAoC;QACpD;QAEA,IAAID,WAAW;YACXC,QAAQ,GAAG,CAAC,iBAAiB;YAC7BA,QAAQ,GAAG,CAAC,gBAAgB;YAC5BA,QAAQ,GAAG,CAAC,0BAA0B;YACtCA,QAAQ,GAAG,CAAC,gCAAgC;YAC5CA,QAAQ,GAAG,CAAC,gCAAgCN,mBAAmB,IAAI,CAAC;QACxE,OAAO;YACHM,QAAQ,GAAG,CAAC,YAAYH,QAAQ,OAAO,CAAC,WAAW,IAAI;YACvDG,QAAQ,GAAG,CAAC,QAAQ;QACxB;QAEAF,MAAM,OAAO,CAACE,QAAQ,UAAU;IACpC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webiny/api-core",
|
|
3
|
-
"version": "6.4.12-beta.
|
|
3
|
+
"version": "6.4.12-beta.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -14,39 +14,39 @@
|
|
|
14
14
|
"./*": "./*"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@ai-sdk/anthropic": "4.0.
|
|
18
|
-
"@ai-sdk/openai": "4.0.
|
|
19
|
-
"@webiny/api": "6.4.12-beta.
|
|
17
|
+
"@ai-sdk/anthropic": "4.0.105",
|
|
18
|
+
"@ai-sdk/openai": "4.0.118",
|
|
19
|
+
"@webiny/api": "6.4.12-beta.10",
|
|
20
20
|
"@webiny/di": "1.1.0",
|
|
21
|
-
"@webiny/error": "6.4.12-beta.
|
|
22
|
-
"@webiny/feature": "6.4.12-beta.
|
|
23
|
-
"@webiny/feature-flags": "6.4.12-beta.
|
|
24
|
-
"@webiny/handler": "6.4.12-beta.
|
|
25
|
-
"@webiny/handler-db": "6.4.12-beta.
|
|
26
|
-
"@webiny/handler-graphql": "6.4.12-beta.
|
|
27
|
-
"@webiny/plugins": "6.4.12-beta.
|
|
28
|
-
"@webiny/utils": "6.4.12-beta.
|
|
29
|
-
"@webiny/wcp": "6.4.12-beta.
|
|
30
|
-
"ai": "7.0.
|
|
21
|
+
"@webiny/error": "6.4.12-beta.10",
|
|
22
|
+
"@webiny/feature": "6.4.12-beta.10",
|
|
23
|
+
"@webiny/feature-flags": "6.4.12-beta.10",
|
|
24
|
+
"@webiny/handler": "6.4.12-beta.10",
|
|
25
|
+
"@webiny/handler-db": "6.4.12-beta.10",
|
|
26
|
+
"@webiny/handler-graphql": "6.4.12-beta.10",
|
|
27
|
+
"@webiny/plugins": "6.4.12-beta.10",
|
|
28
|
+
"@webiny/utils": "6.4.12-beta.10",
|
|
29
|
+
"@webiny/wcp": "6.4.12-beta.10",
|
|
30
|
+
"ai": "7.0.173",
|
|
31
31
|
"dataloader": "2.2.3",
|
|
32
|
-
"jose": "6.2.
|
|
32
|
+
"jose": "6.2.17",
|
|
33
33
|
"jsonwebtoken": "9.0.3",
|
|
34
34
|
"lodash": "4.18.1",
|
|
35
|
-
"minimatch": "
|
|
36
|
-
"pino": "10.
|
|
35
|
+
"minimatch": "11.0.8",
|
|
36
|
+
"pino": "10.4.0",
|
|
37
37
|
"pino-lambda": "4.4.1",
|
|
38
|
-
"zod": "4.6.
|
|
38
|
+
"zod": "4.6.7"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@types/jsonwebtoken": "9.0.10",
|
|
42
|
-
"@webiny/build-tools": "6.4.12-beta.
|
|
43
|
-
"@webiny/db-dynamodb": "6.4.12-beta.
|
|
44
|
-
"@webiny/handler-aws": "6.4.12-beta.
|
|
45
|
-
"@webiny/project-utils": "6.4.12-beta.
|
|
42
|
+
"@webiny/build-tools": "6.4.12-beta.10",
|
|
43
|
+
"@webiny/db-dynamodb": "6.4.12-beta.10",
|
|
44
|
+
"@webiny/handler-aws": "6.4.12-beta.10",
|
|
45
|
+
"@webiny/project-utils": "6.4.12-beta.10",
|
|
46
46
|
"jest-dynalite": "3.6.1",
|
|
47
|
-
"rimraf": "6.1.
|
|
47
|
+
"rimraf": "6.1.4",
|
|
48
48
|
"typescript": "6.0.3",
|
|
49
|
-
"vitest": "5.0
|
|
49
|
+
"vitest": "5.1.0"
|
|
50
50
|
},
|
|
51
51
|
"publishConfig": {
|
|
52
52
|
"access": "public"
|