External login , in case internal login fail I have a website which needs to authenticate users using drupal users table.

If authentication fails, then I want to run the authentication against users table from another database. 

lf authentication is successful , then I want to register this user inside drupal, so the next this user next time he logs in , he get authenticated from drupal users table , not the external users table. 

I wish to get a complete solution for that.

the following code is my attempt :

function external_auth_form_user_login_alter(&amp;$form,$form_state){

$form['#validate'] = array( 'user_login_name_validate' );
user_login_authenticate_validate( $form, $form_state );
if(!empty($form_state['uid'])){

db_set_active('barakah');
$result=db_query('select username,password from users where username= :name   and password= :pass',array(':name' =&gt;$form_state['input']['name'],':pass'=&gt;$form_state['input']['pass']));
db_set_active('default');
if(!empty($result)){
$username = $form_state['input']['name'];
user_external_login_register($username, 'external_auth');

}




} 

}


but as if the code doesn't exist, nothing happens
You can use:

drupal_external_login_register


  Helper function for authentication modules. Either logs in or
  registers the current user


An example implementation is detailed here:

https://api.drupal.org/comment/13434#comment-13434