Issue
This Content is from Stack Overflow. Question asked by Rick
I have a dashboard controller where I show the dashboard to users who are not anonymous. My controller code is as below:
class DashboardController extends ControllerBase {
protected $currentUser;
/**
* {@inheritdoc}
*/
public function __construct(AccountProxy $current_user) {
$this->currentUser = $current_user;
}
//HERE IS WHERE THE PROBLEM IS. FOR NON-ADMIN USERS, THE USERID IS RETURNED AS 0
public function access(AccountInterface $account) {
dd($this->currentUser);
if (!$this->currentUser->isAuthenticated()) {
return AccessResult::forbidden();
} else {
return AccessResult::allowed();
}
//FUNCTION TO DISPLAY DASHBOARD
public function accessDashboard(AccountInterface $account) {
$current_user = $this->currentUser;
$roles = $current_user->getRoles();
$current_user_record = DrupaluserEntityUser::load($current_user->id());
if (!$current_user->isAuthenticated()) {
return AccessResult::forbidden();
}
if ($current_user->hasPermission('view school dashboard')) {
//SHOW THE ASSOCIATED SCHOOL NAMES DASHBOARD
}
return AccessResult::forbidden();
}
}
Screenshot of what I see when logged in as a non-admin user:
When logging in as an Administrator, I can clearly see the user ID and details as below:
any help on how to handle this problem?
Solution
In Drupal, if a visitor/user not logged in (Anonymous User) then they will share the UID of 0.
You can find this from the below doc:
Drupal – User Documentation
Also, in your first screenshot the object you dump is of AnonymousUserSession which is the implementation representing anonymous users. So I think there are no authenticated users yet.
Drupal – Class AnonymousUserSession
This Question was asked in StackOverflow by Rick and Answered by Harish ST It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.