Drupal 7 change default user login functionality
I had a similar functionality in a project a while ago and I solved it by adding a validation handler and doing the check in that.

function mymodule_form_alter(&amp;$form, &amp;$form_state, $form_id) {
  // Replace the drupal authenticate function is it's used as validation.
  if (isset($form['#validate']) &amp;&amp; is_array($form['#validate']) &amp;&amp; ($key = array_search('user_login_authenticate_validate', $form['#validate']))) {
    $form['#validate'][$key] = 'mymodule_login_authenticate_validate';
  }
}

function mymodule_login_authenticate_validate($form, &amp;$form_state) {
  // Set 
  $account = mymodule_authenticate($form_state);
  if ($account) {
    $form_state['uid'] = $account-&gt;uid;
  }
}


function mymodule_authenticate($form_state) {
  // Your magic code here
  // In my project I either created a new user or updated an existing user and set $account as that.

  // And if everything went well in your code, finalize login and return account
  user_login_finalize($form_state['values']);
  return $account;
}