Adding the below Changes the username of the user to the portion of the email address before the @ sign.

Thought this might be a good patch to add, too.

(Around line 380)

		if (empty($user->mail)) {
		
			
			$newname = substr	($prevname, 0, strpos($form_state['values']['name'], "@") );
							
			$userinfo = array(
			'name' => $newname,
			'mail' => $form_state['values']['name']
			);
			user_save($user, $userinfo);
		}

Comments

acb’s picture

WHOOPS!

Posted wrong code:

here it is:

But it doesn't work!

It posts the new(shortened) username into the DB, but it seems impossible to log in with the drupal Username, and seems to be setting the password to something random, rather than the password that authenticates from OSCommerce...

Am I missing something? I think it is not so secure to post the username AS email address in the drupal side of the site.

Ideas?

	if (empty($user->mail)) {
		
			
			$newname = substr	($form_state['values']['name'], 0, strpos($form_state['values']['name'], "@") );
							
			$userinfo = array(
			'name' => $newname,
			'mail' => $form_state['values']['name']
			);
			user_save($user, $userinfo);
		}

acb’s picture

OK:

FIXED IT.

Changed a few things:
around line 380

delete this line

//		user_external_login_register($form_state['values']['name'], 'oscommerse_user');

so it reads

	else {

		$newname = substr	($form_state['values']['name'], 0, strpos($form_state['values']['name'], "@") );

		user_external_login_register($newname, 'oscommerse_user');


		//Saving email to reset password later
		if (empty($user->mail)) {
		
			
							
			$userinfo = array(
			'name' => $newname,
			'mail' => $form_state['values']['name'],
			'init' => $form_state['values']['name'],
			'pass' => $form_state['values']['pass']
			);
			user_save($user, $userinfo);
		}

My entire module file (just in case):

<?php
// $Id: oscommerse_auth.module,v 1.1 2010/02/20 18:33:29 enzo Exp $

/**
 * Implementation of hook_help()
 *
 * @param unknown $path
 * @param unknown $arg
 */


function oscommerse_auth_help($path, $arg) {}


/**
 * Implementation of hook_perm()
 *
 * @return unknown
 */
function oscommerse_auth_perm() {
	return array('');
}


/**
 * Implementation of hook_admin()
 *
 * @return unknown
 */
function oscommerse_auth_admin() {
	$form = array();

	$form['oscommerse_auth_settings'] = array(
		'#type' => 'fieldset',
		'#title' => t('OS Commerse DB Settigns'),
		'#description' => t('This information will be use to connect to OS Commerse DB users'),
	);

	$form['oscommerse_auth_settings']['oscommerse_auth_hostname'] = array(
		'#type' => 'textfield',
		'#title' => t('OS Commerse DB Hostname'),
		'#required' => TRUE,
		'#description' => t('oscommerse DB hostname i.e. localhost'),
		'#default_value' => variable_get('oscommerse_auth_hostname', NULL),
	);

	$form['oscommerse_auth_settings']['oscommerse_auth_username'] = array(
		'#type' => 'textfield',
		'#title' => t('OS Commerse DB Username'),
		'#required' => TRUE,
		'#description' => t('oscommerse DB username i.e. root'),
		'#default_value' => variable_get('oscommerse_auth_username', NULL),
	);

	$form['oscommerse_auth_settings']['oscommerse_auth_password'] = array(
		'#type' => 'password',
		'#title' => t('OS Commerse DB Password'),
		'#required' => TRUE,
		'#description' => t('oscommerse DB password i.e. 123456'),
		'#default_value' => variable_get('oscommerse_auth_password', NULL),
	);

	$form['oscommerse_auth_settings']['oscommerse_auth_schema'] = array(
		'#type' => 'textfield',
		'#title' => t('OS Commerse DB Schema'),
		'#required' => TRUE,
		'#description' => t('oscommerse DB schema i.e. oscommerse'),
		'#default_value' => variable_get('oscommerse_auth_schema', NULL),
	);

	return system_settings_form($form);
}


/**
 * Implementation of hook_menu()
 *
 * @return unknown
 */
function oscommerse_auth_menu() {

	$items = array();

	$items['admin/settings/oscommerse_auth'] = array(
		'title' => t('Oscommerce Auth module settings'),
		'description' => t('Oscommerse Configuration options'),
		'page callback' => 'drupal_get_form',
		'page arguments' => array('oscommerse_auth_admin'),
		'access arguments' => array('access administration pages'),
		'type' => MENU_NORMAL_ITEM,
	);

	$items['oscommerse_auth/pass'] = array(
		'title' => t('Reset Password'),
		'description' => t('Reset your password'),
		'page callback' => 'drupal_get_form',
		'page arguments' => array('oscommerse_auth_pass'),
		'access callback' => 'user_is_anonymous',
		'type' => MENU_LOCAL_TASK,
	);

	return $items;
}


/**
 * Implementation of hook_menu_alter.
 * Tell the menu system to use our custom callback rather than the core callback.
 *
 * @param unknown $items (reference)
 */
function oscommerse_auth_menu_alter(&$items) {
	$items['user/password']['page callback'] = 'drupal_get_form';
	$items['user/password']['page arguments'] = array('oscommerse_auth_pass');
}


/**
 * Form builder; Request a password reset.
 *
 * @ingroup forms
 * @see user_pass_validate()
 * @see user_pass_submit()
 * @return unknown
 */
function oscommerse_auth_pass() {
	$form['name'] = array(
		'#type' => 'textfield',
		'#title' => t('Username or e-mail address'),
		'#description' => t('Password will be sent to this email account'),
		'#size' => 60,
		'#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
		'#required' => TRUE,
	);

	$form['#validate'] = array('oscommerse_auth_pass_validate');
	$form['#submit'] = array('oscommerse_auth_pass_submit');
	$form['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));

	return $form;
}


/**
 * Validate if users is a valid user to reset password
 *
 * @param unknown $form
 * @param unknown $form_state
 * @return unknown_type
 */
function oscommerse_auth_pass_validate($form, &$form_state) {
	global $db_url;
	$name = trim($form_state['values']['name']);

	//Check if user requested is oscommerse valid user
	if (is_array($db_url)) {
		$connect_url = $db_url['default'];
	}
	else {
		$connect_url = $db_url;
	}

	$db_type = substr($connect_url, 0, strpos($connect_url, '://'));
	$hostname = variable_get('oscommerse_auth_hostname', NULL);
	$username = variable_get('oscommerse_auth_username', NULL);
	$password = trim(variable_get('oscommerse_auth_password', NULL));
	$schema = variable_get('oscommerse_auth_schema', NULL);

	$db_url = array (
		"default" => $connect_url,
		"oscommerse_auth" => "{$db_type}://{$username}:{$password}@{$hostname}/{$schema}"
	);
	//  echo $db_url;
	db_set_active("oscommerse_auth");
	$result = db_query("SELECT * FROM customers where customers_email_address='%s'", array($name));
	$oscommerse_user = db_fetch_array($result);
	db_set_active("default");

	if (!empty($oscommerse_user)) {
		$account = user_load(array('name' => $name, 'status' => 1));
		$account->type = 'oscommerse_user';
		form_set_value(array('#parents' => array('account')), $account, $form_state);
		return true;
	};

	// Blocked accounts cannot request a new password,
	// check provided username and email against access rules.
	if (drupal_is_denied('user', $name) || drupal_is_denied('mail', $name)) {
		form_set_error('name', t('%name is not allowed to request a new password.', array('%name' => $name)));
	}

	// Try to load by email.
	$account = user_load(array('mail' => $name, 'status' => 1));
	if (!$account) {
		// No success, try to load by name.
		$account = user_load(array('name' => $name, 'status' => 1));
	}
	if (isset($account->uid)) {
		form_set_value(array('#parents' => array('account')), $account, $form_state);
	}
	else {
		form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
	}
}


/**
 * Sent a password reset
 *
 * @param unknown $form
 * @param unknown $form_state
 * @return unknown_type
 */
function oscommerse_auth_pass_submit($form, &$form_state) {
	include "oscommerse_functions.php";
	global $language;

	$account = $form_state['values']['account'];
	if ($account->type == 'oscommerse_user') {
		global $db_url;
		if (is_array($db_url)) {
			$connect_url = $db_url['default'];
		}
		else {
			$connect_url = $db_url;
		}

		$db_type = substr($connect_url, 0, strpos($connect_url, '://'));
		$hostname = variable_get('oscommerse_auth_hostname', NULL);
		$username = variable_get('oscommerse_auth_username', NULL);
		$password = trim(variable_get('oscommerse_auth_password', NULL));
		$schema = variable_get('oscommerse_auth_schema', NULL);

		$db_url = array (
			"default" => $connect_url,
			"oscommerse_auth" => "{$db_type}://{$username}:{$password}@{$hostname}/{$schema}"
		);

		db_set_active("oscommerse_auth");

		$new_password = oscommerse_auth_generatePassword();
		$new_password_encrypt = tep_encrypt_password($new_password);
		$result = db_query("update customers set customers_password='%s' where customers_email_address='%s'", array($new_password_encrypt, $account->mail));

		if ($result) {
			$params['subject'] = t("Password reset");
			$params['body'] = t("Your new password is : ") . $new_password;
			// Mail one time login URL and instructions using current language.
			drupal_mail('oscommerse_auth', 'password_reset', $account->mail, $language, $params);
			//drupal_mail('oscommerse_auth', 'password_reset', 'enzo@excelsoftsources.com', $language, $params);
		} else {
			drupal_set_message(t('Error updating OSCommerse user password'));
			return FALSE;
		}

		db_set_active("default");
	} else {
		$account = $form_state['values']['account'];
		// Mail one time login URL and instructions using current language.
		_user_mail_notify('password_reset', $account, $language);
	}

	watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
	drupal_set_message(t('Further instructions have been sent to your e-mail address.'));

	$form_state['redirect'] = 'user';
	return;
}


/**
 * Implementation of hook_mail()
 *
 * @param unknown $key
 * @param unknown $message (reference)
 * @param unknown $params
 */
function oscommerse_auth_mail($key, &$message, $params) {
	$headers = array(
		'MIME-Version' => '1.0',
		'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
		'Content-Transfer-Encoding' => '8Bit',
		'X-Mailer' => 'Drupal'
	);

	foreach ($headers as $idx => $value) {
		$message['headers'][$idx] = $value;
	}
	$message['subject'] = $params['subject'];
	$message['body'][] = $params['body'];

	//dpr($params);

	watchdog('user', print_r($params, true));

}


/**
 * Implementation of hook_form_alter()
 *
 * @param unknown $form       (reference)
 * @param unknown $form_state
 * @param unknown $form_id
 */
function oscommerse_auth_form_alter(&$form, $form_state, $form_id) {

	//dpr("Form: " . $form_id);


	if ($form_id == 'oscommerse_auth_login_block' || $form_id == 'user_login_block' || $form_id == 'user_login') {
		$hostname = variable_get('oscommerse_auth_hostname', NULL);
		$username = variable_get('oscommerse_auth_username', NULL);
		$schema = variable_get('oscommerse_auth_username', NULL);
		$password = variable_get('oscommerse_auth_password', NULL);

		/*

		if ($form_id == 'oscommerse_auth_login_block' || $form_id == 'user_login_block' || $form_id == 'user_login') {
		$hostname = variable_get('oscommerse_auth_hostname', NULL);
		$username = variable_get('oscommerse_auth_username', NULL);
		$schema = variable_get('oscommerse_auth_schema', NULL);
		$pass = variable_get('oscommerse_auth_forgot', NULL);

	*/

		//Check os commerse setting were set, password is optional
		if ($hostname != '' && $username != '' && $schema != '' && $password != '') {

			//  if($hostname != '' && $username != '' && $schema != '' ){
			if (isset($form_state['post']['name'])) {
				$form['#validate'] = array('oscommerse_auth_validate');
			}
		} else {
			drupal_set_message( 'OSCommerse Auth ' . t("module wasn't configured"));
		}
	}
}


/**
 * Custom function to validate against oscommerse
 *
 * @param unknown $form
 * @param unknown $form_state
 * @return unknown_type
 */
function oscommerse_auth_validate($form, &$form_state) {
	include "oscommerse_functions.php";
	global $db_url, $user;

	if (is_array($db_url)) {
		$connect_url = $db_url['default'];
	}
	else {
		$connect_url = $db_url;
	}

	$db_type = substr($connect_url, 0, strpos($connect_url, '://'));
	$hostname = variable_get('oscommerse_auth_hostname', NULL);
	$username = variable_get('oscommerse_auth_username', NULL);
	$password = trim(variable_get('oscommerse_auth_password', NULL));
	$schema = variable_get('oscommerse_auth_schema', NULL);

	$db_url = array (
		"default" => $connect_url,
		"oscommerse_auth" => "{$db_type}://{$username}:{$password}@{$hostname}/{$schema}"
	);

	db_set_active("oscommerse_auth");
	$result = db_query("SELECT * FROM customers where customers_email_address='%s'", array($form_state['values']['name']));
	$oscommerse_user = db_fetch_array($result);
	db_set_active("default");

	if (!tep_validate_password($form_state['values']['pass'], $oscommerse_user['customers_password'])) {
	
		user_login_authenticate_validate($form, &$form_state);
		
		if (!$user->uid) {
		
			form_set_error('name', t('The E-Mail Address or password was not found in our records.  Please try again or <a href="@password">click here to request a new password.</a>', array('@password' => url('user/password'))));
			
			watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
			return FALSE;
		}
		
		return TRUE;
	}
	
	
	else {
//		user_external_login_register($form_state['values']['name'], 'oscommerse_user');

			$newname = substr	($form_state['values']['name'], 0, strpos($form_state['values']['name'], "@") );

		user_external_login_register($newname, 'oscommerse_user');
		//Saving email to reset password later
		if (empty($user->mail)) {
		
			
			$newname = substr	($form_state['values']['name'], 0, strpos($form_state['values']['name'], "@") );
							
			$userinfo = array(
			'name' => $newname,
			'mail' => $form_state['values']['name'],
			'init' => $form_state['values']['name'],
			'pass' => $form_state['values']['pass']
			);
			user_save($user, $userinfo);
		}

		//Example about how link this module to other modules
		/*if(module_exists('profile')){
 			$edit = array('profile_first_name'=> $oscommerse_user['customers_firstname'],'profile_last_name'=>$oscommerse_user['customers_lastname']);
 			profile_save_profile(&$edit, &$user, 'Personal Information');
 		}*/

		user_authenticate_finalize($form_state['values']);
	}

	//Call to custom extra process function
	oscommerse_auth_extra_process($oscommerse_user, $form_state);
	return TRUE;
}


/**
 * Function to process user after auth with oscommerse, options like set a role or similar
 * This function must be extend by end user
 *
 * @return unknown_type
 * @param unknown $oscommerse_user
 * @param unknown $form_state
 */
function oscommerse_auth_extra_process($oscommerse_user, $form_state) {
	global $user;
}


/**
 *
 *
 * @param unknown $length   (optional)
 * @param unknown $strength (optional)
 * @return unknown
 */
function oscommerse_auth_generatePassword($length=9, $strength=0) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength & 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 2) {
		$vowels .= "AEUY";
	}
	if ($strength & 4) {
		$consonants .= '23456789';
	}
	if ($strength & 8) {
		$consonants .= '@#$%';
	}

	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}


/**
 * Implementation of the block hook
 * This is merely optional and just for kidssoup
 *
 * @param <type>  $op
 * @param <type>  $delta
 * @param <type>  $edit
 * @return <type>
 */
function oscommerse_auth_block($op='list', $delta=0, $edit=array()) {
	switch ($op) {
	case 'list':
		$blocks[1] = array(
			'info'       => t('OS Commerse custom block login'),
			'cache'  => BLOCK_NO_CACHE,
			'status'     => TRUE,
			'weight'     => -10,
			'visibility' => 1,
			'region'     => 'header');
		return $blocks;
	case 'view':
		switch ($delta) {
		case 1:
			$blocks['subject'] = ''; // Block without title
			$blocks['content'] = drupal_get_form('oscommerse_auth_login_block');
			break;
		}

		return $blocks;
	}
}


/**
 *
 *
 * @return unknown
 */
function oscommerse_auth_login_block() {

	$form['name'] = array('#type' => 'textfield',
		'#title' => t('Username'),
		'#maxlength' => USERNAME_MAX_LENGTH,
		'#size' => 15,
		'#required' => TRUE,
	);
	$form['pass'] = array('#type' => 'password',
		'#title' => t('Password'),
		'#maxlength' => 60,
		'#size' => 15,
		'#required' => TRUE,
	);
	$form['submit'] = array('#type' => 'submit',
		'#value' => t('Log in'),
	);

	return $form;
}