How to get details of logged in user with Identity

+
0
-

I understand that the Identity is returned from my class MyAuthenticator which implements NS\IAuthenticator.

I can get the user id of the logged in user with $this->getUser()->getId() however,
I cannot get the username of the logged in user with $this->getUser()->getIdentity()->username.

Is there something in the authenticator which needs to be loaded to populate the identity?

My Authenticator is shown here:

<?php

namespace App\Model\SiteAuthenticator;

use \Nette\Security\IIdentity;
use \Nette\Security\Passwords;
use \Nette\Security\IAuthenticator;

class SiteAuthenticator implements IAuthenticator
{
        public function __construct(\Nette\Database\Context $database, \Nette\Security\Passwords $passwords)
        {
                $this->database = $database;
                $this->passwords = $passwords;
        }

        public function authenticate(array $credentials): \Nette\Security\IIdentity
        {
                [$username, $password] = $credentials;

                $row = $this->database->table('users')
                        ->where('username', $username)->fetch();

                if (!$row) {
                        throw new \Nette\Security\AuthenticationException('User not found.');
                }

                if (!$this->passwords->verify($password, $row->password)) {
                        throw new \Nette\Security\AuthenticationException('Invalid password.');
                }

                return new \Nette\Security\Identity($row->id, ['username' => $row->username]);
        }
}
?>
n3t
Member | 37
+
+2
-

Second parameter in \Nette\Security\Identity constructor is roles, not data, change it like this

return new \Nette\Security\Identity($row->id, null, ['username' => $row->username]);
+
0
-

n3t wrote:

Second parameter in \Nette\Security\Identity constructor is roles, not data, change it like this

return new \Nette\Security\Identity($row->id, null, ['username' => $row->username]);

Still does not give me the username.
Am I doing something (many somethings) wrong in the presenter?
The ID works fine.

<?php
        public function renderDefault()
        {
                $this->template->title = "User Admin";
                $this->template->username = $this->getUser()->getIdentity()->username;
                $this->template->id = $this->getUser()->getId();
        }
?>

dump of getIdentity()

Nette\Security\Identity
id private => 1
roles private =>
    username => "admin" (5)
data private =>
    nickname => null
    username => null

Last edited by kevin.waterson@gmail.com (2019-12-10 13:43)

MajklNajt
Member | 494
+
+1
-

have you tried to re-login, because identity is saved in sessions…

+
0
-

MajklNajt wrote:

have you tried to re-login, because identity is saved in sessions…

Ahh, that got it. Thanks.