MyBB Community Forums

Full Version: [Tutorial] EZ Fast Login | (SSO Integration) | Force Login To MyBB
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Most of this code is originally from MyBB 1.4, but does work in 1.6
  • You can use it to (force) login to MyBB as someone is logging into your other system/script/CMS, etc.
  • Works anywhere you are able to include ' mybb/global.php '

Please note: I'm not an expert on avoiding conflicts with your other script. I use this code with SSL and encrypted tokens, and those subjects are beyond the purpose of this tutorial.


// !! Use w/ caution this logs a user in without a password
// auth is already done above
// You now have the MyBB username currently stored in  $name

define('IN_MYBB', 1);
// Modify path here for your needs:
require_once './global.php';  

$query = $db->simple_select("users", "uid,username,password,salt,loginkey,email,usergroup", "username='$name'", array('limit' => 1));
$user = $db->fetch_array($query);
my_setcookie('loginattempts', 1);
		$db->delete_query("sessions", "ip='".$db->escape_string($session->ipaddress)."' AND sid != '".$session->sid."'");
		$newsession = array(
			"uid" => $user['uid'],
		);
		$db->update_query("sessions", $newsession, "sid='".$session->sid."'");
		
		$db->update_query("users", array("loginattempts" => 1), "uid='{$user['uid']}'");
		
		// Temporarily set the cookie remember option for the login cookies
		$mybb->user['remember'] = $user['remember'];
	
		my_setcookie("mybbuser", $user['uid']."_".$user['loginkey'], null, true);
		my_setcookie("sid", $session->sid, -1, true);
	
	 	$plugins->run_hooks("member_do_login_end");

// Modify below here for your needs:
      //  $user= $user['username'];
     header( "Location: enter_here.php?return=$return&status=hello" ) ; 
     header ("Content-Length: 0");
     exit;


#
Edit:
  • This (above) shows SSO Integration (Single-Sign-On), but doesn't cover integration (syncing) of both user tables in your database.
  • For basic use: You could have a small group of Admins/Editors who can log into your CMS (and this code gives them SSO into MyBB forum), while everyone else logs in normally to your forum.
  • For advanced applications: Anyone with a matching username in "YourCMS" can instantly login to your MyBB forums.


##
Feel free to ask questions, but sometimes my answer might be "it works figure it out". Toungue
Can this work with 2 mybb forums?
Awesome thanks for this. I have been suffering periodic log outs and was looking at a move to myBB this means I should be able to quickly make that happen
(2012-07-26, 08:02 PM)mobert Wrote: [ -> ]Can this work with 2 mybb forums?

Yes, certainly.

(2012-07-27, 01:27 AM)Dannymh Wrote: [ -> ]Awesome thanks for this. I have been suffering periodic log outs and was looking at a move to myBB this means I should be able to quickly make that happen

You are welcome. Smile
Ok so how can I get this to work with two forums? Where would I place this code?

(newbie here)
Hi mobert,
Simple answer:*
In the root folder of the forum you want to "force" an easy SSO login, you would name a file 'sso.php' (for example), and in that file you would include the code from the tutorial.

*See below

(2012-07-28, 05:46 AM)mobert Wrote: [ -> ]Ok so how can I get this to work with two forums? Where would I place this code?

(newbie here)

If it was that easy all the newbies would be doing it. Toungue

#
Real Answer:
You need to securely make sure the user is already logged into the other forum/cms/script.
// auth is already done above
// You now have the MyBB username currently stored in  $name

Quote:I use this code with SSL and encrypted tokens, and those subjects are beyond the purpose of this tutorial.

There are no really easy answers (SSO is hard), but this solution is relatively simple** so "EZ" is in the title.
**This solution is 'very easy', but you need a way to be certain the user is already logged in:


##
Other info:
*Passing sensitive data (passwords, for example) in the url is usually not a good idea, and only possible with SSL. (still not a great idea, even with SSL, >>> plus this solution logs someone in without a password since auth is already done, either "above" or previously)
*Using SSL and encrypted tokens is really fun, but not for most "newbies."
*The other option is to have the same file (sso.php) also log the person into the other target/forum/CMS.

Have fun Smile
I have been using jfusion with joomla to achieve my dual login, however the jfusion login flakes out a fair bit.

I am looking at ways to integrate the login so that Joomla natively logs in and mybb authenticates as well.

I think I may need to lift all of the login and authentication and session handling from mybb and write it into a plugabble login for Joomla

Basically including global.php is not really a suitable solution. There needs to be a better way to touch this. Ideally when version 2 comes out there will be an authentication system that can be plugged directly into another website.

i.e. I can call just a single "mybb_login_api.php" which will allow me to just use this code and function set to authentication. With the option to include the DB class. The important thing is that in most cases this is the only main integration point most sites need

Ive stripped this out into a Joomla authentication plugin, going to now modify it to check the username, password and salting, though it should theoretically be somewhat secure, i.e. if you are logged into Joomla it then triggers this, so you are only ever going to get in on a successful login.

Last time I messed around getting the salts I became a little frustrated, but I should be able to make an adaptation of it at least
(2012-07-30, 12:27 AM)Dannymh Wrote: [ -> ]I have been using jfusion with joomla to achieve my dual login...

Setting MyBB as master then (dual) logging in through Joomla used to work fine, but I haven't tested the newest versions. jFusion doesn't support username changes, so that was a strong reason to stop using it.


#
Last time I messed around getting the salts I became a little frustrated...
Yes, diving into the details is one way to learn why so many people avoid SSO.
I find Jfusion sufferes from random logouts and other oddities. I will be also looking into making a wordpress dual login after this as well.

So I didn't have much of a chance to work on this today, but have been able to do the following (I will break this out to a new thread soon).

So I altered the queries for Joomla and this is my login functions

- Set Cookie function
function mybb_setcookie($name, $value="", $expires="", $httponly=false)
	{
		$db = JFactory::getDBO();

		$mybbcookiepath = $this->mybb_get_setting('cookiepath');
		$mybbcookiedomain = $this->mybb_get_setting('cookiedomain');
		$mybbcookieprefix = $this->mybb_get_setting('cookieprefix');

		//echo "cookie: ".$mybbcookiepath;
		//exit;

		if($expires == -1)
		{
			$expires = 0;
		}
		elseif($expires == "" || $expires == null)
		{
			$expires = TIME() + (60*60*24*365); // Make the cookie expire in a years time
		}
		else
		{
			$expires = TIME() + intval($expires);
		}

		$mybbcookiepath = str_replace(array("\n","\r"), "", $mybbcookiepath);
		$mybbcookiedomain = str_replace(array("\n","\r"), "", $mybbcookiedomain);
		$mybbcookieprefix = str_replace(array("\n","\r", " "), "", $mybbcookieprefix);

		// Versions of PHP prior to 5.2 do not support HttpOnly cookies and IE is buggy when specifying a blank domain so set the cookie manually
		$cookie = "Set-Cookie: {$mybbcookieprefix}{$name}=".urlencode($value);

		if($expires > 0)
		{
			$cookie .= "; expires=".@gmdate('D, d-M-Y H:i:s \\G\\M\\T', $expires);
		}

		if(!empty($mybbcookiepath))
		{
			$cookie .= "; path={$mybbcookiepath}";
		}

		if(!empty($mybbcookiedomain))
		{
			$cookie .= "; domain={$mybbcookiedomain}";
		}

		if($httponly == true)
		{
			$cookie .= "; HttpOnly";
		}
		
		$mybb->cookies[$name] = $value;

		header($cookie, false);
	}

login function
function mybb_log_me_in($name, $password)	{
		$db = JFactory::getDBO();
		// !! Use w/ caution this logs a user in without a password
		// auth is already done above
		// You now have the MyBB username currently stored in  $name

		$query = "select uid,username,password,salt,loginkey,email,usergroup from mybb_users where username='".$name."' limit 1";
		$db->setQuery($query);
		$user = $db->loadRow();

		
		if(md5(md5($user[3]).md5($password))== $user[2])	{
			// The password matches the password in the database so lets log them in
			$this->mybb_setcookie('loginattempts', 1, null);			
			
			$db->setQuery("Delete from mybb_sessions where ip='".$_SESSION['IPADDR']." AND sid !='".session_id()."'");
			$result = $db->query();
			
			$newsession = array(
				"uid" => $user['uid'],
			);
			
			$db->setQuery("Update mybb_sessions set uid=".$user[0]." where sid='".session_id()."'");
			$result = $db->query();
			if(!$result)	{
				echo $db->getErrorMsg()."<br/>";
				exit;
			}

			//$db->setQuery("Updaye mybb_users set uid=".$user['id']." where sid='".$session->sid."'");
			//$result = $db->query();
			//$db->update_query("users", array("loginattempts" => 1), "uid='{$user['uid']}'");

			//Skipped above 3 lines, this just increases the login attemps by 1, however given we are succesful in our Joomla login we shouldn't need this

			// Temporarily set the cookie remember option for the login cookies
			//$mybb->user['remember'] = $user['remember'];

			$this->mybb_setcookie("mybbuser", $user[0]."_".$user[4], null, true);
			$this->mybb_setcookie("sid", session_id(), -1, true);
		}
	}

- small function to grab myBB settings by name
function mybb_get_setting($setting)	{
		$db = JFactory::getDBO();
		$db->setQuery("select value from mybb_settings where name='".$setting."'", 'mybb_');
		$result = $db->loadResult();
		//echo "Query: select value from mybb_settings where name='".$setting."' result: ".$result[0]." <br>";
		if(!$result)	{
			echo $db->getErrorMsg()."<br/>";
		}
		return $result;
	}

As you can see I added a salt check, it really shouldn't be needed as if you are authenticated with Joomla you should be authenticated with mybb, however adding an extra security layer never really hurt anyone. (I forgot about Joomla not using named arrays in the loadRow() query eek.

Of course this all assumes the tables for myBB and Joomla are in the same database, and assumes that the table prefix for mybb is mybb_

None of this will work without calling the $this->mybb_log_me_in($credentials['username'], $credentials['password']);

Which I am doing inside the joomla.php auth script in the onAuthenticate area, you call it where the success messsage is and you should be good to go.

I need to write all of this into a proper user plugin for joomla with parameters for setting the table prefix and I need to fix the "remember me" stuff.

I will package it with a user function and a sync system if I get the chance that can be called on registration on Joomla side and also on changing passwords so that they are properly inserted on both sides, name change really shouldn't matter, if data is pushed from both tables it really is no big deal. I have already written this for my site and jFusion anyway.

After I am done with that I will write one for the myBB side so that the login system of myBB also logs you into Joomla and does all of the same actions as above. I believe that way for most people all bases will be covered for the user integration and login systems and we can break the need for jFusion.

After all that is complete I will adapt the scripts to wordpress and we should have a system that works for good user integration in both and we can expand them later to synch and manage profiles better.

Of course if the interest is not there I will keep them to myself Smile

I couldn't have really gotten to this point without your code above, so for that I thank you.

Dan

Oh additionally once I have completed all this work, it should be pretty simple for anyone to adapt this to other systems and CMS, in fact I should be able to help with that, once I go through the learning curve.

The hardest part is getting the right cookies set correctly and handling the password to make sure they are all correctly hashed. However that should be relatively simple information to find out I would imagine. My coding style is not too formal but it is effective enough.
(2012-07-31, 06:56 AM)Dannymh Wrote: [ -> ]...

Of course if the interest is not there I will keep them to myself Smile

I couldn't have really gotten to this point without your code above, so for that I thank you...

Glad you are making progress Dan.
Yes, please release it when you're ready; There will be plenty of people interested especially with both Wordpress and Joomla.
I'll help test it too...


#
My over-all approach is "too custom" for most people. (i.e. SSL is required on the master site, plus I try to avoid storing/using passwords more than one place and just "force an EZ login" everywhere else. For security I like to use encrypted tokens that expire after a few seconds, generated after login to the master is confirmed.)
Pages: 1 2