6

I am using drupal 6, and I have created a custom module. This module consists of a form that can be used for adding records to the database.

But I saw that the link to this form (http://localhost/drupal/my_module/form) is accessible to all the users, even anonymous users.

I want to restrict the access to this module and form from all the normal users. I want only the administrator to access it.

I have created a role called Administrator and permitted my module only for the administrator. It still doesn't work.

How can I restrict the access to my custom module ?

| improve this question | | | | |
8
  1. Declare a permission with hook_perm(). It is recommended to somehow use your module name in the permission or something unique to your module to avoid conflicts (there is no namespacing, permission names are global).

  2. In your hook_menu() implementation, add 'access arguments' => array('permission name here'). Since the default access callback is user_access(), the menu system will call user_access('your permission name') to check if the current user has access to that menu item. See hook_menu() documentation for more information. You can also use user_access() directly in your code, if you want to check permissions somewhere else; for example for blocks, you can use that function directly.

  3. Then, you can create whatever roles you want to and give them the permissions of your module at admin/user/permissions. The important distinction here is that permissions are controlled in modules (which can be more or less generically written) while roles and the permissions they have are site-specific.

Then, make sure to rebuild the menu (by using devel.module or saving the modules form) and you should be good.

| improve this answer | | | | |
  • Thanks, in my hook_perm() method, i am returning permission like: return array('admin_only'); and in my form generation code, i checked it like this: if(user_access('admin_only')) return $form; – shasi kanth May 31 '11 at 12:40
  • 3
    @dskanth When the full form should not be visible to users without the right permission, it's rather better to use the access arguments in hook_menu() as reported by Berdir, than conditionally return the form array basing on the user's permissions. – kiamlaluno Jun 30 '11 at 3:41
  • I'd put it more strongly than this. Using the access control provided by hook_menu is the right way to do it and you should avoid performing access control checks in callbacks. They make your code less flexible and harder to integrate with other modules. – Alfred Armstrong Apr 16 '13 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.