How to prevent Login from two places?

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

In your models (User class)

/**
	 * session_validate()
	 * Will check if a user has a encrypted key stored in the session array.
	 * If it returns true, user is the same as before
	 * If the method returns false, the session_id is regenerated
	 *
	 * @param {String} $email	The users email adress
	 * @return {boolean} True if valid session, else false
	 */
	
	public function session_validate(  )
	{

		// Encrypt information about this session
		$user_agent = $this->session_hash_string($_SERVER['HTTP_USER_AGENT'], $this->user_email);
	
		// Check for instance of session
		if ( session_exists() == false )
		{
			// The session does not exist, create it
			$this->session_reset($user_agent);
		}
		
		// Match the hashed key in session against the new hashed string
		if ( $this->session_match($user_agent) )
		{
			return true;
		}
		
		// The hashed string is different, reset session
		$this->session_reset($user_agent);
		return false;
	}
	
	/**
	 * session_exists()
	 * Will check if the needed session keys exists.
	 *
	 * @return {boolean} True if keys exists, else false
	 */
	
	private function session_exists()
	{
		return isset($_SESSION['USER_AGENT_KEY']) && isset($_SESSION['INIT']);
	}
	
	/**
	 * session_match()
	 * Compares the session secret with the current generated secret.
	 *
	 * @param {String} $user_agent The encrypted key
	 */
	
	private function session_match( $user_agent )
	{
		// Validate the agent and initiated
		return $_SESSION['USER_AGENT_KEY'] == $user_agent && $_SESSION['INIT'] == true;
	}
	
	/**
	 * session_encrypt()
	 * Generates a unique encrypted string
	 *
	 * @param {String} $user_agent		The http_user_agent constant
	 * @param {String} $unique_string	 Something unique for the user (email, etc)
	 */
	
	private function session_hash_string( $user_agent, $unique_string )
	{
		return md5($user_agent.$unique_string);
	}
	
	/**
	 * session_reset()
	 * Will regenerate the session_id (the local file) and build a new
	 * secret for the user.
	 *
	 * @param {String} $user_agent
	 */
	
	private function session_reset( $user_agent )
	{
		// Create new id
		session_regenerate_id(TRUE);
		$_SESSION = array();
		$_SESSION['INIT'] = true;
		
		// Set hashed http user agent
		$_SESSION['USER_AGENT_KEY'] = $user_agent;
	}
	
	/**
	 * Destroys the session
	 */
	
	private function session_destroy()
	{
		// Destroy session
		session_destroy();
	}

What will do -

  1. Concatenate the user agent with their email adress and md5 it. This is their secret key, store as unique info as possible.
  2. Compare this key for each request and also just check if a session key is true.

Courtesy - Prevent login from two places