Howdy folks!
I’m using the googleapis extension to get an access_token from google, works great.
After authenticating with google for the first time in addition to the standard access_token they provide you with a "refresh_token" that is used to get a new access token after the current token expires (1 hour or when browser is closed, whichever comes first).
I’m storing the access_token in the session, and the refresh_token in the DB.
When a user logs in to my app in I’m using setstate to add the refresh token to Yii::app()->user->refresh_token so its always available.
I have various models and controller actions that need to have a valid google api client object to run.
The Google access_token has to be set to the client object each time those models or controller actions run.
I wrote this code to handle it (it works fine):
/**
* @var apiClient $client
*/
$client = Yii::app()->GoogleApis->client;
// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
try {
if(isset(Yii::app()->session['auth_token'])) {
//token set in session, set it to client object each time the app runs
$client->setAccessToken(Yii::app()->session['auth_token']);
if($client->isAccessTokenExpired()) {
//token expired get new token with refresh token, set it to session
$client->refreshToken(Yii::app()->user->refresh_token);
Yii::app()->session['auth_token'] = $client->getAccessToken();
}
} else {
// token not set in session, get a new token with refresh token
$client->refreshToken(Yii::app()->user->refresh_token);
// set the new token in the session
Yii::app()->session['auth_token'] = $client->getAccessToken();
}
} catch(Exception $e) {
throw new CHttpException(400,$e->getMessage());
}
So my question is where do I put it to make it reusable in a model or controller action that requires access to the Google API?
Thanks!