PHP-Auth icon indicating copy to clipboard operation
PHP-Auth copied to clipboard

Change username method?

Open turbopixel opened this issue 5 years ago • 4 comments

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?

turbopixel avatar May 26 '19 19:05 turbopixel

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:

  1. Check if the user is already logged in, i.e. whether Auth#isLoggedIn() equals true.
  2. Using Auth#getUserId(), in the database table users, for the row with the relevant user ID, update the column username to store your new value.
  3. 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.

ocram avatar May 26 '19 21:05 ocram

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. image


I think a method like this can implement in the Auth framework. What do you think about this?

turbopixel avatar May 29 '19 20:05 turbopixel

Thanks for trying this and for your feedback!

We will definitely add this feature to the library soon.

ocram avatar May 29 '19 20:05 ocram

I also find the username change function useful.

PhantomArt avatar Jan 29 '21 04:01 PhantomArt