WordPress Sahana Authentication

Quick wordpress plugin to create sahana users on wp using basic authentication requests with curl and authenticate them. Probably this is not the best way to do it, use at your own risk!

<?php

/**
 * @package WP Sahana Authenticate
 * @version 1.0
 */
/*
Plugin Name: WP Sahana Authenticate
Plugin URI:
Description: WP Sahana Authenticate
Author: ratikal
Version: 1.0
Author URI: ratikal.gr
*/

define('SAHANA_URL', 'sahana.installation.url');

function wp_sahana_authenticate_admin_notice()
{
	// only for roles that have dashboard

   	if (isset($_REQUEST['sahana_user_login']))
   		 echo '<div class="notice notice-warning is-dismissible">
             <p>This notice appears on the settings page.</p>
         </div>';
}
add_action('admin_notices', 'wp_sahana_authenticate_admin_notice');

function wp_sahana_authenticate_check_user($username, $password)
{
	$auth = 'Basic '.base64_encode($username.':'.$password);

	$cmd = 'curl -L -X PUT '.SAHANA_URL.' -H \'Authorization: '.$auth.'\'';exec($cmd, $output);

	$html = implode("\n", $output);

	if (strpos($html, '<h2>User Profile</h2>')!==false)
	{
		$first_user_string_position = strpos($html, $username);

		if ($first_user_string_position!==false)
		{
			$last_user_string_position = strrpos($html, $username);

			if ($last_user_string_position!=$first_user_string_position)
				return true;
		}
	}

	return false;
}

function wp_sahana_authenticate_login($user_id)
{
	wp_set_auth_cookie($user_id);
	do_action('wp_login',$user_id);
	header("Location: ".admin_url('?sahana_user_login'));
	die();
}

function wp_sahana_authenticate($username, $password )
{
	if (!empty($username) && !empty($password))
	{
		if (email_exists($username))
		{
			$user = get_user_by('email', $username);

			if (empty(get_user_meta($user->ID, 'IS_SAHANA_USER', true)))
				return new WP_Error( 'authentication_failed', __( '<strong>ERROR</strong>: Invalid username, email address or incorrect password.' ) );
			elseif (wp_sahana_authenticate_check_user($username, $password))
				wp_sahana_authenticate_login($user->ID);
			else
				return new WP_Error( 'authentication_failed', __( '<strong>ERROR</strong>: Invalid username, email address or incorrect password.' ) );
		}
		elseif (wp_sahana_authenticate_check_user($username, $password))
		{
			$password = md5($username.$password.wp_salt());

			$user_id = wp_create_user( $username, $password, $username);

			if (is_wp_error($user_id))
				return new WP_Error( 'authentication_failed', __( '<strong>ERROR</strong>: Invalid username, email address or incorrect password.' ) );

			add_user_meta($user_id, 'IS_SAHANA_USER', 'YES', true);

			wp_sahana_authenticate_login($user_id);
		}
	}

}
add_action('wp_authenticate', 'wp_sahana_authenticate', 30, 2);