PHP-Auth
PHP-Auth copied to clipboard
Change username method?
I want to allow my user to login by username. Currently the column 'username' is empty.
How can I change the user name so that the value in the session is also updated?
Good question!
The fact that your username
column is empty means that you didn’t collect and store a username during registration, right?
If you want to let users change (or add) their usernames later, the corresponding feature for this is unfortunately not available yet – but it can be easily added on top of this library.
So if you want to implement changeUsername
(probably as a function in your own application code), you can proceed as follows:
- Check if the user is already logged in, i.e. whether
Auth#isLoggedIn()
equalstrue
. - Using
Auth#getUserId()
, in the database tableusers
, for the row with the relevant user ID, update the columnusername
to store your new value. - Update
$_SESSION[\Delight\Auth\UserManager::SESSION_FIELD_USERNAME]
to store the name value as well – but only if the previous step succeeded, of course.
If you want the newly implemented function to behave like something you would call changeUniqueUsername
instead, you would probably want to copy some code from here.
Hope that helps!
Let’s also leave this issue open until the feature is part of this library itself.
Correct, user can register without a username. The username column are always empty.
So I create a custom method like this:
protected function fieldUsername(string $name) {
if($this->controller->auth->isLoggedIn() !== true){
return NULL;
}
$sql = "UPDATE users SET username = :username WHERE id = :id LIMIT 1";
$this->controller->db->getPdo()->beginTransaction();
$this->controller->db->prepare($sql, [
"username" => $name,
"id" => $this->controller->auth->getUserId()
]);
$_SESSION[UserManager::SESSION_FIELD_USERNAME] = $name;
return $this->controller->db->getPdo()->commit();
}
I missed a session username refresh. Your session key tip is my solution.
So this works well!
Info: PHPStorm marks the method as internal, because the flag @internal
is set in the class description.
I think a method like this can implement in the Auth framework. What do you think about this?
Thanks for trying this and for your feedback!
We will definitely add this feature to the library soon.
I also find the username change function useful.