Kirby initialization

Hi,

I’m currently working on a starter for my Kirby projects. I would like to create programmatically an admin user (credentials defined in a .env file) and pages (like home, error) at the initialization of the project.

I did something like that but don’t know really if it’s ok or if someone have a better idea.
I wonder if for example if “impersonate” will not be called on every request.

$app = new Kirby();

// ----------------------------------

$users = $app->users();

if ($users->isEmpty() || !$users->findBy('email', $_ENV['ADMIN_EMAIL'])) :
    User::create([
        'name'      => $_ENV['ADMIN_NAME'],
        'email'     => $_ENV['ADMIN_EMAIL'],
        'password'  => $_ENV['ADMIN_PASSWORD'],
        'language'  => $_ENV['ADMIN_LANGUAGE'],
        'role'      => 'admin'
    ]);
endif;

// ----------------------------------

$app->impersonate('kirby', function () use($app) {
    if (!$app->page('home')) :
        Page::create([
            'slug' => 'home',
            'template' => 'home',
            'draft' => false,
            'content'  => [
                'title' => 'Home'
            ]
        ]);
    endif;

    if (!$app->page('error')) :
        Page::create([
            'slug' => 'error',
            'template' => 'error',
            'draft' => false,
            'content'  => [
                'title' => 'Error'
            ]
        ]);
    endif;
});

// ----------------------------------

echo $app->render();

If someone already did that, or if you have a more optimized code, feel free to share :smile:

LGTM, I’d probably be lazy and create an array if the names for title, template etc. are repetitive, might not work for all use cases.

$pages = ['home', 'error', 'whatever']:
foreach ( $pages as $page ) {
  try {
    Page::create([
            'slug' => $page,
            'template' => $page,
            'draft' => false,
            'content'  => [
                'title' => ucfirst($page),
            ],
        ]);
  } catch( Exception $e ) {
    echo $e->getMessage();
  }
}
1 Like

Yes, don’t work for my case (most of my projects are in french) but good idea.

Is it not a problem to call the impersonate on each request ?

Impersonation with the callback is probably not a problem as the user is automatically reset after your callback returns. It will have a tiny performance impact though.

For security, I wouldn’t use this index.php in production though. If the web server is misconfigured, it could be possible to inject the ADMIN_* env vars from the request, which is an unnecessary risk.

Ok, this is what I also thought for impersonation. :slight_smile:
Don’t worry, will not use too like that, it was easier to present like this for this topic.

Thanks !