You can easily check whether a given user should access a certain resource as long as you have that user account at hand. Here, you can encounter two scenarios:
- You want to "interrogate" the current user.
- You want to "interrogate" a given user, not necessarily the current one.
As we saw in Chapter 2, Creating Your First Module, the current user is represented by a service that implements the AccountProxyInterface interface. This service can be accessed by the current_user key or statically with this shorthand:
$accountProxy = \Drupal::currentUser();
From this account proxy we can request the AccountInterface which represents the actual logged-in user account (the UserSession object). It holds a reference to the User entity, with a few of its account-related data, but that is pretty much it. If we need to access its entity fields, we need to load the entity as we normally do:
$user = \Drupal::entityTypeManager()
->getStorage('user')
->load($accountProxy->id());
The resulting UserInterface, by the way, also implements the same AccountInterface, so these common methods can be used on both objects. So, the User entity type is essentially the storage facility for the AccountInterface that represents a user who is browsing the site. However, for the moment, the User entity is not so relevant, so we will get back to the account, which we can retrieve from the proxy, like so:
$account = $accountProxy->getAccount();
The methods on this interface allow us to "interrogate" the account (either the current user account or the one represented by a given User entity) as to its credentials. Also, many of them are also present in the AccountProxy, meaning that you can ask it directly for these.
Two very general but often helpful methods are the following:
$account->isAnonymous(); $account->isAuthenticated();
These check whether the account is anonymous or not, without taking any roles or permissions into account. Sometimes, your access control is solely based on this distinction.
We can also get a list of roles the account has, as follows:
$account->getRoles();
Even more important, check whether the user has a given permission:
$account->hasPermission($permission)
Where $permission is a string (the machine name of the permission as we saw it defined earlier). This method is very helpful because it checks all the roles the user has for the specified permission.
You can use these methods anywhere in your code when you need to check whether a user should be accessing certain parts of your functionality.