diff --git a/libs/auth-core/package.json b/libs/auth-core/package.json index 6dfdbd3c..d7c03be3 100644 --- a/libs/auth-core/package.json +++ b/libs/auth-core/package.json @@ -6,7 +6,6 @@ "peerDependencies": { "@amplication/code-gen-types": "^2.0.23", "@amplication/code-gen-utils": "^0.0.9", - "@babel/types": "7.24.0", "ast-types": "0.14.2", "dotenv": "16.3.2", "lodash": "^4.17.21", diff --git a/libs/auth-core/src/auth-core-plugin.spec.ts b/libs/auth-core/src/auth-core-plugin.spec.ts index b677b5fc..66244636 100644 --- a/libs/auth-core/src/auth-core-plugin.spec.ts +++ b/libs/auth-core/src/auth-core-plugin.spec.ts @@ -2,7 +2,6 @@ import { EventNames, Events } from "@amplication/code-gen-types"; import { AuthCorePlugin } from "./auth-core-plugin"; import { afterCreateAppModule, - afterCreateSeed, afterCreateServerAuth, afterCreateServerPackageJson, beforeCreateAppModule, @@ -15,7 +14,6 @@ import { beforeCreateEntityResolverToOneRelationMethods, beforeCreateResolverBaseModule, beforeCreateResolverModule, - beforeCreateSeed, beforeCreateServer, beforeCreateServerDotEnv, beforeCreateServerPackageJson, @@ -84,10 +82,6 @@ describe("AuthCorePlugin", () => { CreateEntityResolverToOneRelationMethods: { before: beforeCreateEntityResolverToOneRelationMethods, }, - CreateSeed: { - before: beforeCreateSeed, - after: afterCreateSeed, - }, CreateServer: { before: beforeCreateServer, }, @@ -136,10 +130,6 @@ describe("AuthCorePlugin", () => { CreateEntityResolverToOneRelationMethods: { before: beforeCreateEntityResolverToOneRelationMethods, }, - CreateSeed: { - before: beforeCreateSeed, - after: afterCreateSeed, - }, CreateServer: { before: beforeCreateServer, }, diff --git a/libs/auth-core/src/auth-core-plugin.ts b/libs/auth-core/src/auth-core-plugin.ts index f39478ec..35e9027c 100644 --- a/libs/auth-core/src/auth-core-plugin.ts +++ b/libs/auth-core/src/auth-core-plugin.ts @@ -5,7 +5,6 @@ import { } from "@amplication/code-gen-types"; import { afterCreateAppModule, - afterCreateSeed, afterCreateServerAuth, beforeCreateAppModule, beforeCreateEntityControllerModule, @@ -15,7 +14,6 @@ import { beforeCreateEntityResolverToOneRelationMethods, beforeCreateResolverBaseModule, beforeCreateResolverModule, - beforeCreateSeed, beforeCreateServer, beforeCreateServerDotEnv, beforeCreateServerPackageJson, @@ -70,10 +68,6 @@ export abstract class AuthCorePlugin implements AmplicationPlugin { CreateEntityResolverToOneRelationMethods: { before: beforeCreateEntityResolverToOneRelationMethods, }, - CreateSeed: { - before: beforeCreateSeed, - after: afterCreateSeed, - }, CreateServer: { before: beforeCreateServer, }, diff --git a/libs/auth-core/src/core/user-entity.ts b/libs/auth-core/src/core/user-entity.ts index b74a895d..4abecc3e 100644 --- a/libs/auth-core/src/core/user-entity.ts +++ b/libs/auth-core/src/core/user-entity.ts @@ -4,7 +4,6 @@ import { EntityField, EnumEntityPermissionType, EnumEntityAction, - DsgContext, } from "@amplication/code-gen-types"; export const USER_ENTITY_NAME = "User"; diff --git a/libs/auth-core/src/index.ts b/libs/auth-core/src/index.ts index 6f91ad1f..49449212 100644 --- a/libs/auth-core/src/index.ts +++ b/libs/auth-core/src/index.ts @@ -7,7 +7,6 @@ export * from "./events/create-entity-resolver-base"; export * from "./events/create-entity-resolver-to-many-relation-methods"; export * from "./events/create-entity-resolver-to-one-relation-methods"; export * from "./events/create-entity-resolver"; -export * from "./events/create-seeds"; export * from "./events/create-server-app-module"; export * from "./events/create-server-auth"; export * from "./events/create-server-dotenv"; diff --git a/libs/auth-core/src/tests/afterCreateSeed.spec.ts b/libs/auth-core/src/tests/afterCreateSeed.spec.ts deleted file mode 100644 index c450d6c1..00000000 --- a/libs/auth-core/src/tests/afterCreateSeed.spec.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { - BuildLogger, - CreateSeedParams, - DsgContext, - ModuleMap, -} from "@amplication/code-gen-types"; -import { mock } from "jest-mock-extended"; -import normalize from "normalize-path"; -import path from "path"; -import fg from "fast-glob"; -import * as fs from "fs"; -import { name } from "../../package.json"; -import { afterCreateSeed } from "../index"; - -describe("Testing afterCreateSeed hook", () => { - let context: DsgContext; - let params: CreateSeedParams; - let modules: ModuleMap; - - beforeEach(() => { - context = mock({ - pluginInstallations: [{ npm: name }], - serverDirectories: { scriptsDirectory: "scripts" }, - utils: { - importStaticModules: readStaticModulesInner, - }, - }); - params = mock(); - modules = new ModuleMap(mock()); - }); - - it("should correctly add static scripts files", async () => { - const newModules = await afterCreateSeed(context, params, modules); - expect(newModules.modules().length).toStrictEqual(0); - }); -}); - -/** - * Reads files from given source directory and maps them to module objects with - * path relative to given basePath - * @param source source directory to read files from - * @param basePath path to base the created modules path on - * @returns array of modules - */ -export async function readStaticModulesInner( - source: string, - basePath: string -): Promise { - const directory = `${normalize(source)}/`; - const staticModules = await fg(`${directory}**/*`, { - absolute: false, - dot: true, - ignore: ["**.js", "**.js.map", "**.d.ts"], - }); - const filesToFilter = /(\._.*)|(.DS_Store)$/; - const modules = await Promise.all( - staticModules - .sort() - .filter( - (module) => - !filesToFilter.test( - module.replace(directory, basePath ? basePath + "/" : "") - ) - ) - .map(async (module) => { - const encoding = getFileEncoding(module); - return { - path: module.replace(directory, basePath ? basePath + "/" : ""), - code: await fs.promises.readFile(module, encoding), - }; - }) - ); - const moduleMap: ModuleMap = new ModuleMap(mock()); - for await (const module of modules) { - await moduleMap.set(module); - } - return moduleMap; -} - -export function getFileEncoding(filePath: string): BufferEncoding { - const extension = path.extname(filePath); - switch (extension) { - case ".png": - case ".ico": - case ".jpg": - return "base64"; - default: - return "utf-8"; - } -} diff --git a/package-lock.json b/package-lock.json index a7f4a028..2eba2491 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12276,7 +12276,7 @@ }, "plugins/auth-basic": { "name": "@amplication/plugin-auth-basic", - "version": "1.4.11", + "version": "1.4.12", "license": "ISC", "dependencies": { "@amplication/code-gen-types": "^2.0.23", @@ -12305,7 +12305,7 @@ }, "plugins/auth-core": { "name": "@amplication/plugin-auth-core", - "version": "2.0.13", + "version": "2.0.14", "license": "Apache-2.0", "dependencies": { "@amplication/code-gen-types": "^2.0.23", @@ -12338,7 +12338,7 @@ }, "plugins/auth-jwt": { "name": "@amplication/plugin-auth-jwt", - "version": "1.4.11", + "version": "1.4.12", "license": "ISC", "dependencies": { "@amplication/code-gen-types": "^2.0.23", @@ -12400,7 +12400,7 @@ }, "plugins/auth-saml": { "name": "@amplication/plugin-auth-saml", - "version": "1.0.2", + "version": "1.0.3", "license": "Apache-2.0", "dependencies": { "@amplication/auth-core": "*", diff --git a/plugins/auth-basic/package.json b/plugins/auth-basic/package.json index 1edb0870..2056afb4 100644 --- a/plugins/auth-basic/package.json +++ b/plugins/auth-basic/package.json @@ -1,6 +1,6 @@ { "name": "@amplication/plugin-auth-basic", - "version": "1.4.11", + "version": "1.4.12", "description": "set basic auth for Amplication build", "main": "dist/index.js", "nx": {}, diff --git a/libs/auth-core/src/events/create-seeds.ts b/plugins/auth-basic/src/events/createSeed.ts similarity index 89% rename from libs/auth-core/src/events/create-seeds.ts rename to plugins/auth-basic/src/events/createSeed.ts index a9770a08..edf928f3 100644 --- a/libs/auth-core/src/events/create-seeds.ts +++ b/plugins/auth-basic/src/events/createSeed.ts @@ -1,20 +1,14 @@ -import { - DsgContext, - CreateSeedParams, - ModuleMap, -} from "@amplication/code-gen-types"; +import { CreateSeedParams, DsgContext } from "@amplication/code-gen-types"; +import { addImports, importNames, interpolate } from "../util/ast"; import { builders, namedTypes } from "ast-types"; -import { interpolate, importNames, addImports } from "../util/ast"; import { - BlockStatement, IfStatement, - Statement, FunctionDeclaration, + BlockStatement, + Statement, Identifier, TSTypeAnnotation, } from "@babel/types"; -import { resolve } from "path"; -import { getStaticFiles } from "../util/file"; export async function beforeCreateSeed( context: DsgContext, @@ -175,18 +169,3 @@ export async function beforeCreateSeed( return eventParams; } - -export async function afterCreateSeed( - context: DsgContext, - eventParams: CreateSeedParams, - modules: ModuleMap -): Promise { - const staticPath = resolve(__dirname, "./static/scripts"); - const staticsFiles = await getStaticFiles( - context, - context.serverDirectories.scriptsDirectory, - staticPath - ); - await modules.merge(staticsFiles); - return modules; -} diff --git a/plugins/auth-basic/src/index.ts b/plugins/auth-basic/src/index.ts index fc7de843..01143478 100644 --- a/plugins/auth-basic/src/index.ts +++ b/plugins/auth-basic/src/index.ts @@ -31,6 +31,7 @@ import { AUTH_ENTITY_FIELD_PASSWORD, AUTH_ENTITY_FIELD_USERNAME, } from "./constants"; +import { beforeCreateSeed } from "./events/createSeed"; const ARGS_ID = builders.identifier("args"); const PASSWORD_FIELD_ASYNC_METHODS = new Set(["create", "update"]); @@ -61,6 +62,9 @@ class BasicAuthPlugin implements AmplicationPlugin { CreateEntityServiceBase: { before: this.beforeCreateEntityServiceBase, }, + CreateSeed: { + before: beforeCreateSeed, + }, }; } diff --git a/libs/auth-core/src/tests/beforeCreateSeed.spec.ts b/plugins/auth-basic/src/tests/beforeCreateSeed.spec.ts similarity index 97% rename from libs/auth-core/src/tests/beforeCreateSeed.spec.ts rename to plugins/auth-basic/src/tests/beforeCreateSeed.spec.ts index 4706c19b..20f08a09 100644 --- a/libs/auth-core/src/tests/beforeCreateSeed.spec.ts +++ b/plugins/auth-basic/src/tests/beforeCreateSeed.spec.ts @@ -3,7 +3,7 @@ import { parse } from "@amplication/code-gen-utils"; import { mock } from "jest-mock-extended"; import { prettyPrint } from "recast"; import { name } from "../../package.json"; -import { beforeCreateSeed } from "../events/create-seeds"; +import { beforeCreateSeed } from "../events/createSeed"; describe("Testing beforeCreateSeed hook", () => { let context: DsgContext; diff --git a/plugins/auth-core/package.json b/plugins/auth-core/package.json index 47146398..b2413138 100644 --- a/plugins/auth-core/package.json +++ b/plugins/auth-core/package.json @@ -1,6 +1,6 @@ { "name": "@amplication/plugin-auth-core", - "version": "2.0.13", + "version": "2.0.14", "description": "set auth for Amplication build", "main": "dist/index.js", "nx": {}, diff --git a/plugins/auth-core/src/index.ts b/plugins/auth-core/src/index.ts index 3c647076..82384563 100644 --- a/plugins/auth-core/src/index.ts +++ b/plugins/auth-core/src/index.ts @@ -9,7 +9,6 @@ import { CreateEntityResolverParams, CreateEntityResolverToManyRelationMethodsParams, CreateEntityResolverToOneRelationMethodsParams, - CreateSeedParams, CreateServerAppModuleParams, CreateServerAuthParams, CreateServerDotEnvParams, @@ -57,14 +56,6 @@ import { addInjectableDependency, buildSwaggerForbiddenResponse, } from "./util/nestjs-code-generation"; -import { - BlockStatement, - IfStatement, - Statement, - FunctionDeclaration, - Identifier, - TSTypeAnnotation, -} from "@babel/types"; import { appendImports, parse, print } from "@amplication/code-gen-utils"; import { merge } from "lodash"; @@ -114,10 +105,6 @@ class AuthCorePlugin implements AmplicationPlugin { CreateEntityResolverToOneRelationMethods: { before: this.beforeCreateEntityResolverToOneRelationMethods, }, - CreateSeed: { - before: this.beforeCreateSeed, - after: this.afterCreateSeed, - }, CreateServer: { before: this.beforeCreateServer, }, @@ -243,21 +230,6 @@ class AuthCorePlugin implements AmplicationPlugin { return updatedModules; } - async afterCreateSeed( - context: DsgContext, - eventParams: CreateSeedParams, - modules: ModuleMap - ): Promise { - const staticPath = resolve(__dirname, "./static/scripts"); - const staticsFiles = await AuthCorePlugin.getStaticFiles( - context, - context.serverDirectories.scriptsDirectory, - staticPath - ); - await modules.merge(staticsFiles); - return modules; - } - async afterCreateServerAuth( context: DsgContext, eventParams: CreateServerAuthParams, @@ -917,165 +889,6 @@ class AuthCorePlugin implements AmplicationPlugin { return eventParams; } - - async beforeCreateSeed(context: DsgContext, eventParams: CreateSeedParams) { - interpolate(eventParams.template, eventParams.templateMapping); - - const passwordImport = importNames( - [builders.identifier("Salt"), builders.identifier("parseSalt")], - "../src/auth/password.service" - ); - - const hashImport = importNames([builders.identifier("hash")], "bcrypt"); - - addImports( - eventParams.template, - [passwordImport, hashImport].filter( - (x) => x //remove nulls and undefined - ) as namedTypes.ImportDeclaration[] - ); - - const ifStatementFromBody = eventParams.template.program.body.find( - (x) => x.type === "IfStatement" - ) as IfStatement; - - const functionDeclarationFromBody = eventParams.template.program.body.find( - (x) => x.type === "FunctionDeclaration" - ) as FunctionDeclaration; - - const ifBlock = ifStatementFromBody.consequent as BlockStatement; - const functionDeclarationBlock = - functionDeclarationFromBody.body as BlockStatement; - - const saltConstVariable = builders.variableDeclaration("const", [ - builders.variableDeclarator( - builders.identifier("salt"), - builders.callExpression(builders.identifier("parseSalt"), [ - builders.identifier("BCRYPT_SALT"), - ]) - ), - ]) as Statement; - - const blockCode: namedTypes.BlockStatement = { - body: [ - builders.expressionStatement( - builders.callExpression( - builders.memberExpression( - builders.identifier("console"), - builders.identifier("error") - ), - [builders.identifier("error")] - ) - ), - builders.expressionStatement( - builders.callExpression( - builders.memberExpression( - builders.identifier("process"), - builders.identifier("exit") - ), - [builders.numericLiteral(1)] - ) - ), - ], - directives: [], - type: "BlockStatement", - }; - - const saltExpression = builders.expressionStatement( - builders.callExpression( - builders.memberExpression( - builders.callExpression(builders.identifier("seed"), [ - builders.identifier("salt"), - ]), - builders.identifier("catch") - ), - [ - builders.arrowFunctionExpression( - [builders.identifier("error")], - blockCode - ), - ] - ) - ) as Statement; - - const bcryptSaltIdentifier = builders.identifier( - "bcryptSalt" - ) as Identifier; - bcryptSaltIdentifier.typeAnnotation = builders.tsTypeAnnotation( - builders.tsTypeReference(builders.identifier("Salt")) - ) as TSTypeAnnotation; - - const authEntity = context.entities?.find( - (x) => x.name === context.resourceInfo?.settings.authEntityName - ); - - if (!authEntity) { - context.logger.error(`Authentication entity does not exist`); - return eventParams; - } - - const functionExp = builders.expressionStatement( - builders.awaitExpression( - builders.callExpression( - builders.memberExpression( - builders.memberExpression( - builders.identifier("client"), - builders.identifier(authEntity.name.toLocaleLowerCase()) - ), - builders.identifier("upsert") - ), - [ - builders.objectExpression([ - builders.objectProperty( - builders.identifier("where"), - builders.objectExpression([ - builders.objectProperty( - builders.identifier("username"), - builders.memberExpression( - builders.identifier("data"), - builders.identifier("username") - ) - ), - ]) - ), - builders.objectProperty( - builders.identifier("update"), - builders.objectExpression([]) - ), - builders.objectProperty( - builders.identifier("create"), - builders.identifier("data") - ), - ]), - ] - ) - ) - ) as Statement; - - const dataVar = builders.variableDeclaration("const", [ - builders.variableDeclarator( - builders.identifier("data"), - builders.identifier("DATA") - ), - ]) as Statement; - - functionDeclarationFromBody.params.push(bcryptSaltIdentifier); - const prevStatement2 = functionDeclarationBlock.body[2]; - const prevStatement3 = functionDeclarationBlock.body[3]; - const prevStatement4 = functionDeclarationBlock.body[4]; - const prevStatement5 = functionDeclarationBlock.body[5]; - - functionDeclarationBlock.body[2] = dataVar; - functionDeclarationBlock.body[3] = functionExp; - functionDeclarationBlock.body[4] = prevStatement2; - functionDeclarationBlock.body[5] = prevStatement3; - functionDeclarationBlock.body[6] = prevStatement4; - functionDeclarationBlock.body[7] = prevStatement5; - - ifBlock.body.push(saltConstVariable, saltExpression); - - return eventParams; - } } export default AuthCorePlugin; diff --git a/plugins/auth-core/src/templates/seed.template.ts b/plugins/auth-core/src/templates/seed.template.ts deleted file mode 100644 index cafd7671..00000000 --- a/plugins/auth-core/src/templates/seed.template.ts +++ /dev/null @@ -1,44 +0,0 @@ -/*** - * This file was auto-generated by Amplication and should not be modified by hand. - * The file will be re-generated with every new build, and all changes will be lost. - * To add a custom seed script, you can safely edit the content of ./customSeed.ts - ***/ - -import * as dotenv from "dotenv"; -import { PrismaClient } from "@prisma/client"; -import { customSeed } from "./customSeed"; - -declare const DATA: { username: string }; - -if (require.main === module) { - dotenv.config(); - - const { BCRYPT_SALT } = process.env; - - if (!BCRYPT_SALT) { - throw new Error("BCRYPT_SALT environment variable must be defined"); - } - - seed().catch((error) => { - console.error(error); - process.exit(1); - }); -} - -async function seed() { - console.info("Seeding database..."); - - const client = new PrismaClient(); - const data = DATA; - await client.user.upsert({ - where: { username: data.username }, - update: {}, - create: data, - }); - void client.$disconnect(); - - console.info("Seeding database with custom seed..."); - customSeed(); - - console.info("Seeded database successfully"); -} diff --git a/plugins/auth-core/src/tests/afterCreateSeed.spec.ts b/plugins/auth-core/src/tests/afterCreateSeed.spec.ts deleted file mode 100644 index 00757007..00000000 --- a/plugins/auth-core/src/tests/afterCreateSeed.spec.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { - BuildLogger, - CreateSeedParams, - DsgContext, - ModuleMap, -} from "@amplication/code-gen-types"; -import { mock } from "jest-mock-extended"; -import normalize from "normalize-path"; -import path from "path"; -import fg from "fast-glob"; -import * as fs from "fs"; -import { name } from "../../package.json"; -import AuthCorePlugin from "../index"; - -describe("Testing afterCreateSeed hook", () => { - let plugin: AuthCorePlugin; - let context: DsgContext; - let params: CreateSeedParams; - let modules: ModuleMap; - - beforeEach(() => { - plugin = new AuthCorePlugin(); - context = mock({ - pluginInstallations: [{ npm: name }], - serverDirectories: { scriptsDirectory: "scripts" }, - utils: { - importStaticModules: readStaticModulesInner, - }, - }); - params = mock(); - modules = new ModuleMap(mock()); - }); - - it("should correctly add static scripts files", async () => { - const newModules = await plugin.afterCreateSeed(context, params, modules); - expect(newModules.modules().length).toStrictEqual(0); - }); -}); - -/** - * Reads files from given source directory and maps them to module objects with - * path relative to given basePath - * @param source source directory to read files from - * @param basePath path to base the created modules path on - * @returns array of modules - */ -export async function readStaticModulesInner( - source: string, - basePath: string -): Promise { - const directory = `${normalize(source)}/`; - const staticModules = await fg(`${directory}**/*`, { - absolute: false, - dot: true, - ignore: ["**.js", "**.js.map", "**.d.ts"], - }); - const filesToFilter = /(\._.*)|(.DS_Store)$/; - const modules = await Promise.all( - staticModules - .sort() - .filter( - (module) => - !filesToFilter.test( - module.replace(directory, basePath ? basePath + "/" : "") - ) - ) - .map(async (module) => { - const encoding = getFileEncoding(module); - return { - path: module.replace(directory, basePath ? basePath + "/" : ""), - code: await fs.promises.readFile(module, encoding), - }; - }) - ); - const moduleMap: ModuleMap = new ModuleMap(mock()); - for await (const module of modules) { - await moduleMap.set(module); - } - return moduleMap; -} - -export function getFileEncoding(filePath: string): BufferEncoding { - const extension = path.extname(filePath); - switch (extension) { - case ".png": - case ".ico": - case ".jpg": - return "base64"; - default: - return "utf-8"; - } -} diff --git a/plugins/auth-jwt/package.json b/plugins/auth-jwt/package.json index fbc35ba8..08aeeb4e 100644 --- a/plugins/auth-jwt/package.json +++ b/plugins/auth-jwt/package.json @@ -1,6 +1,6 @@ { "name": "@amplication/plugin-auth-jwt", - "version": "1.4.11", + "version": "1.4.12", "description": "set jwt as provider for Amplication build", "main": "dist/index.js", "nx": {}, diff --git a/plugins/auth-jwt/src/events/createSeed.ts b/plugins/auth-jwt/src/events/createSeed.ts new file mode 100644 index 00000000..edf928f3 --- /dev/null +++ b/plugins/auth-jwt/src/events/createSeed.ts @@ -0,0 +1,171 @@ +import { CreateSeedParams, DsgContext } from "@amplication/code-gen-types"; +import { addImports, importNames, interpolate } from "../util/ast"; +import { builders, namedTypes } from "ast-types"; +import { + IfStatement, + FunctionDeclaration, + BlockStatement, + Statement, + Identifier, + TSTypeAnnotation, +} from "@babel/types"; + +export async function beforeCreateSeed( + context: DsgContext, + eventParams: CreateSeedParams +) { + interpolate(eventParams.template, eventParams.templateMapping); + + const passwordImport = importNames( + [builders.identifier("Salt"), builders.identifier("parseSalt")], + "../src/auth/password.service" + ); + + const hashImport = importNames([builders.identifier("hash")], "bcrypt"); + + addImports( + eventParams.template, + [passwordImport, hashImport].filter( + (x) => x //remove nulls and undefined + ) as namedTypes.ImportDeclaration[] + ); + + const ifStatementFromBody = eventParams.template.program.body.find( + (x) => x.type === "IfStatement" + ) as IfStatement; + + const functionDeclarationFromBody = eventParams.template.program.body.find( + (x) => x.type === "FunctionDeclaration" + ) as FunctionDeclaration; + + const ifBlock = ifStatementFromBody.consequent as BlockStatement; + const functionDeclarationBlock = + functionDeclarationFromBody.body as BlockStatement; + + const saltConstVariable = builders.variableDeclaration("const", [ + builders.variableDeclarator( + builders.identifier("salt"), + builders.callExpression(builders.identifier("parseSalt"), [ + builders.identifier("BCRYPT_SALT"), + ]) + ), + ]) as Statement; + + const blockCode: namedTypes.BlockStatement = { + body: [ + builders.expressionStatement( + builders.callExpression( + builders.memberExpression( + builders.identifier("console"), + builders.identifier("error") + ), + [builders.identifier("error")] + ) + ), + builders.expressionStatement( + builders.callExpression( + builders.memberExpression( + builders.identifier("process"), + builders.identifier("exit") + ), + [builders.numericLiteral(1)] + ) + ), + ], + directives: [], + type: "BlockStatement", + }; + + const saltExpression = builders.expressionStatement( + builders.callExpression( + builders.memberExpression( + builders.callExpression(builders.identifier("seed"), [ + builders.identifier("salt"), + ]), + builders.identifier("catch") + ), + [ + builders.arrowFunctionExpression( + [builders.identifier("error")], + blockCode + ), + ] + ) + ) as Statement; + + const bcryptSaltIdentifier = builders.identifier("bcryptSalt") as Identifier; + bcryptSaltIdentifier.typeAnnotation = builders.tsTypeAnnotation( + builders.tsTypeReference(builders.identifier("Salt")) + ) as TSTypeAnnotation; + + const authEntity = context.entities?.find( + (x) => x.name === context.resourceInfo?.settings.authEntityName + ); + + if (!authEntity) { + context.logger.error(`Authentication entity does not exist`); + return eventParams; + } + + const functionExp = builders.expressionStatement( + builders.awaitExpression( + builders.callExpression( + builders.memberExpression( + builders.memberExpression( + builders.identifier("client"), + builders.identifier(authEntity.name.toLocaleLowerCase()) + ), + builders.identifier("upsert") + ), + [ + builders.objectExpression([ + builders.objectProperty( + builders.identifier("where"), + builders.objectExpression([ + builders.objectProperty( + builders.identifier("username"), + builders.memberExpression( + builders.identifier("data"), + builders.identifier("username") + ) + ), + ]) + ), + builders.objectProperty( + builders.identifier("update"), + builders.objectExpression([]) + ), + builders.objectProperty( + builders.identifier("create"), + builders.identifier("data") + ), + ]), + ] + ) + ) + ) as Statement; + + const dataVar = builders.variableDeclaration("const", [ + builders.variableDeclarator( + builders.identifier("data"), + builders.identifier("DATA") + ), + ]) as Statement; + + functionDeclarationFromBody.params.push(bcryptSaltIdentifier); + const prevStatement2 = functionDeclarationBlock.body[2]; + const prevStatement3 = functionDeclarationBlock.body[3]; + const prevStatement4 = functionDeclarationBlock.body[4]; + const prevStatement5 = functionDeclarationBlock.body[5]; + + functionDeclarationBlock.body[2] = dataVar; + functionDeclarationBlock.body[3] = functionExp; + functionDeclarationBlock.body[4] = prevStatement2; + functionDeclarationBlock.body[5] = prevStatement3; + functionDeclarationBlock.body[6] = prevStatement4; + functionDeclarationBlock.body[7] = prevStatement5; + + ifBlock.body.push(saltConstVariable, saltExpression); + + return eventParams; +} diff --git a/plugins/auth-jwt/src/index.ts b/plugins/auth-jwt/src/index.ts index 7576767b..06c3e57b 100644 --- a/plugins/auth-jwt/src/index.ts +++ b/plugins/auth-jwt/src/index.ts @@ -40,6 +40,7 @@ import { updateDockerComposeProperties, } from "./constants"; import { getPluginSettings } from "./util/getPluginSettings"; +import { beforeCreateSeed } from "./events/createSeed"; const ARGS_ID = builders.identifier("args"); const PASSWORD_FIELD_ASYNC_METHODS = new Set(["create", "update"]); @@ -76,6 +77,9 @@ class JwtAuthPlugin implements AmplicationPlugin { CreateServerSecretsManager: { before: this.beforeCreateSecretsManager, }, + CreateSeed: { + before: beforeCreateSeed, + }, }; } diff --git a/plugins/auth-core/src/tests/beforeCreateSeed.spec.ts b/plugins/auth-jwt/src/tests/beforeCreateSeed.spec.ts similarity index 93% rename from plugins/auth-core/src/tests/beforeCreateSeed.spec.ts rename to plugins/auth-jwt/src/tests/beforeCreateSeed.spec.ts index 65536a47..20f08a09 100644 --- a/plugins/auth-core/src/tests/beforeCreateSeed.spec.ts +++ b/plugins/auth-jwt/src/tests/beforeCreateSeed.spec.ts @@ -3,15 +3,13 @@ import { parse } from "@amplication/code-gen-utils"; import { mock } from "jest-mock-extended"; import { prettyPrint } from "recast"; import { name } from "../../package.json"; -import AuthCorePlugin from "../index"; +import { beforeCreateSeed } from "../events/createSeed"; describe("Testing beforeCreateSeed hook", () => { - let plugin: AuthCorePlugin; let context: DsgContext; let params: CreateSeedParams; beforeEach(() => { - plugin = new AuthCorePlugin(); context = mock({ pluginInstallations: [{ npm: name }], resourceInfo: { @@ -29,7 +27,7 @@ describe("Testing beforeCreateSeed hook", () => { }); it("should correctly alter the template", async () => { - const { template } = await plugin.beforeCreateSeed(context, params); + const { template } = await beforeCreateSeed(context, params); const code = prettyPrint(template).code; const expectedCode = prettyCode(correctOutputTemplate); expect(code).toStrictEqual(expectedCode); diff --git a/plugins/auth-saml/package.json b/plugins/auth-saml/package.json index 8ce4cc87..eabd9d52 100644 --- a/plugins/auth-saml/package.json +++ b/plugins/auth-saml/package.json @@ -1,6 +1,6 @@ { "name": "@amplication/plugin-auth-saml", - "version": "1.0.2", + "version": "1.0.3", "description": "Description of your plugin", "main": "dist/index.js", "nx": {},