Monthly Archives: January 2010

Drupal: Redirecting a User After Login

This has me beating my head on the desk a bit. I’m coding up a Drupal 6 module, and wanted to redirect the user after logging in, depending on what role they belong to.

In this example, let’s say I have a role called “treasurer” – and anyone that’s logged in and not a treasurer is an administrator. In my module (called mymod here), I knew that hook_user would do the trick somehow. Note that in hook_user, the $op variable contains what operation is being performed, and “login” is an option we can use here. So, this will fire right after the login form is processed and the user is loaded. The $account variable contains the entire $user object being worked on (so we can use it instead of a “global $user” declaration). Here’s what I originally wanted to do but it does not work:

function mymod_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'login':
      if (in_array('treasurer', $account->roles)) {
        drupal_goto('user/' . $account->uid);
      } else {
        drupal_goto('admin/users');
      }
      break;
    default:
      // nothing
      break;
  }
}

We can’t  use drupal_goto here, surprisingly. But after a little Googling, here is the way to do it – this works:

function mymod_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'login':
      if (in_array('treasurer', $account->roles)) {
        $_REQUEST['destination'] = 'user/' . $account->uid;
      } else {
        $_REQUEST['destination'] = 'admin/user/user';
      }
      break;
    default:
      // nothing
      break;
  }
}

In short, we just need to set $_REQUEST['destination'] to whatever we want. In the above example, if the user is a treasurer, we sent them to their user account page. Otherwise, we know that it’s an administrator (since that’s the only other role I set up), and we show the admin all the users. Tailor to your needs. Note that if your destination has a url alias setup, this will automatically fetch the alias too. Cheers.