Writing a simple node_access module: resume access

One of the powerful features in Drupal is the node_access system. This is an API within Drupal which allows modules to do fine grained access access contol to individual nodes.

If you are using Drupal core, this system does nothing. You need to either enable one of the many node access modules, or write your own module to do that.

Writing a simple specialized node access module is what this article covers.

Privacy for resumes

The resume_access module is part of the Drupal jobsearch module, which 2bits wrote. In a nutshell, the jobsearch modules allows you to define one or more content types to be job postings (openings, contracts, ...etc), and one or more to be resumes (CVs for those across the pond). Then for the job postings, there is an "apply" link that prompts job candidates to apply to the job.

One request is to make resumes private so job applicants cannot see other job applicants' resumes.

The module we are discussing today is called resume_access, and it does this by using the node_access system.

First we define a permission called "view resumes". Under Roles, you select one or more roles that has the right to see resumes, for example employers, recruiters, ...etc.

function resume_access_perm() {
return array('view resumes');
}

Then, we implement hook_node_grants, and for each job applicant has the right to see their own resumes. We do this by having a grant ID called "resume_owner" and store the uid of the user in it. We also have a grant id called "resume_view" for employers/recruiters.

function resume_access_node_grants($account, $op) {
global $user;

$grants = array();
if ($op == 'view') {
if (user_access('view resumes', $account)) {
$grants['resume_view'] = array(1);
}
$grants['resume_owner'] = array($user->uid);
}
return $grants;
}

The last thing we do is store these grant IDs and the realms in the node_access table. Here is the hook that does that.

function resume_access_node_access_records($node) {
$grants = array();
if (variable_get('resume_node_type_' . $node->type, 0)) {
$grants[] = array(
'realm' => 'resume_view',
'gid' => 1,
'grant_view' => TRUE,
'grant_update' => FALSE,
'grant_delete' => FALSE,
'priority' => 0,
);
$grants[] = array(
'realm' => 'resume_owner',
'gid' => $node->uid ,
'grant_view' => TRUE,
'grant_update' => TRUE,
'grant_delete' => TRUE,
'priority' => 0,
);
}
return $grants;
}

One thing to do after you install a node access module is to rebuild the node access system. Check the README.txt of the jobsearch module for details on how to do this.

The full module can be found in the directory called access when you download the job search module.

And there you have it. Resumes are now private.

Thanks to Earl Miles (merlinofchaos) for his answering questions with the node access system.

Contents: