Skip to content

Instantly share code, notes, and snippets.

@datio
Created August 6, 2018 12:56
Show Gist options
  • Save datio/23b78c963a48498fecf2d4d3d15163d0 to your computer and use it in GitHub Desktop.
Save datio/23b78c963a48498fecf2d4d3d15163d0 to your computer and use it in GitHub Desktop.

Revisions

  1. datio created this gist Aug 6, 2018.
    63 changes: 63 additions & 0 deletions UserLogin.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    <?php

    namespace Datio\WeightixCli\Cli\Command\Misc;

    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Input\InputOption;
    use Symfony\Component\Console\Output\OutputInterface;

    class UserLogin extends Command
    {
    protected function configure()
    {
    $this
    ->setName('misc-user:login')
    ->setDescription('Create an authenticated session for a user')
    ->addOption(
    'user-id',
    null,
    InputOption::VALUE_REQUIRED,
    'User id of user'
    );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
    $userId = $input->getOption('user-id');

    $errors = false;
    $missingArgs = [];
    if (!$userId) {
    array_push($missingArgs, 'user-id');
    $errors = true;
    }

    if ($errors) {
    $output->writeln(sprintf("<error>Required argument(s): %s.</error>", implode(', ', $missingArgs)));
    return 1;
    }

    /** @var \XF\Entity\User $user */
    $user = \XF::app()->finder('XF:User')->where('user_id', $userId)->with(['Profile'])->fetchOne();
    if (!$user) {
    $output->writeln("<error>User could not be found.</error>");
    return 1;
    }

    $class = \XF::app()->extendClass('XF\Session\Session');
    /** @var \XF\Session\Session $session */
    $session = new $class(\XF::app()->container('session.public.storage'), [
    'cookie' => 'session'
    ]);

    $session->start(\XF::app()->request());
    $session->changeUser($user);
    $cookieVal = $session->getSessionId();
    $session->save();

    $output->writeln(sprintf("xf_session: %s", $cookieVal));

    return 0;
    }
    }