You are hereCustom Authentication for Drupal

Custom Authentication for Drupal


By justin - Posted on 10 February 2010

I recently had a need to write a custom authentication module for Drupal 6. I struggled to find a good example from which to work. As anyone researching the topic knows, Drupal 6 dropped the couple of hooks that were in Drupal 5 that made custom authentication a brainless activity.

It turns out, Drupal 6 isn't all that hard, once you know what to do. The below is my work, which I built after studying the user and the ldap authentication modules. Note that the below code will fail all logins. Why? To save you from yourself. Down towards the end there's a "if (1==1)". Yeap. 100% of all requests hitting this will match, and a return will happen.

To actually make this work, remove that and the return... but then 100% of requests will be valid, assuming there's a valid user in the database. Yes, you probably want to add a database lookup, RADIUS lookup, or something in there somewhere. If you can't figure out where - you probably should not be tampering with Drupal's login code. Just remember - bad logins just return. Good logins return $user.

Yours,

-jbn

<?php
// $Id$

function customauth_form_alter(&$form, $form_state, $form_id) {
  global $user;
  if (isset($form['#validate']) && is_array($form['#validate']) && ($key = array_search('user_login_authenticate_validate', $form['#validate'])))
    $form['#validate'][$key] = 'customauth_login_authenticate_validate';

}

function customauth_login_validators() {
  return array('user_login_name_validate', 'customauth_login_authenticate_validate');

}

function customauth_login_authenticate_validate($form, &$form_state) {
customauth_authenticate($form_state['values']);
}

function customauth_authenticate($form_values = array()) {
  global $user;
  $name = $form_values['name'];
  $pass = trim($form_values['pass']);

  $form_state['values'] = $form_values;
  user_login_name_validate(NULL, $form_state);

  if (form_get_errors())
    return;

  $account = user_load(array('name' => $name, 'status' => 1));
  if (!$account)
    return;

  if (1==1)
    return;

  $user = $account;
  return $user;
}

Tags