Skip to content
This repository has been archived by the owner on Sep 10, 2021. It is now read-only.

Commit

Permalink
We now successfully get the user info from the g+ api
Browse files Browse the repository at this point in the history
- Added google person ID to data model as the authoritative
identifier for a google auth user
  • Loading branch information
zachmullen committed Jun 24, 2014
1 parent a46b05b commit 8679bf7
Show file tree
Hide file tree
Showing 6 changed files with 168 additions and 1 deletion.
10 changes: 10 additions & 0 deletions modules/googleauth/Notification.php
Expand Up @@ -23,11 +23,13 @@ class Googleauth_Notification extends MIDAS_Notification
{
public $moduleName = 'googleauth';
public $_models = array('Setting');
public $_moduleModels = array('User');

/** init notification process*/
public function init()
{
$this->addCallBack('CALLBACK_CORE_LOGIN_EXTRA_HTML', 'googleAuthLink');
$this->addCallBack('CALLBACK_CORE_USER_DELETED', 'handleUserDeleted');
}//end init

/**
Expand All @@ -54,4 +56,12 @@ public function googleAuthLink()
'<a style="text-decoration: underline;" href="'.$href.'">'.
'Login with your Google account</a></div>';
}

/**
* If a user is deleted, we must delete any corresponding google auth user
*/
public function handleUserDeleted($params)
{
$this->Googleauth_User->deleteByUser($params['userDao']);
}
} // end class
133 changes: 133 additions & 0 deletions modules/googleauth/controllers/CallbackController.php
@@ -0,0 +1,133 @@
<?php


class Googleauth_CallbackController extends Googleauth_AppController
{
public $_models = array('Setting');
public $_moduleModels = array('User');

/**
* This action gets called into as the OAuth callback after the user
* successfully authenticates with Google and approves the scope. A code
* is passed that can be used to make authorized requests later.
*/
function indexAction()
{
$this->disableLayout();
$this->disableView();

$code = $this->_getParam('code');

if (!$code)
{
$error = $this->_getParam('error');
throw new Zend_Exception('Failed to log in with Google OAuth: '.$error);
}

$info = $this->_getUserInfo($code);

$user = $this->_createOrGetUser($info);

echo json_encode($user);
}

/**
* Use the authorization code to get an access token, then use that access
* token to request the user's email and profile info. Returns the necessary
* user info in an array.
*/
protected function _getUserInfo($code)
{
$clientId = $this->Setting->getValueByName('client_id', $this->moduleName);
$clientSecret = $this->Setting->getValueByName('client_secret', $this->moduleName);
$scheme = (array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS']) ?
'https://' : 'http://';
$redirectUri = $scheme.$_SERVER['HTTP_HOST'].
Zend_Controller_Front::getInstance()->getBaseUrl().
'/'.$this->moduleName.'/callback';
$headers = array(
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'Connection: Keep-Alive'
);
$postData = join('&', array(
'grant_type=authorization_code',
'code='.$code,
'client_id='.$clientId,
'client_secret='.$clientSecret,
'redirect_uri='.$redirectUri
));

// Make the request for the access token
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_PORT, 443);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$resp = curl_exec($curl);

$httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpStatus != 200)
{
throw new Zend_Exception('Access token request failed: '.$resp);
}

$resp = json_decode($resp);
$accessToken = $resp->access_token;
$tokenType = $resp->token_type;

// Use the access token to request info about the user
$headers = array(
'Authorization: '.$tokenType.' '.$accessToken
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/plus/v1/people/me');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_PORT, 443);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$resp = curl_exec($curl);
$httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpStatus != 200)
{
throw new Zend_Exception('Get Google user info request failed: '.$resp);
}
$resp = json_decode($resp);

// Now that we have the user info, we use that to log in
$googlePersonId = $resp->id;
$firstName = $resp->name->givenName;
$lastName = $resp->name->familyName;

foreach($resp->emails as $emailEntry)
{
$email = $emailEntry->value;
break;
}

return array(
'googlePersonId' => $googlePersonId,
'firstName' => $firstName,
'lastName' => $lastName,
'email' => $email);
}

protected function _createOrGetUser($info)
{
$personId = $info['googlePersonId'];
$existing = $this->Googleauth_User->getByGooglePersonId($personId);

if (!$existing)
{
// TODO register a new user with the given info
$this->Googleauth_User->createGoogleUser($user, $personId)
}
else
{
$user = $this->User->load($existing->getUserId());
}
}
}//end class
4 changes: 3 additions & 1 deletion modules/googleauth/database/mysql/0.1.0.sql
@@ -1,6 +1,8 @@
CREATE TABLE IF NOT EXISTS `googleauth_user` (
`googleauth_user_id` bigint(20) NOT NULL AUTO_INCREMENT,
`google_person_id` varchar(255) NOT NULL,
`user_id` bigint(20) NOT NULL,
PRIMARY KEY (`googleauth_user_id`),
KEY `user_id` (`user_id`)
KEY `user_id` (`user_id`),
KEY `google_person_id` (`google_person_id`)
);
2 changes: 2 additions & 0 deletions modules/googleauth/database/pgsql/0.1.0.sql
@@ -1,6 +1,8 @@
CREATE TABLE googleauth_user (
googleauth_user_id serial PRIMARY KEY,
google_person_id character varying(255) NOT NULL,
user_id bigint NOT NULL
);

CREATE INDEX googleauth_user_user_id_idx ON googleauth_user (user_id);
CREATE INDEX googleauth_user_gperson_id_idx ON googleauth_user (google_person_id);
9 changes: 9 additions & 0 deletions modules/googleauth/models/base/UserModelBase.php
Expand Up @@ -30,9 +30,18 @@ public function __construct()
$this->_mainData = array(
'googleauth_user_id' => array('type' => MIDAS_DATA),
'user_id' => array('type' => MIDAS_DATA),
'google_person_id' => array('type' => MIDAS_DATA),
'user' => array('type' => MIDAS_MANY_TO_ONE, 'model' => 'User',
'parent_column' => 'user_id', 'child_column' => 'user_id')
);
$this->initialize(); // required
} // end __construct()

public abstract function getByGooglePersonId($pid);
public abstract function deleteByUser($userDao);

public function createGoogleUser($user, $googlePersonId)
{

}
}
11 changes: 11 additions & 0 deletions modules/googleauth/models/pdo/UserModel.php
Expand Up @@ -23,4 +23,15 @@
/** pdo model implementation */
class Googleauth_UserModel extends Googleauth_UserModelBase
{
public function getByGooglePersonId($pid)
{
$sql = $this->database->select()->where('google_person_id = ?', $pid);
$row = $this->database->fetchRow($sql);
return $this->initDao('User', $row, 'googleauth');
}

public function deleteByUser($userDao)
{
$this->database->getDB()->delete('googleauth_user', 'user_id = '.$userDao->getKey());
}
}

0 comments on commit 8679bf7

Please sign in to comment.