1

I thought it would be simple to do, but after lots of searching I couldn't find exact solution for it.

So the issue is, I have 2-3 main menu items which I have to show to anonymous users but have to call a URL(for login/register popup) & prompt for login or register if they click on them.

Best solution I found for create content link "node/add/node-type" was something like --

function THEME_preprocess_page(&$vars, $hook) {
    global $user;
    # if url starts with "add" and current user is anonymous
    if (arg(1) === 'add' && $user->uid === 0) {
          # redirect to login page
          drupal_goto('user/login');
          exit;
    }
}

It didn't work & it says - "$base_path has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer."

This is a very important functionality thing & I don't know how people resolve it. Can I get any suggestion for it ?

0

You can use hook_node_access for that.

Of course it's not a turn-key solution, but I'm sure this example will help anyone who will face this kind of issues.

Example:

/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access($node, $op, $account) {

  // define restricted node id's
  $restricted_nids = array(7,27);

  // If $node is a string, the node has not yet been created. We don't care
  // about that case.
  // Check permissions only for restricted nids.  
  if (!is_string($node) && in_array($node->nid, $restricted_nids) && $op == 'view') {

    global $user;

    // OPTION #1
    // Give an access if they have ANY of these roles.

    //$has_permission = array_intersect(array('testrole', 'testrole2'), array_values($user->roles));
    //return $has_permission ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;

    // OPTION #2
    // Give an access if they have ALL of required roles.   

    $required_roles = array('testrole', 'testrole2');
    $has_permission = (count(array_intersect($user->roles, $required_roles)) == count($required_roles)) ? TRUE : FALSE;
    if ($has_permission) {
      return NODE_ACCESS_ALLOW;
    }
    else {
      if ($user->uid) {
        drupal_set_message("You don't have appropriate permission to view this content");
      }
      else {
        drupal_set_message('You have to login to see this content');
        drupal_goto('user/login'); 
      }
      return NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}
1

I had the same problem, and solved it without coding.

  1. Manually set the menu path with absolute URL, ie. http://yourdomain.com/node/add/node-type
  2. Install and enable the module r4032login‎
  3. Done!

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.