A fusion of technology, music, and geekyness.

Peep! A friendly GTD compliant productivity tool for you.


About a year ago Rick (http://www.rickguyer.com) had me read the book Getting Things Done by David Allen. In his book, Allen teaches you how to use his strategies and procedures on managing your tasks (or actions) in a very organized and well thought out fashion. His strategy is unique and calls for a very unique tool to accompany his GTD system. When I originally read his book, Rick and I spent several days searching for a different program, service, or web app that would allow us to incorporate Allen’s GTD system in an electronic fashion. After a solid week of effort I gave up after finding nothing that I felt was easy to use and completely GTD compliant.

Finally, after over a year, we decided to create this perfect GTD compliant web service that will help people, like us, be able to incorporate Allen’s system and become more productive. Peep! is “a simple and easy-to-use tool to help you focus and start getting things done.” I highly suggest you all try it and let me know what you think.

Head over to http://trypeep.com and get started today!


Coming Soon: Peep!

We’ve been working hard at the office lately in efforts to launch a new application that will be aimed towards increasing one’s productivity. The app will follow the principles in the book Getting Things Done by David Allen. Check out the sneak peek below!

peep


Authenticating a CakePHP App Against a CakePHP Webservice

Update 03/27: I fixed the code formatting and added the Cakeservice Behavior

Rick and I figured out a nice solution to having one CakePHP application authenticate a user (and thus acodeessing data) from a different CakePHP application setup as an XML webservice. The authenticating app POSTs an XML string to the web service, which is automatically parsed by CakePHP and put into $this->data. It is then used in a custom xmlLogin() function that uses the Auth Component to log the user in. This solution handles all cookies appropriately so you wont have to worry about much there.

This solution would most likely be better if it were a DataSource instead of a ModelBehavior. We chose a ModelBehavior first because we are not familiar with writing custom data sources yet and wanted a simple, quick, and effective solution. This is a work in progress so I hope to expand on it more later and eventually have it act as a data source instead.

I am assuming:

* You have the latest CakePHP (1.2.1) installed and connected to the database
* You have the Auth Component installed and configured to the defaults
* You have at least one user record with a valid password hash
* You have the XML Helper enabled in your app_controller.php

Step 1: Make CakePHP Act as a Webservice (service side)

1. Add similar code in app/config/routes.php:

Router::mapResources(array('users', 'acodeounts'));
Router::parseExtensions();

2. Add RequestHandler to your components array in app_controller:

var $components = array('RequestHandler');

3. Add an xml folder to each view directory, with .ctp files for each action you would like to have. This is an example of app/views/users/xml/index.ctp:

<users>
<?php echo $xml->serialize($users); ?>
</users>

See the CakeBook for more information on step 1.

Step 2: Setup CakePHP Errors for Reponse XML (service side)

We decided to use the built in custom errors system inside Cake for displaying Reponse XML for Webservice calls. I know that not all XML responses will be errors (it should actually be the opposite) but I like the way CakePHP handles custom error pages so we leveraged this functionality for this topic.

1. Create app/views/errors/serviceresponse.ctp

<responses>
  <response>
    <code><?php echo $errorCode; ?></code>
    <message><?php echo $errorMessage; ?></message>
  </response>
</response>

2. Create app/app_error.php

<?php
Class AppError extends ErrorHandler {

    function serviceResponse($params) {
        $this->controller->set('errorCode', $params['errorCode']);
        $this->controller->set('errorMessage', $params['errorMessage']);
        $this->controller->layout = 'xml/default';
        $this->_outputMessage('serviceresponse');
    }
}
?>

Now this can be called by using this code in the controller as needed

$this->cakeError('serviceResponse', array('errorMessage' => $errorMessage, 'errorCode' => $errorCode));

Step 3: Create Custom Login Function (service side)

1. Add xmlLogin() to app/controllers/users_controller.php

    function xmlLogin() {
        // Verify request is from a webservice
        if ($this->Session->check('webserviceRequest')) {
            $this->Session->delete('webserviceRequest');

            // Default response
            $errorMessage = 'Login is required to acodeess this resource';
            $errorCode = 'login_required';

            // Check to see if data was posted
            if (!empty($this->data)) {
                // Parse the XML object into an array
                $data = Set::reverse($this->data);

                // Hash the passwords
                $this->data = $this->Auth->hashPasswords($data['Users']);

                // Login
                if($this->Auth->login($this->data)) {
                    $errorMessage = 'Logged in';
                    $errorCode    = 'auth_sucodeess';
                } else {
                    $errorMessage = 'Invalide username or password';
                    $errorCode = 'auth_fail';
                }

            }

            // Generate the response
            $this->cakeError('serviceResponse', array('errorMessage' => $errorMessage, 'errorCode' => $errorCode));
        }
    }

2. Modify the default login()

    function login() {
        if ($this->Session->check('webserviceRequest')) {
            $this->Session->delete('webserviceRequest');

            $this->cakeError('serviceResponse', array('errorMessage' => 'Login is required to acodeess this resource', 'errorCode' => 'login_required'));
        }
    }

3. Add in the webserviceRequest check to beforeFilter() in app/app_controller.php

    function beforeFilter() {
        if ($this->params['url']['ext'] == 'xml') {
            $this->Session->write('webserviceRequest', true);
        }
    }

4. Allow xmlLogin() to bypass Auth. Add the following to the top of your users_controller.php:

	var $preAuth = array();
	function beforeFilter() {
		parent::beforeFilter();

		$this->preAuth['password'] = $this->data['User']['password'];
		$this->Auth->allow('loginTest');
	}

Step 4: Install the Cakeservice Behavior (app side)

1. Download cakeservice.php and put it in app/models/behaviors/cakeservice.php

<?php
/**
 * A simple WebService Behavior class that eases requests to foreign pages
 * Entirely PHP based, does not require and modules or cURL.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * Based on the WebserviceModel authored by Felix Geisendörfer (http://debuggable.com)
 * Based on WebService Behavior by Mark Story (mark-story.com)
 *
 * @author DualTech Services, Inc. (dual-tech.com)
 */
App::import('Core', 'Socket');

class CakeserviceBehavior extends ModelBehavior {
	var $_headers, $_path, $response, $Socket;
	var $cookies = array();

	function request(&$Model, $params = array()) {
		// Setup the connection
		if (!empty($params['url'])) {
			$this->serviceConnect($Model, $params['url']);
		} else {
			return false;
		}

		$postHeaders = array(
			'Host' => 'jadams.bounceme.net',
			'Connection' => 'Close',
		);

		$requestMethod = 'POST';
		if (empty($params['data'])) {
			$requestMethod = 'GET';

		} else {
			$params['data'] = '<?xml version="1.0" encoding="UTF-8" ?>' . $params['data'];
			$postHeaders = array_merge($postHeaders, array('Content-Length' => strlen($params['data']), 'Content-Type'	=> 'text/xml'));
		}

		$this->_formatHeaders($postHeaders);

		$request = "$requestMethod {$this->_path} HTTP/1.0\r\n";
		$request .= $this->_headers . "\r\n";
		$request .= "\r\n";
		if (!empty($params['data'])) {
			$request .= $params['data'];
		}

		$this->Socket->write($request);

		$response = '';
		while ($data = $this->Socket->read()) {
			$response .= $data;
		}

		$this->_parseResponse($response);

		if (array_key_exists('Location', $this->response['headers'])) {
			//$this->serviceConnect($Model, $this->response['headers']['Location']);
			$params['url'] = $this->response['headers']['Location'];
			$this->request($Model, $params);
		}
		return $this->response['body'];
	}

/**
 * Connect the Behavior to a new URL
 *
 * @param string $url The URL to connect to.
 * @param array $options Options Array for the new connection.
 * @return bool success
 **/
	function serviceConnect(&$Model, $url) {
	    $options = array(
	        'timeout' => 30,
	        'persistent' => false,
	        'defaultUrl' => null,
	        'port' => 80,
	        'protocol' => 'tcp',
	        'followRedirect' => true
	    );		

		$path = $this->_setPath($url);
		$options['host'] = $path['host'];

		if ($this->Socket === null) {
			$this->Socket = new CakeSocket($options);
		} else {
			$this->serviceDisconnect($Model);
			$this->Socket->config = $options;
		}
		return $this->Socket->connect();
	}

/**
 * Disconnect / Reset the Webservice Socket.
 *
 * @return boolean
 **/
	function serviceDisconnect(&$Model) {
		if ($this->Socket !== null) {
			$this->Socket->disconnect();
			$this->Socket->reset();
		}
	}

/**
 * Formats Additional Request Headers
 *
 * @return void
 **/
	function _formatHeaders($headers = array()) {
		$headers['User-Agent'] = 'CakeserviceBehavior';
		$headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
		$headers['Accept-Language'] = 'en-us,en;q=0.5';

		// Load cookies
		$headers['Cookie'] = '';
		foreach($this->cookies as $cookieKey => $cookieData) {
			$headers['Cookie'] .= $cookieKey . '=' . $cookieData['value'] . '; ';
		}

		foreach ($headers as $name => $value) {
			$tmp[] = "$name: $value";
		}
		$header = implode("\r\n", $tmp);
		$this->_headers = $header;
	}	

/**
 * Parse the Reponse from the request, separating the headers from the content.
 *
 * @return void
 **/
	function _parseResponse($response) {
		$headers = substr($response, 0, strpos($response, "\r\n\r\n"));
		$body = substr($response, strlen($headers));

		//split up the headers
		$parts = preg_split("/\r?\n/", $headers, -1, PREG_SPLIT_NO_EMPTY);
		$heads = array();
		for ($i = 1, $total = sizeof($parts); $i < $total; $i++ ) {
			list($name, $value) = explode(': ', $parts[$i]);
			$heads[$name] = $value;
		}

		if (array_key_exists('Set-Cookie', $heads)) {
			// Save cookies

			$cookies = array();
			foreach ($heads as $headerKey => $headerValue) {
				if ($headerKey == 'Set-Cookie') {
					$parts = split('; ', $headerValue);

					$cookieKey = '';
					foreach ($parts as $index => $part) {
						list($key, $value) = split('=', $part);

						if ($index == 0) {
							$cookieKey = $key;
							$cookies[$cookieKey]['value'] = $value;
						} else {
							$cookies[$cookieKey][$key] = $value;
						}
					}
				}
			}

			$this->cookies = $cookies;
		}

		$this->response['headers'] = $heads;
		$this->response['body'] = trim($body);
	}	

/**
 * Set the host and path for the webservice.
 * @param string $url The complete url you want to connect to.
 * @return array Host & Path
 **/
    function _setPath($url) {
        $port = 80;
        if (preg_match('/^https?:\/\//', $url)) {
            $url = substr($url, strpos($url, '://') + 3);
        }
        if (strpos($url, '/') === false) {
            $host = $url;
            $path = '/';
        } else {
            $host = substr($url, 0, strpos($url, '/'));
            $path = substr($url, strlen($host));
        }
        if ($path == '') {
            $path = '/';
        }

        $this->_path =$path;
        return array('host' => $host, 'path' => $path, 'port' => $port);
    }

    function setCookies(&$Model, $cookies) {
    	$this->cookies = $cookies;
    }

    function getCookies(&$Model) {
    	return $this->cookies;
    }
}
?>

2. Add cakeservice to your actsAs array in each model you want to utilize it:

var $actsAs = array('cakeservice');

3. Overwrite the default login() function

	function login() {
		if (!empty($this->data)) {
	        $user = array(
	            'Users' => array(
	                'User' => array(
	                    'username'    => $this->data['User']['username'],
	                    'password'    => $this->preAuth['password'],
	                )
	            )
	        );		

	        // Convert the data to XML
	        App::import('Xml');
	        $xml = new Xml($user);

	        // Load existing cookies, if any, for the webservice call
	        if($this->Session->check('apiCookies')) {
	            $this->User->setCookies($this->Session->read('apiCookies'));
	        }

	        // Web service communication
	        $result = $this->User->request(array(
	            'data'    => $xml,
	            'url'    => 'domain.example/path_to_cake/users/xmlLogin.xml',
	        ));

	        // Save the cookies from the web service
	        $cookies = $this->User->getCookies();
	        if(!empty($cookies)) {
	            $this->Session->write('apiCookies', $cookies);
	        }

			$xml = new Xml($result);
			$response = Set::reverse($xml);

			if (isset($response['Responses']['Response']['Data']['User']['id'])) {
				$this->Session->write('Auth.User', $response['Responses']['Response']['Data']['User']);
				$this->Session->setFlash('Successfully logged in.');
				$this->redirect('/');
			} else {
				$authData = $this->Session->read('Message.auth');
				$authData['message'] = $response['Responses']['Response']['message'];
				$this->Session->write('Message.auth', $authData);
			}
		}
	}

Please feel free to post any comments or questions you may have.


Using the Security Component in CakePHP for SSL

I recently needed to require some of my CakePHP actions to be forced to use a secure connection for security purposes. It took me a long time to finally figure out the solution that I found in CakePHP 1.2 so I figured I would share. There is a handy Security Component provided by CakePHP that does exactly what I was looking for. I attempted to contribute to the Cake Book so hopefully the changes will show up there soon.

The example below shows how to force certain actions (login and checkout) to use a secure connection. You specify as many actions in your $this->Security->requireSecure() function that you want to require to be secure. Each time a request that you put in this method is called in a non-secure manner it will do what is called a black hole. When the request is black holed, it will generate a 404 error by default. In the example below I have overridden the default behavior and created my own custom call back that will redirect to a secure connection automatically.

<?php
class AppController extends Controller {
	var $components = array('Security');

	function beforeFilter() {
		$this->Security->blackHoleCallback = 'forceSSL';
		$this->Security->requireSecure('login', 'checkout');
	}

	function forceSSL() {
		$this->redirect('https://' . $_SERVER['SERVER_NAME'] . $this->here);
	}
}
?>

Notice: All of the Security Component’s methods will be passed to the same callback function that you specify so be careful if you are using multiple methods.

Update 03/09/09: My doc changes and usage example were accepted on the official Cake book!


Next Entries »

Powered by Wordpress | Designed by Elegant Themes