Force user account to have a unique username
Why this is not default is unknown at the moment.
@return void
492489
public function forceUniqueUserNames()
    {
        //Check for not unique index in user table
        $userLoginIndex = $this->db->get_row("SHOW INDEX FROM " . $this->db->users . " WHERE Key_name = 'user_login_key' AND Non_unique = 1");

        if (is_object($userLoginIndex) && !empty($userLoginIndex)) {

            //Remove old index
            $this->db->query("ALTER TABLE " . $this->db->users . " DROP INDEX user_login_key");

            //Add new index
            $this->db->query("ALTER TABLE " . $this->db->users . " ADD UNIQUE user_login_key (user_login);");
        }
    }
1050224
public function createAnonymousUser()
    {
        $now = Date::factory('now')->getDatetime();

        // The anonymous user is the user that is assigned by default
        // note that the token_auth value is anonymous, which is assigned by default as well in the Login plugin
        $db = $this->getDb();
        $db->query("INSERT IGNORE INTO " . Common::prefixTable("user") . "
                    VALUES ( 'anonymous', '', 'anonymous', 'anonymous@example.org', '', 'anonymous', 0, '$now', '$now' );");
    }
954772
static function forceLogin(\Db\Connection $db, $user_id) {
    User::$instance = User::findUser($db, $user_id);
  }
691070
function usernameIsUnique ( id ) {
        var deferred = q.defer();

        db.users.query( [ { key: 'identities.basic.username', cmp: '=', value: user.identities.basic.username } ] ,
            { limit: 1, skip: 0 } ).then(
                function ( payload ) {
                    if ( payload.total === 0 ) {
                        deferred.resolve();
                    }
                    else if( !_.isUndefined( id ) && payload.results[0]._id.toString() === id.toString() ) {
                        deferred.resolve();
                    }
                    else {
                        deferred.reject( new Error(messages.duplicate_username) );
                    }
                },
                function ( err ) {
                    deferred.reject( err );
                }
            );

        return deferred.promise;
    }
299614
public function actionUserNameToFirstName()
    {
        if (!CmsUser::find()->count()) {
            $this->stdout("Content not found!\n", Console::BOLD);
            return;
        }

        $this->stdout("1. Cms user name normalize!\n", Console::FG_YELLOW);

        /**
         * @var CmsUser $cmsUser
         */
        foreach (CmsUser::find()->orderBy(['id' => SORT_ASC])->each(10) as $cmsUser) {
            $this->stdout("\t User: {$cmsUser->id}\n", Console::FG_YELLOW);

            if (!$cmsUser->_to_del_name) {
                $this->stdout("\t NOT found property: _to_del_name\n", Console::FG_YELLOW);
                continue;
            }

            $name = $cmsUser->_to_del_name;
            $nameData = explode(" ", $name);

            if (isset($nameData[0])) {
                $cmsUser->first_name = trim($nameData[0]);
            }

            if (isset($nameData[1])) {
                $cmsUser->last_name = trim($nameData[1]);
            }

            if (isset($nameData[2])) {
                $cmsUser->patronymic = trim($nameData[2]);
            }


            if ($cmsUser->save()) {
                $this->stdout("\t Updated name: {$cmsUser->name}\n", Console::FG_GREEN);
            } else {
                $this->stdout("\t NOT updated name: {$cmsUser->id}\n", Console::FG_RED);
            }
        }
    }
265118
public function setUsername(string $username): void
	{
		if (Strings::match($username, '/[^A-Za-z0-9_]/')) {
			throw new InvalidArgumentException('Username contains invalid characters');
		}

		/* @var $repository UsersRepository */
		$repository = $this->getRepository();
		$user = $repository->getByUsername($username);
		if ($user !== null && $user !== $this) {
			throw new UniqueConstraintViolationException("Username '$username' exists");
		}
		$this->username = $username;
	}
107129
public function setUsername($value)
    {
        $this->assertValidString($value, false);

        $this->username = $value;
        if ($this->username !== '') {
            $this->flags |= 64;
        } else {
            $this->flags &= ~64;
        }
    }
480894
public function createUsername($username)
    {
        if (!$this->hasEnabledUsername()) {
            return null;
        }
        $usernameClass = $this->usernameClass;
        $model = $usernameClass::findOne($this->getGUID());
        if (!$model) {
            $model = $this->create($usernameClass);
            $model->setGUID($this->getGUID());
        }
        $model->content = $username;
        return $model;
    }
180020
public function getUsername() : ?string 
    {
        if ( ! $this->hasUsername()) {
            $this->setUsername($this->getDefaultUsername());
        }
        return $this->username;
    }
1004967
public function username($username)
    {
        $app = Application::getFacadeApplication();
        $validator = $app->make('validator/user/name');
        foreach ($validator->getValidators() as $handle => $validator) {
            if ($handle !== 'unique_username') {
                if (!$validator->isValid($username)) {
                    return false;
                }
            }
        }

        return true;
    }
1328835
public function setUsername($username = '')
    {
        $this->username = $username;
        $this->_debug->info(__FUNCTION__, 'setUsername: ', $this->username);
    }
1103260
protected function setUser() {
		if (!empty($this->getSiteConfig()['USER_CLASS'])) {
			$className = "{$this->getSiteConfig()['NAMESPACE_APP']}Classes\\Data\\{$this->getSiteConfig()['USER_CLASS']}";
			if (class_exists($className)) {
				$this->setGlobalUser(new $className());
			} else {
				$this->getLogger()->error("Configured User class not found: {$className}");
			}
		} else if (isset($this->getSiteConfig()['USECAS']) && $this->getSiteConfig()['USECAS']) {
			$this->setGlobalUser(new Data\UserCAS($this->getSanitizedInputData(),$this->getDataRepository('Users')));
		} else {
			$this->setGlobalUser(new Data\UserDB());
		}
	}
569185
def change_username(self, username):
        
        username = username.lower()
        if self.username != username:
            if self.get_by_username(username):
                raise exceptions.AuthError("Username exists already")
            self.update(username=username)
802031
def username(self, value):
        """"""
        if isinstance(value, str):
            self._username = value
            self._handler = None
325798
public function setUsername($v)
    {
        if ($v !== null) {
            $v = (string) $v;
        }

        if ($this->username !== $v) {
            $this->username = $v;
            $this->modifiedColumns[UserTableMap::COL_USERNAME] = true;
        }

        return $this;
    }
664390
protected function setTitleEditUser()
    {
        if (isset($this->data_user['name'])) {
            $title = $this->text('Edit %name', array('%name' => $this->data_user['name']));
        } else {
            $title = $this->text('Add user');
        }

        $this->setTitle($title);
    }
1277039
public function setUsername($username)
    {
        if (preg_match(self::PATTERN_MATCH_USERNAME, $username) !== 1) {
            throw new \InvalidArgumentException('"' . $username . '" is not a valid username.', 1184071238);
        }

        $this->username = $username;
    }