title: Yii Console Script, Login to User
body: <p>I'm working on a console controller that imports data into a Yii2 app. I'm attempting to use the app's existing models for this import instead of re-engineering all of my validations and inserts, but many of the models use ::beforeSave method to give ownership of newly created records to the user who is logged in. I've been told to apply record ownership to the admin user, but I'm not certain how to &quot;login&quot; a user from a console controller as the Yii::$app-&gt;user property appears to not exist in console controllers.</p>
  <p>How do I populate the Yii::$app-&gt;user-&gt;identity property with a user account of my choice for the duration of a console controller's actions?</p>
  <pre><code>&lt;?php
  
  namespace app\commands;
  
  use yii\console\Controller;
  use Yii;
  
  class TestController extends Controller
  {
    public function beforeAction($action)
    {
      // Set the user identity to admin
      $user = $model-&gt;find()-&gt;where(['usr_username' =&gt; 'admin'])-&gt;one();
      Yii::$app-&gt;user-&gt;login( $user );
    }
    
    public function actionRun()
    {
      /*
      Yii::$app-&gt;user-&gt;identity
      ...should reflect the admin account set above so any controllers or models I invoke see this user performing actions
      */
    }
  }
  </code></pre>