Skip to content
tenebrousedge edited this page Dec 26, 2012 · 1 revision

Copula provides a very simple interface at the Model layer, in the form of the OAuthConsumer Behavior. This is attached as normal for CakePHP using the $actsAs property.

<?php
	class ApiModel extends AppModel{
		public $actsAs = array('Copula.OAuthConsumer' => array('autoFetch' => false));
}

The 'autoFetch' key determines whether or not an access token is automatically fetched from the local database. If you set it to false, you must manually call authorize() before using any API functions. Note: If you are not storing access tokens in the database, you must set 'autoFetch' to false. An example of this is shown below:

<?php
	class ApiModel extends AppModel{
		protected function _authorize(){
			$TokenStore = ClassRegistry::init('Copula.TokenStoreSession');
			$user_id = AuthComponent::user('id');
			return $this->authorize($user_id, $TokenStore, 'myApi');
		}
	}

The authorize() function retrieves tokens from storage, if they exist, and throws an exception if they do not exist. OAuth 2.0 tokens have their expiration checked when retrieved from the database. This will probably fail hard if your time zone is not set correctly. If the token is determined to be expired, it will be refreshed automatically. If a token is expired and cannot be refreshed, an exception will be thrown. The token is then merged with the model's datasource configuration.

The OAuthConsumer Behavior also provides a method for models to switch datasources. If you don't understand how that might be useful, you probably don't need to use it.