How to programmatically set permissions for a custom content type created in a module? I have a module which creates a node type as part of hook_install. I want to be able to automatically set permission to authenticated users to create nodes.

I have tried the following code:   

 /**
  * Implements hook_enable().
  */
function my_module_enable() {
  $permissions = array('create my_module_content_type content');
  user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}


But I receive this error.

Notice: Undefined index: create my_module_content_type content in user_role_grant_permissions() (line 3111 of ...


If I delete the two lines of code, the module installs fine. And when I run those 2 lines of code in an "execute PHP" window after install, they work as desired.

I believe hook_install should execute before hook_enable so the content type should exist when hook_enable is run. Are permissions defined later? Thoughts on how to handle this?
The problem is that the user_permission_get_modules function fails to get the permissions at the point of install (too early in the process, not all the caches have been reset). So you would have to copy the user_role_grant_permissions function to your new module, it should look something like this:

/**
 * Custom user_role_grant_permissions function
 * does the same thing as user_role_grant_permissions
 * but it can run at install time
 * @see user_role_grant_permissions
 * @param int $rid
 * @param array $permissions
 */
function _my_module_grant_permissions($rid, array $permissions = array()) {
    // this line doesn't work on install / enable hooks
    // $modules = user_permission_get_modules();
    // Grant new permissions for the role.
    foreach ($permissions as $module =&gt; $permission_list) {
    foreach ($permission_list as $name) {
        db_merge('role_permission')
        -&gt;key(array(
            'rid' =&gt; $rid,
            'permission' =&gt; $name,
        ))
        -&gt;fields(array(
            'module' =&gt; $module,
        ))
        -&gt;execute();
    }
    }

    // Clear the user access cache.
    drupal_static_reset('user_access');
    drupal_static_reset('user_role_permissions');
}


This is slightly different than the user_role_grant_permissions module in that the permissions are keyed to the module, so you call it like this:

function my_module_enable(){
    $permissions = array(
        // module key
        'my_module' =&gt; array(
           // permissions in the module
           'do module things',
           'modify module things',
        ),
    );
    _my_module_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}