diff --git a/packages/cms/.env.example b/packages/cms/.env.example index 4f5ae276..92e2b32d 100644 --- a/packages/cms/.env.example +++ b/packages/cms/.env.example @@ -4,7 +4,8 @@ PAYLOAD_PUBLIC_FRONTEND_URL=http://localhost:3000 PAYLOAD_PRIVATE_REVALIDATION_KEY=EXAMPLE_REVALIDATION_KEY # seed database when starting up for the first time. -# ONLY FOR DEV, do NOT do this for prod -# also sets up root@tietokilta.fi account with autologin enabled -#PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_AND_SEEDING=true - +# ONLY FOR DEV, do NOT do this for staging/prod +# also sets up account with autologin enabled, if not already set up +#PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT=true +#PAYLOAD_PUBLIC_DEVELOPMENT_AUTOLOGIN_USERNAME=root@tietokilta.fi +#PAYLOAD_PUBLIC_DEVELOPMENT_AUTOLOGIN_PASSWORD=root diff --git a/packages/cms/src/payload.config.ts b/packages/cms/src/payload.config.ts index 3288f169..e008ed86 100644 --- a/packages/cms/src/payload.config.ts +++ b/packages/cms/src/payload.config.ts @@ -18,10 +18,12 @@ export default buildConfig({ bundler: viteBundler(), user: Users.slug, autoLogin: - process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_AND_SEEDING === "true" + process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT === "true" && + process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_EMAIL && + process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_PASSWORD ? { - email: "root@tietokilta.fi", - password: "root", + email: process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_EMAIL, + password: process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_PASSWORD, } : false, }, diff --git a/packages/cms/src/server.ts b/packages/cms/src/server.ts index 48aa6375..d469685d 100644 --- a/packages/cms/src/server.ts +++ b/packages/cms/src/server.ts @@ -21,8 +21,36 @@ const start = async () => { await payload.init({ secret: process.env.PAYLOAD_SECRET!, express: app, - onInit: (payload) => { + onInit: async (payload) => { payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`); + if (process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT === "true") { + const email = process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_EMAIL; + const password = process.env.PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_PASSWORD; + if (!email || !password) { + throw new Error( + "PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_EMAIL and PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT_PASSWORD must be set when PAYLOAD_PUBLIC_LOCAL_DEVELOPMENT is true", + ); + } + // check if the user exists, if not, create it + const user = await payload.find({ + collection: "users", + where: { email: { equals: email } }, + }); + if (user.totalDocs === 0) { + payload.logger.warn(`user ${email} not found, creating...`); + payload.logger.warn( + "NOTE that it is recommended to use the seeding scripts to a get filled database for local development", + ); + await payload.create({ + collection: "users", + data: { + email, + password, + }, + }); + payload.logger.warn("Payload autologin enabled!"); + } + } }, });