Refreshing current user’s identity
Nette stores current user’s identity in session. There are a few situations when you want to reload the identity or change it completely. For example, the user updates his profile and you want the change reflected in the page header. Or a super administrator is allowed to re-authenticate as a different user without having to know the other user’s password.
NUser has a convenient method called setIdentity() but unfortunately, it’s declared as private so you can’t use it. The solution is either to loop through the current identity and update its fields one by one, or do it nice and clean with a custom authenticator. Let me show you.
Here’s the looping method. It just does the job.
-
-
$currentIdentity = $this->parent->getUser()->getIdentity();
-
-
foreach ($values as $attribute => $value) {
-
$currentIdentity->$attribute = $value;
-
}
-
And here’s the custom authenticator. One for refreshing updated profile and another one for swapping identities.
-
-
class DummyAuthenticator implements IAuthenticator {
-
return new NIdentity($values[‘id’], null, $values);
-
}
-
}
-
-
// in presenter
-
$user = $this->getUser();
-
$newValues = UserModel::getById($user->getIdentity()->id);
-
$user->setAuthenticator(new DummyAuthenticator);
-
$user->login($newValues);
-
In this example, the authenticator actually does some job – it verifies that the current user is allowed to change his identity. It’s in fact authorization, not authentication, but that’s not the point here.
-
-
class ReAuthenticator implements IAuthenticator {
-
$newUser = UserModel::getById($newUserId);
-
-
return new NIdentity($newUser[‘id’], null, $newUser);
-
}
-
if (($currentIdentity->role == ‘consultant’) && ($newUser[‘role’] == ‘manager’)) {
-
return new NIdentity($newUser[‘id’], null, $newUser);
-
}
-
-
throw new NAuthenticationException("Insufficient permissions.", self::NOT_APPROVED);
-
}
-
}
-
-
// in presenter
-
try {
-
$user = $this->getUser();
-
$user->setAuthenticator(new ReAuthenticator);
-
$user->login($user->getIdentity(), 1234);
-
} catch (NAuthenticationException $e) {
-
…
-
}
-
Tags: Nette Framework 2.0-beta (revision 8a3182e released on 2011-10-11)