Hello
I want to run a command to auto populate the SQLITE db for local development. See it as hard coded mock data to make it easy for new developers in the team to get the project running.
I do have a way to re-create everything in the api, user and role sector, but I can’t find how to recreate the Strapi Administrator from the code and not the web interface.
This code will create the strapi-super-admin role as it doesn’t exist on the first run, then it will create the super-admin user. For security reasons I’ve added it only for “development” environment, to avoid cases when developers forget about this code in production.
module.exports = async () => {
if (process.env.NODE_ENV === 'development') {
const params = {
username: process.env.DEV_USER || 'admin',
password: process.env.DEV_PASS || 'admin',
firstname: process.env.DEV_USER || 'Admin',
lastname: process.env.DEV_USER || 'Admin',
email: process.env.DEV_EMAIL || 'admin@test.test',
blocked: false,
isActive: true,
};
//Check if any account exists.
const admins = await strapi.query('user', 'admin').find();
if (admins.length === 0) {
try {
let tempPass = params.password;
let verifyRole = await strapi.query('role', 'admin').findOne({ code: 'strapi-super-admin' });
if (!verifyRole) {
verifyRole = await strapi.query('role', 'admin').create({
name: 'Super Admin',
code: 'strapi-super-admin',
description: 'Super Admins can access and manage all features and settings.',
});
}
params.roles = [verifyRole.id];
params.password = await strapi.admin.services.auth.hashPassword(params.password);
await strapi.query('user', 'admin').create({
...params,
});
strapi.log.info('Admin account was successfully created.');
strapi.log.info(`Email: ${params.email}`);
strapi.log.info(`Password: ${tempPass}`);
} catch (error) {
strapi.log.error(`Couldn't create Admin account during bootstrap: `, error);
}
}
}
};
@Antoine, @jakubgs, if you usually need to use this functionality during the development process, check my new plugin strapi-plugin-boostrap-admin-user, which uses the plugin’s bootstrap.js file to create the admin user on the first run. So there is no need to hardcode all that stuff in your main bootstrap.js file.
It works in production, you just have to be more careful. Is better if you create it by hand in the production environment and only use it in develelopment. That type of automation is not good in production. But it works in both
being super newbie in strapi, where did you have to put this code? I am trying to initialize strapi automatically, and i also need to create folders before it can be used.