Switch the active user account to perform the import.

@hook pre-command migrate:import
350520
public function preImport(CommandData $commandData) {
    $userid = $commandData->input()->getOption('userid');
    if ($userid) {
      $account = User::load($userid);
      $accountSwitcher = \Drupal::service('account_switcher');
      $userSession = new UserSession([
        'uid'   => $account->id(),
        'name'  => $account->getUsername(),
        'roles' => $account->getRoles(),
      ]);
      $accountSwitcher->switchTo($userSession);
      $this->logger()->notice(
          dt(
              'Now acting as user ID @id',
              ['@id' => \Drupal::currentUser()->id()]
            )
      );
    }
  }
211852
def initiate_migration(self):
        
        self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self)
1276305
protected function migrateAccountRolesDown()
    {
        if (!$this->sm->tablesExist(['typo3_flow_security_account', 'typo3_flow_security_policy_role', 'typo3_flow_security_account_roles_join'])) {
            return;
        }
        $allRolesAndAccounts = array();
        $accountRolesResult = $this->connection->executeQuery('SELECT persistence_object_identifier, roleidentifiers FROM typo3_flow_security_account');
        while ($accountIdentifierAndRoles = $accountRolesResult->fetch(\PDO::FETCH_ASSOC)) {
            $accountIdentifier = $accountIdentifierAndRoles['persistence_object_identifier'];
            $roleIdentifiers = explode(',', $accountIdentifierAndRoles['roleidentifiers']);
            foreach ($roleIdentifiers as $roleIdentifier) {
                if (!isset($allRolesAndAccounts[$roleIdentifier])) {
                    $allRolesAndAccounts[$roleIdentifier] = array();
                }
                $allRolesAndAccounts[$roleIdentifier][] = $accountIdentifier;
            }
        }
        $this->addSql("INSERT INTO typo3_flow_security_policy_role (identifier, sourcehint) VALUES ('Everybody', 'system')");
        $this->addSql("INSERT INTO typo3_flow_security_policy_role (identifier, sourcehint) VALUES ('Anonymous', 'system')");
        $this->addSql("INSERT INTO typo3_flow_security_policy_role (identifier, sourcehint) VALUES ('AuthenticatedUser', 'system')");
        foreach ($allRolesAndAccounts as $roleIdentifier => $accountIdentifiers) {
            $this->addSql("INSERT INTO typo3_flow_security_policy_role (identifier, sourcehint) VALUES (" . $this->connection->quote($roleIdentifier) . ", 'policy')");
            foreach ($accountIdentifiers as $accountIdentifier) {
                $this->addSql("INSERT INTO typo3_flow_security_account_roles_join (flow_security_account, flow_policy_role) VALUES (" . $this->connection->quote($accountIdentifier) . ", " . $this->connection->quote($roleIdentifier) . ")");
            }
        }
    }
206054
public function runMigration()
    {
        if ($this->confirm('Do you want to run all migration now?')) {
            $this->migrated = true;

            $this->console->call('migrate', [
                '--force' => $this->console->option('force'),
            ]);
        }
    }
306550
private void migrateUsers() throws Exception
   {
      Session session = service.getStorageSession();
      try
      {
         if (session.itemExists(usersStorageOld))
         {
            NodeIterator iterator = ((ExtendedNode)session.getItem(usersStorageOld)).getNodesLazily();
            UserHandlerImpl uh = ((UserHandlerImpl)service.getUserHandler());
            while (iterator.hasNext())
            {
               uh.migrateUser(iterator.nextNode());
            }
         }
      }
      finally
      {
         session.logout();
      }
   }
495487
private function runMigration()
    {
        $this->info("Running database migration...");
        $this->call('migrate', ['--force' => true]);

        $this->line('');
        $this->advanceBar();

        $this->clearCaches();
        return $this;
    }
623955
public function up()
	{
		if(Schema::hasColumn('001_017_text', 'lang_017'))
		{
			$key = DB::select(DB::raw('SHOW KEYS FROM 001_017_text WHERE Key_name=\'fk01_001_017_text\''));

			if($key != null)
			{
				Schema::table('001_017_text', function (Blueprint $table) {
					$table->dropForeign('fk01_001_017_text');
					$table->dropIndex('fk01_001_017_text');
				});

				Schema::table('001_017_text', function (Blueprint $table) {
					// rename column, function renameColumn doesn't work
					DB::select(DB::raw('ALTER TABLE 001_017_text CHANGE lang_017 lang_id_017 VARCHAR(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL'));
					$table->foreign('lang_id_017', 'fk01_001_017_text')->references('id_001')->on('001_001_lang')
						->onDelete('restrict')->onUpdate('cascade');
				});
			}
		}
	}
416719
def setup_migrate(app):
    """"""
    directory = path.join(path.dirname(__file__), 'migrations')
    migrate.init_app(app, db, directory=directory)
1231840
public function up()
	{
		//Create our first version of the audittrail table	
		//Please note that this matches the original creation of the 
		//table from version 1 of the extension. Other migrations will
		//upgrade it from here if we ever need to. This was done so
		//that older versions can still use migrate functionality to upgrade.
		$this->createTable( 'audit_trail', [
				'id' => Schema::TYPE_PK,
				'old_value' => Schema::TYPE_TEXT,
				'new_value' => Schema::TYPE_TEXT,
				'action' => Schema::TYPE_STRING . ' NOT NULL',
				'model' => Schema::TYPE_STRING . ' NOT NULL',
				'field' => Schema::TYPE_STRING . '',
				'stamp' => Schema::TYPE_DATETIME . ' NOT NULL',
				'user_id' => Schema::TYPE_STRING . '',
				'model_id' => Schema::TYPE_STRING . ' NOT NULL',
			]
		);

		//Index these bad boys for speedy lookups
		$this->createIndex( 'idx_audit_trail_user_id', 'audit_trail', 'user_id');
		$this->createIndex( 'idx_audit_trail_model_id', 'audit_trail', 'model_id');
		$this->createIndex( 'idx_audit_trail_model', 'audit_trail', 'model');
		$this->createIndex( 'idx_audit_trail_field', 'audit_trail', 'field');
		/* http://stackoverflow.com/a/1827099/383478
		$this->createIndex( 'idx_audit_trail_old_value', 'tbl_audit_trail', 'old_value');
		$this->createIndex( 'idx_audit_trail_new_value', 'tbl_audit_trail', 'new_value');
		*/
		$this->createIndex( 'idx_audit_trail_action', 'audit_trail', 'action');
	}
557356
protected function _initCurrentUser()
    {
        $this->bootstrap(array('acl', 'basepath', 'cache', 'db', 'loader', 'project', 'session', 'translate', 'util'));

        // Fix for _init resourcea being case insensitive
        $container = $this->getContainer();
        $user      = $this->loader->getCurrentUser();
        $container->currentUser = $user;

        return $user;
    }
962699
public function importAction()
    {

        $form = $this->formFactory->create(new ImportUserType(true));
        $form->handleRequest($this->request);
        $mode = $form->get('mode')->getData();

        if ($mode === 'update') {
            $form = $this->formFactory->create(new ImportUserType(true, 1));
            $form->handleRequest($this->request);
        }

        if ($form->isValid()) {
            $file = $form->get('file')->getData();
            $sendMail = $form->get('sendMail')->getData();
            $data = file_get_contents($file);
            $data = $this->container->get('claroline.utilities.misc')->formatCsvOutput($data);
            $lines = str_getcsv($data, PHP_EOL);
            $users = array();
            $toUpdate = array();
            $sessionFlashBag = $this->session->getFlashBag();

            foreach ($lines as $line) {

                if ($mode === 'update') {
                    $datas = str_getcsv($line, ';');
                    $username = $datas[2];
                    $email = $datas[4];
                    $existingUser = $this->userManager->getUserByUsernameOrMail(
                        $username,
                        $email
                    );

                    if (is_null($existingUser)) {
                        $users[] = $datas;
                    } else {
                        $toUpdate[] = $datas;
                    }
                } else {
                    $users[] = str_getcsv($line, ';');
                }
            }

            $roleUser = $this->roleManager->getRoleByName('ROLE_USER');
            $max = $roleUser->getMaxUsers();
            $total = $this->userManager->countUsersByRoleIncludingGroup($roleUser);

            if ($total + count($users) > $max) {

                return array('form' => $form->createView(), 'error' => 'role_user unavailable');
            }

            $additionalRoles = $form->get('roles')->getData();

            foreach ($additionalRoles as $additionalRole) {
                $max = $additionalRole->getMaxUsers();
                $total = $this->userManager->countUsersByRoleIncludingGroup($additionalRole);

                if ($total + count($users) > $max) {

                    return array(
                        'form' => $form->createView(),
                        'error' => $additionalRole->getName() . ' unavailable'
                    );
                }
            }

            if (count($toUpdate) > 0) {
                $updatedNames = $this->userManager->updateImportedUsers(
                    $toUpdate,
                    $additionalRoles->toArray()
                );

                foreach ($updatedNames as $name) {
                    $msg =  '<' . $name . '> ';
                    $msg .= $this->translator->trans(
                        'has_been_updated',
                        array(),
                        'platform'
                    );
                    $sessionFlashBag->add('success', $msg);
                }
            }
            $createdNames = $this->userManager->importUsers(
                $users,
                $sendMail,
                null,
                $additionalRoles
            );

            foreach ($createdNames as $name) {
                $msg =  '<' . $name . '> ';
                $msg .= $this->translator->trans(
                    'has_been_created',
                    array(),
                    'platform'
                );
                $sessionFlashBag->add('success', $msg);
            }

            return new RedirectResponse($this->router->generate('claro_admin_users_index'));
        }

        return array('form' => $form->createView());
    }
234848
public function change()
    {
        $table = $this->table('permissions');
        
        $table->addColumn('owner_model', 'string', [
            'default' => null,
            'null' => false,
            'limit' => 50,
        ]);

        $table->removeColumn('user_id');
        $table->removeColumn('is_active');

        $table->addColumn('owner_foreign_key', 'char', [
            'default' => null,
            'null' => false,
            'limit' => 36 
        ]);

        $table->save();
    }
1239130
def enable(ctx):
    """"""

    if ctx.obj['username'] is None:
        log('Specify the username with "iso db user --username ..."')
        return

    change_user = ctx.obj['db'].objectmodels['user'].find_one({
        'name': ctx.obj['username']
    })

    change_user.active = True
    change_user.save()
    log('Done')
1325171
protected function migrateAccountRolesDown()
    {
        if (!$this->sm->tablesExist(['typo3_flow_security_account_roles_join', 'typo3_flow_security_policy_role'])) {
            return;
        }
        $accountsWithRoles = array();

        $accountRolesResult = $this->connection->executeQuery('SELECT j.flow_security_account, r.identifier FROM typo3_flow_security_account_roles_join as j LEFT JOIN typo3_flow_security_policy_role AS r ON j.flow_policy_role = r.identifier');
        while ($accountIdentifierAndRole = $accountRolesResult->fetch(\PDO::FETCH_ASSOC)) {
            $accountIdentifier = $accountIdentifierAndRole['flow_security_account'];
            $roleIdentifier = $accountIdentifierAndRole['identifier'];
            $accountsWithRoles[$accountIdentifier][] = substr($roleIdentifier, strrpos($roleIdentifier, ':') + 1);
        }

        foreach ($accountsWithRoles as $accountIdentifier => $roles) {
            $this->addSql("UPDATE typo3_flow_security_account SET roles = " . $this->connection->quote(serialize($roles)) . " WHERE persistence_object_identifier = " . $this->connection->quote($accountIdentifier));
        }
    }
769197
public function up()
	{
        // Create the new table
        if (! Schema::hasTable('order_pricelist')) {
            Schema::create('order_pricelist', function(Blueprint $table)
            {
                $table->increments('id');
                $table->integer('order_id')->unsigned();
                $table->integer('pricelist_id')->unsigned();
                $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
                $table->foreign('pricelist_id')->references('id')->on('pricelists')->onDelete('cascade');
            });
        }
        
        // Transfer existing data to new table, at the end of it drop table user_pricelists
        if (Schema::hasTable('user_pricelists') and Schema::hasTable('order_pricelist')) {
            $orders = DB::table('user_pricelists')->get();
            
            foreach ($orders as $item) {
				// Check if user exists
				if (DB::table('users')->where('id', $item->user_id)->count() > 0) {
					$order_id = DB::table('orders')->insertGetId([
						'user_id' => $item->user_id,
						'paid' => $item->paid,
						'transaction_id' => $item->transaction_id,
						'payment_status' => $item->payment_status,
						'options' => $item->options,
						'created_at' => $item->created_at,
						'updated_at' => $item->updated_at
					]);
					
					DB::table('order_pricelist')->insert([
						'order_id' => $order_id,
						'pricelist_id' => $item->pricelist_id
					]);
				}
            }
            
            Schema::dropIfExists('user_pricelists');
        }
	}
270955
def switch_user(self, username, password):
        
        self._username = username
        self._password = password
456430
public function up()
    {
        if (is_null($this->userClassName)) {
            throw new Exception('Admin user model not defined');
        }
        DB::transaction(function () {
            foreach ($this->permissions as $permission) {
                $permissionItem = DB::table('permissions')->where([
                    'name' => $permission['name'],
                    'guard_name' => $permission['guard_name']
                ])->first();
                if (is_null($permissionItem)) {
                    DB::table('permissions')->insert($permission);
                }
            }

            foreach ($this->roles as $role) {
                $permissions = $role['permissions'];
                unset($role['permissions']);

                $roleItem = DB::table('roles')->where([
                    'name' => $role['name'],
                    'guard_name' => $role['guard_name']
                ])->first();
                if (is_null($roleItem)) {
                    $roleId = DB::table('roles')->insertGetId($role);
                } else {
                    $roleId = $roleItem->id;
                }

                $permissionItems = DB::table('permissions')->whereIn('name', $permissions)->where('guard_name',
                    $role['guard_name'])->get();
                foreach ($permissionItems as $permissionItem) {
                    $roleHasPermissionData = [
                        'permission_id' => $permissionItem->id,
                        'role_id' => $roleId
                    ];
                    $roleHasPermissionItem = DB::table('role_has_permissions')->where($roleHasPermissionData)->first();
                    if (is_null($roleHasPermissionItem)) {
                        DB::table('role_has_permissions')->insert($roleHasPermissionData);
                    }
                }
            }

            foreach ($this->users as $user) {
                $roles = $user['roles'];
                unset($user['roles']);

                $permissions = $user['permissions'];
                unset($user['permissions']);

                $userItem = DB::table($this->userTable)->where([
                    'email' => $user['email'],
                ])->first();

                if (is_null($userItem)) {
                    $userId = DB::table($this->userTable)->insertGetId($user);

                    AdminUser::find($userId)->addMedia(storage_path()."/images/avatar.png")
                        ->preservingOriginal()
                        ->toMediaCollection('avatar', 'media');

                    foreach ($roles as $role) {
                        $roleItem = DB::table('roles')->where([
                            'name' => $role['name'],
                            'guard_name' => $role['guard_name']
                        ])->first();

                        $modelHasRoleData = [
                            'role_id' => $roleItem->id,
                            'model_id' => $userId,
                            'model_type' => $this->userClassName
                        ];
                        $modelHasRoleItem = DB::table('model_has_roles')->where($modelHasRoleData)->first();
                        if (is_null($modelHasRoleItem)) {
                            DB::table('model_has_roles')->insert($modelHasRoleData);
                        }
                    }

                    foreach ($permissions as $permission) {
                        $permissionItem = DB::table('permissions')->where([
                            'name' => $permission['name'],
                            'guard_name' => $permission['guard_name']
                        ])->first();

                        $modelHasPermissionData = [
                            'permission_id' => $permissionItem->id,
                            'model_id' => $userId,
                            'model_type' => $this->userClassName
                        ];
                        $modelHasPermissionItem = DB::table('model_has_permissions')->where($modelHasPermissionData)->first();
                        if (is_null($modelHasPermissionItem)) {
                            DB::table('model_has_permissions')->insert($modelHasPermissionData);
                        }
                    }
                }

            }
        });
        app()['cache']->forget(config('permission.cache.key'));
    }