How to limit access to certain users for those who have "administer users" permission EDIT: I have found out how to solve the 'administer users permission needed' problem so I don't really need to know the answer for this. I will not delete the question however, since I would like to know the answer out of curiosity anyway.

Because of this I need to give the permission 'administer users' to everyone while still being able to manage access to individual users (to their view and edit pages as well as to their cancellation).

Therefore I need to restrict users with 'administer users' permission to be able to edit just certain users (based on their id and the id of the user that is to be viewed or edited). (the access function itself is not the problem I already have that one)

I thought about doing something like 'Administer Users by Role' plugin but as it seems there are just too many potential security issues there (the 'administer users permission' is not used only in access to user edit/view but e.g in access to user fields settings page as well.

Any ideas?
The administer users permission is a VERY powerful permission and you shouldn't give this permission anyone that you don't trust. Otherwise, the users with that permission can do all nasty things. For example:


They can manage fields on user accounts at admin/config/people/accounts/fields
They can manage permissions and grant/revoke users including themselves other permissions at admin/people/permissions
They can add/cancel/edit users including admins!


Conclusion: Never, ever give this permission to ANYONE!

There are a few modules that let users granularly administer other users. One of them is the Administer Users by Role. Although, its latest version for Drupal 7 requires to give this mighty permission to the users, but there's a patch, which I also contributed, at this issue page. With this patch, you don't need to give 'administer users' permission to the users and still allow them to administer other users.

There are also other related modules, but I cannot tell anything about them since I don't use them:

Subuser


  This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.


Role Delegation


  This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.