From 507101f6dd76a67adfc2a54f108b87a2cd1165d0 Mon Sep 17 00:00:00 2001 From: Erik Amaru Ortiz Date: Wed, 9 Oct 2013 13:16:05 -0400 Subject: [PATCH] First OAth2 Functional Implementation --- composer.json | 3 +- gulliver/core/Session/PmSessionHandler.php | 22 +- gulliver/system/class.bootstrap.php | 6 + workflow/engine/classes/class.api.php | 13 + .../classes/model/PmoauthUserAccessTokens.php | 19 + .../model/PmoauthUserAccessTokensPeer.php | 23 + .../model/map/OauthClientsMapBuilder.php | 6 + .../map/PmoauthUserAccessTokensMapBuilder.php | 78 ++ .../classes/model/om/BaseOauthClients.php | 182 ++++- .../classes/model/om/BaseOauthClientsPeer.php | 33 +- .../model/om/BasePmoauthUserAccessTokens.php | 684 ++++++++++++++++++ .../om/BasePmoauthUserAccessTokensPeer.php | 582 +++++++++++++++ workflow/engine/config/schema.xml | 10 + workflow/engine/data/mysql/schema.sql | 18 + workflow/engine/methods/oauth2/authorize.php | 34 + .../engine/methods/services/oauth2_grant.php | 37 +- .../services/api/processmaker/Application.php | 9 +- workflow/engine/services/oauth2/Server.php | 197 +++-- .../oauth2/views/oauth2/server/authorize.php | 57 +- .../engine/templates/oauth2/authorize.php | 135 ++++ 20 files changed, 2012 insertions(+), 136 deletions(-) create mode 100644 workflow/engine/classes/model/PmoauthUserAccessTokens.php create mode 100644 workflow/engine/classes/model/PmoauthUserAccessTokensPeer.php create mode 100644 workflow/engine/classes/model/map/PmoauthUserAccessTokensMapBuilder.php create mode 100644 workflow/engine/classes/model/om/BasePmoauthUserAccessTokens.php create mode 100644 workflow/engine/classes/model/om/BasePmoauthUserAccessTokensPeer.php create mode 100644 workflow/engine/methods/oauth2/authorize.php create mode 100644 workflow/engine/templates/oauth2/authorize.php diff --git a/composer.json b/composer.json index ec80ea194..366e3db98 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,6 @@ "require": { "luracast/restler" : "dev-master", - "bshaffer/oauth2-server-php": "v1.0", - "twig/twig": "v1.13.2" + "bshaffer/oauth2-server-php": "v1.0" } } diff --git a/gulliver/core/Session/PmSessionHandler.php b/gulliver/core/Session/PmSessionHandler.php index c8d0c6198..e6cafe112 100644 --- a/gulliver/core/Session/PmSessionHandler.php +++ b/gulliver/core/Session/PmSessionHandler.php @@ -24,8 +24,8 @@ class PmSessionHandler //implements SessionHandlerInterface * @var string */ private $dsn = ''; - private $user = ''; - private $password = ''; + private $dbUser = ''; + private $dbPassword = ''; private $dbtable = 'SESSION_STORAGE'; /** @@ -127,6 +127,10 @@ class PmSessionHandler //implements SessionHandlerInterface public function open($savePath, $sessionName) { // routines moved to __construct() for php 5.3.x compatibility + + + error_log("PmSession :: open($savePath, $sessionName) was called"); + return true; } @@ -146,6 +150,8 @@ class PmSessionHandler //implements SessionHandlerInterface // this was commented to take advantage of PDO persistence connections //$this->db = null; + error_log("PmSession :: close() was called"); + return true; } @@ -170,6 +176,8 @@ class PmSessionHandler //implements SessionHandlerInterface //$this->wstmt->bind_param('siss', $id, $time, $data, $key); $this->wstmt->execute(array($id, $time, $data, $key)); + error_log("PmSession :: write($id, array()) was called"); + return true; } @@ -189,6 +197,8 @@ class PmSessionHandler //implements SessionHandlerInterface $data = $this->rstmt->fetch(); $data = unserialize(base64_decode($data['DATA'])); + error_log("PmSession :: read($id) was called"); + return $data; } @@ -203,6 +213,8 @@ class PmSessionHandler //implements SessionHandlerInterface $this->dstmt = $this->db->prepare("DELETE FROM {$this->dbtable} WHERE ID = ?"); } + error_log("PmSession :: destroy($id) was called"); + $this->dstmt->execute(array($id)); return true; @@ -219,10 +231,12 @@ class PmSessionHandler //implements SessionHandlerInterface $time = time() - $maxlifetime; if(! isset($this->gcstmt)) { - $thi->gcstmt = $this->db->prepare("DELETE FROM {$this->dbtable} WHERE SET_TIME < ?"); + $this->gcstmt = $this->db->prepare("DELETE FROM {$this->dbtable} WHERE SET_TIME < ?"); } - $thi->gcstmt->execute(array($time)); + $this->gcstmt->execute(array($time)); + + error_log("PmSession :: gc($maxlifetime) was called"); return true; } diff --git a/gulliver/system/class.bootstrap.php b/gulliver/system/class.bootstrap.php index 8c8fb8775..8087abe9f 100644 --- a/gulliver/system/class.bootstrap.php +++ b/gulliver/system/class.bootstrap.php @@ -1076,6 +1076,12 @@ class Bootstrap $rest->addAuthenticationClass('Api\\OAuth2\\Server', ''); + list($host, $port) = strpos(DB_HOST, ':') !== false ? explode(':', DB_HOST) : array(DB_HOST, ''); + $port = empty($port) ? '' : ";port=$port"; + + \Api\OAuth2\Server::setDatabaseSource(DB_USER, DB_PASS, DB_ADAPTER.":host=$host;dbname=".DB_NAME.$port); + \Api\OAuth2\Server::setPmClientId('x-pm-local-client'); + $rest->setSupportedFormats('JsonFormat', 'XmlFormat'); //, 'HtmlFormat'); //$rest->setOverridingFormats('UploadFormat', 'JsonFormat', 'XmlFormat', 'HtmlFormat'); $rest->setOverridingFormats('HtmlFormat', 'JsonFormat', 'UploadFormat'); diff --git a/workflow/engine/classes/class.api.php b/workflow/engine/classes/class.api.php index f95ac90b4..e2b6588b8 100644 --- a/workflow/engine/classes/class.api.php +++ b/workflow/engine/classes/class.api.php @@ -4,6 +4,7 @@ namespace ProcessMaker; class Api { private static $workspace; + private static $userId; public function __costruct() { @@ -19,5 +20,17 @@ class Api { return self::$workspace; } + + public static function setUserId($userId) + { + self::$userId = $userId; + } + + public function getUserId() + { + //return self::$userId; + + return \Api\OAuth2\Server::getUserId(); + } } diff --git a/workflow/engine/classes/model/PmoauthUserAccessTokens.php b/workflow/engine/classes/model/PmoauthUserAccessTokens.php new file mode 100644 index 000000000..406648968 --- /dev/null +++ b/workflow/engine/classes/model/PmoauthUserAccessTokens.php @@ -0,0 +1,19 @@ +addColumn('CLIENT_SECRET', 'ClientSecret', 'string', CreoleTypes::VARCHAR, true, 80); + $tMap->addColumn('CLIENT_NAME', 'ClientName', 'string', CreoleTypes::VARCHAR, true, 256); + + $tMap->addColumn('CLIENT_DESCRIPTION', 'ClientDescription', 'string', CreoleTypes::VARCHAR, true, 1024); + + $tMap->addColumn('CLIENT_WEBSITE', 'ClientWebsite', 'string', CreoleTypes::VARCHAR, true, 1024); + $tMap->addColumn('REDIRECT_URI', 'RedirectUri', 'string', CreoleTypes::VARCHAR, true, 2000); } // doBuild() diff --git a/workflow/engine/classes/model/map/PmoauthUserAccessTokensMapBuilder.php b/workflow/engine/classes/model/map/PmoauthUserAccessTokensMapBuilder.php new file mode 100644 index 000000000..e4d7682db --- /dev/null +++ b/workflow/engine/classes/model/map/PmoauthUserAccessTokensMapBuilder.php @@ -0,0 +1,78 @@ +dbMap !== null); + } + + /** + * Gets the databasemap this map builder built. + * + * @return the databasemap + */ + public function getDatabaseMap() + { + return $this->dbMap; + } + + /** + * The doBuild() method builds the DatabaseMap + * + * @return void + * @throws PropelException + */ + public function doBuild() + { + $this->dbMap = Propel::getDatabaseMap('workflow'); + + $tMap = $this->dbMap->addTable('PMOAUTH_USER_ACCESS_TOKENS'); + $tMap->setPhpName('PmoauthUserAccessTokens'); + + $tMap->setUseIdGenerator(false); + + $tMap->addPrimaryKey('ACCESS_TOKEN', 'AccessToken', 'string', CreoleTypes::VARCHAR, true, 40); + + $tMap->addColumn('REFRESH_TOKEN', 'RefreshToken', 'string', CreoleTypes::VARCHAR, true, 40); + + $tMap->addColumn('USER_ID', 'UserId', 'string', CreoleTypes::VARCHAR, false, 32); + + $tMap->addColumn('SESSION_ID', 'SessionId', 'string', CreoleTypes::VARCHAR, true, 40); + + } // doBuild() + +} // PmoauthUserAccessTokensMapBuilder diff --git a/workflow/engine/classes/model/om/BaseOauthClients.php b/workflow/engine/classes/model/om/BaseOauthClients.php index 42c0c8af3..fb515064f 100644 --- a/workflow/engine/classes/model/om/BaseOauthClients.php +++ b/workflow/engine/classes/model/om/BaseOauthClients.php @@ -39,6 +39,24 @@ abstract class BaseOauthClients extends BaseObject implements Persistent */ protected $client_secret; + /** + * The value for the client_name field. + * @var string + */ + protected $client_name; + + /** + * The value for the client_description field. + * @var string + */ + protected $client_description; + + /** + * The value for the client_website field. + * @var string + */ + protected $client_website; + /** * The value for the redirect_uri field. * @var string @@ -81,6 +99,39 @@ abstract class BaseOauthClients extends BaseObject implements Persistent return $this->client_secret; } + /** + * Get the [client_name] column value. + * + * @return string + */ + public function getClientName() + { + + return $this->client_name; + } + + /** + * Get the [client_description] column value. + * + * @return string + */ + public function getClientDescription() + { + + return $this->client_description; + } + + /** + * Get the [client_website] column value. + * + * @return string + */ + public function getClientWebsite() + { + + return $this->client_website; + } + /** * Get the [redirect_uri] column value. * @@ -136,6 +187,72 @@ abstract class BaseOauthClients extends BaseObject implements Persistent } // setClientSecret() + /** + * Set the value of [client_name] column. + * + * @param string $v new value + * @return void + */ + public function setClientName($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->client_name !== $v) { + $this->client_name = $v; + $this->modifiedColumns[] = OauthClientsPeer::CLIENT_NAME; + } + + } // setClientName() + + /** + * Set the value of [client_description] column. + * + * @param string $v new value + * @return void + */ + public function setClientDescription($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->client_description !== $v) { + $this->client_description = $v; + $this->modifiedColumns[] = OauthClientsPeer::CLIENT_DESCRIPTION; + } + + } // setClientDescription() + + /** + * Set the value of [client_website] column. + * + * @param string $v new value + * @return void + */ + public function setClientWebsite($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->client_website !== $v) { + $this->client_website = $v; + $this->modifiedColumns[] = OauthClientsPeer::CLIENT_WEBSITE; + } + + } // setClientWebsite() + /** * Set the value of [redirect_uri] column. * @@ -179,14 +296,20 @@ abstract class BaseOauthClients extends BaseObject implements Persistent $this->client_secret = $rs->getString($startcol + 1); - $this->redirect_uri = $rs->getString($startcol + 2); + $this->client_name = $rs->getString($startcol + 2); + + $this->client_description = $rs->getString($startcol + 3); + + $this->client_website = $rs->getString($startcol + 4); + + $this->redirect_uri = $rs->getString($startcol + 5); $this->resetModified(); $this->setNew(false); // FIXME - using NUM_COLUMNS may be clearer. - return $startcol + 3; // 3 = OauthClientsPeer::NUM_COLUMNS - OauthClientsPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 6; // 6 = OauthClientsPeer::NUM_COLUMNS - OauthClientsPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating OauthClients object", $e); @@ -397,6 +520,15 @@ abstract class BaseOauthClients extends BaseObject implements Persistent return $this->getClientSecret(); break; case 2: + return $this->getClientName(); + break; + case 3: + return $this->getClientDescription(); + break; + case 4: + return $this->getClientWebsite(); + break; + case 5: return $this->getRedirectUri(); break; default: @@ -421,7 +553,10 @@ abstract class BaseOauthClients extends BaseObject implements Persistent $result = array( $keys[0] => $this->getClientId(), $keys[1] => $this->getClientSecret(), - $keys[2] => $this->getRedirectUri(), + $keys[2] => $this->getClientName(), + $keys[3] => $this->getClientDescription(), + $keys[4] => $this->getClientWebsite(), + $keys[5] => $this->getRedirectUri(), ); return $result; } @@ -460,6 +595,15 @@ abstract class BaseOauthClients extends BaseObject implements Persistent $this->setClientSecret($value); break; case 2: + $this->setClientName($value); + break; + case 3: + $this->setClientDescription($value); + break; + case 4: + $this->setClientWebsite($value); + break; + case 5: $this->setRedirectUri($value); break; } // switch() @@ -494,7 +638,19 @@ abstract class BaseOauthClients extends BaseObject implements Persistent } if (array_key_exists($keys[2], $arr)) { - $this->setRedirectUri($arr[$keys[2]]); + $this->setClientName($arr[$keys[2]]); + } + + if (array_key_exists($keys[3], $arr)) { + $this->setClientDescription($arr[$keys[3]]); + } + + if (array_key_exists($keys[4], $arr)) { + $this->setClientWebsite($arr[$keys[4]]); + } + + if (array_key_exists($keys[5], $arr)) { + $this->setRedirectUri($arr[$keys[5]]); } } @@ -516,6 +672,18 @@ abstract class BaseOauthClients extends BaseObject implements Persistent $criteria->add(OauthClientsPeer::CLIENT_SECRET, $this->client_secret); } + if ($this->isColumnModified(OauthClientsPeer::CLIENT_NAME)) { + $criteria->add(OauthClientsPeer::CLIENT_NAME, $this->client_name); + } + + if ($this->isColumnModified(OauthClientsPeer::CLIENT_DESCRIPTION)) { + $criteria->add(OauthClientsPeer::CLIENT_DESCRIPTION, $this->client_description); + } + + if ($this->isColumnModified(OauthClientsPeer::CLIENT_WEBSITE)) { + $criteria->add(OauthClientsPeer::CLIENT_WEBSITE, $this->client_website); + } + if ($this->isColumnModified(OauthClientsPeer::REDIRECT_URI)) { $criteria->add(OauthClientsPeer::REDIRECT_URI, $this->redirect_uri); } @@ -576,6 +744,12 @@ abstract class BaseOauthClients extends BaseObject implements Persistent $copyObj->setClientSecret($this->client_secret); + $copyObj->setClientName($this->client_name); + + $copyObj->setClientDescription($this->client_description); + + $copyObj->setClientWebsite($this->client_website); + $copyObj->setRedirectUri($this->redirect_uri); diff --git a/workflow/engine/classes/model/om/BaseOauthClientsPeer.php b/workflow/engine/classes/model/om/BaseOauthClientsPeer.php index 56e04743c..712e2455a 100644 --- a/workflow/engine/classes/model/om/BaseOauthClientsPeer.php +++ b/workflow/engine/classes/model/om/BaseOauthClientsPeer.php @@ -25,7 +25,7 @@ abstract class BaseOauthClientsPeer const CLASS_DEFAULT = 'classes.model.OauthClients'; /** The total number of columns. */ - const NUM_COLUMNS = 3; + const NUM_COLUMNS = 6; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -37,6 +37,15 @@ abstract class BaseOauthClientsPeer /** the column name for the CLIENT_SECRET field */ const CLIENT_SECRET = 'OAUTH_CLIENTS.CLIENT_SECRET'; + /** the column name for the CLIENT_NAME field */ + const CLIENT_NAME = 'OAUTH_CLIENTS.CLIENT_NAME'; + + /** the column name for the CLIENT_DESCRIPTION field */ + const CLIENT_DESCRIPTION = 'OAUTH_CLIENTS.CLIENT_DESCRIPTION'; + + /** the column name for the CLIENT_WEBSITE field */ + const CLIENT_WEBSITE = 'OAUTH_CLIENTS.CLIENT_WEBSITE'; + /** the column name for the REDIRECT_URI field */ const REDIRECT_URI = 'OAUTH_CLIENTS.REDIRECT_URI'; @@ -51,10 +60,10 @@ abstract class BaseOauthClientsPeer * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('ClientId', 'ClientSecret', 'RedirectUri', ), - BasePeer::TYPE_COLNAME => array (OauthClientsPeer::CLIENT_ID, OauthClientsPeer::CLIENT_SECRET, OauthClientsPeer::REDIRECT_URI, ), - BasePeer::TYPE_FIELDNAME => array ('CLIENT_ID', 'CLIENT_SECRET', 'REDIRECT_URI', ), - BasePeer::TYPE_NUM => array (0, 1, 2, ) + BasePeer::TYPE_PHPNAME => array ('ClientId', 'ClientSecret', 'ClientName', 'ClientDescription', 'ClientWebsite', 'RedirectUri', ), + BasePeer::TYPE_COLNAME => array (OauthClientsPeer::CLIENT_ID, OauthClientsPeer::CLIENT_SECRET, OauthClientsPeer::CLIENT_NAME, OauthClientsPeer::CLIENT_DESCRIPTION, OauthClientsPeer::CLIENT_WEBSITE, OauthClientsPeer::REDIRECT_URI, ), + BasePeer::TYPE_FIELDNAME => array ('CLIENT_ID', 'CLIENT_SECRET', 'CLIENT_NAME', 'CLIENT_DESCRIPTION', 'CLIENT_WEBSITE', 'REDIRECT_URI', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, ) ); /** @@ -64,10 +73,10 @@ abstract class BaseOauthClientsPeer * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('ClientId' => 0, 'ClientSecret' => 1, 'RedirectUri' => 2, ), - BasePeer::TYPE_COLNAME => array (OauthClientsPeer::CLIENT_ID => 0, OauthClientsPeer::CLIENT_SECRET => 1, OauthClientsPeer::REDIRECT_URI => 2, ), - BasePeer::TYPE_FIELDNAME => array ('CLIENT_ID' => 0, 'CLIENT_SECRET' => 1, 'REDIRECT_URI' => 2, ), - BasePeer::TYPE_NUM => array (0, 1, 2, ) + BasePeer::TYPE_PHPNAME => array ('ClientId' => 0, 'ClientSecret' => 1, 'ClientName' => 2, 'ClientDescription' => 3, 'ClientWebsite' => 4, 'RedirectUri' => 5, ), + BasePeer::TYPE_COLNAME => array (OauthClientsPeer::CLIENT_ID => 0, OauthClientsPeer::CLIENT_SECRET => 1, OauthClientsPeer::CLIENT_NAME => 2, OauthClientsPeer::CLIENT_DESCRIPTION => 3, OauthClientsPeer::CLIENT_WEBSITE => 4, OauthClientsPeer::REDIRECT_URI => 5, ), + BasePeer::TYPE_FIELDNAME => array ('CLIENT_ID' => 0, 'CLIENT_SECRET' => 1, 'CLIENT_NAME' => 2, 'CLIENT_DESCRIPTION' => 3, 'CLIENT_WEBSITE' => 4, 'REDIRECT_URI' => 5, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, ) ); /** @@ -172,6 +181,12 @@ abstract class BaseOauthClientsPeer $criteria->addSelectColumn(OauthClientsPeer::CLIENT_SECRET); + $criteria->addSelectColumn(OauthClientsPeer::CLIENT_NAME); + + $criteria->addSelectColumn(OauthClientsPeer::CLIENT_DESCRIPTION); + + $criteria->addSelectColumn(OauthClientsPeer::CLIENT_WEBSITE); + $criteria->addSelectColumn(OauthClientsPeer::REDIRECT_URI); } diff --git a/workflow/engine/classes/model/om/BasePmoauthUserAccessTokens.php b/workflow/engine/classes/model/om/BasePmoauthUserAccessTokens.php new file mode 100644 index 000000000..864053cf2 --- /dev/null +++ b/workflow/engine/classes/model/om/BasePmoauthUserAccessTokens.php @@ -0,0 +1,684 @@ +access_token; + } + + /** + * Get the [refresh_token] column value. + * + * @return string + */ + public function getRefreshToken() + { + + return $this->refresh_token; + } + + /** + * Get the [user_id] column value. + * + * @return string + */ + public function getUserId() + { + + return $this->user_id; + } + + /** + * Get the [session_id] column value. + * + * @return string + */ + public function getSessionId() + { + + return $this->session_id; + } + + /** + * Set the value of [access_token] column. + * + * @param string $v new value + * @return void + */ + public function setAccessToken($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->access_token !== $v) { + $this->access_token = $v; + $this->modifiedColumns[] = PmoauthUserAccessTokensPeer::ACCESS_TOKEN; + } + + } // setAccessToken() + + /** + * Set the value of [refresh_token] column. + * + * @param string $v new value + * @return void + */ + public function setRefreshToken($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->refresh_token !== $v) { + $this->refresh_token = $v; + $this->modifiedColumns[] = PmoauthUserAccessTokensPeer::REFRESH_TOKEN; + } + + } // setRefreshToken() + + /** + * Set the value of [user_id] column. + * + * @param string $v new value + * @return void + */ + public function setUserId($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->user_id !== $v) { + $this->user_id = $v; + $this->modifiedColumns[] = PmoauthUserAccessTokensPeer::USER_ID; + } + + } // setUserId() + + /** + * Set the value of [session_id] column. + * + * @param string $v new value + * @return void + */ + public function setSessionId($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->session_id !== $v) { + $this->session_id = $v; + $this->modifiedColumns[] = PmoauthUserAccessTokensPeer::SESSION_ID; + } + + } // setSessionId() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (1-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param ResultSet $rs The ResultSet class with cursor advanced to desired record pos. + * @param int $startcol 1-based offset column which indicates which restultset column to start with. + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate(ResultSet $rs, $startcol = 1) + { + try { + + $this->access_token = $rs->getString($startcol + 0); + + $this->refresh_token = $rs->getString($startcol + 1); + + $this->user_id = $rs->getString($startcol + 2); + + $this->session_id = $rs->getString($startcol + 3); + + $this->resetModified(); + + $this->setNew(false); + + // FIXME - using NUM_COLUMNS may be clearer. + return $startcol + 4; // 4 = PmoauthUserAccessTokensPeer::NUM_COLUMNS - PmoauthUserAccessTokensPeer::NUM_LAZY_LOAD_COLUMNS). + + } catch (Exception $e) { + throw new PropelException("Error populating PmoauthUserAccessTokens object", $e); + } + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param Connection $con + * @return void + * @throws PropelException + * @see BaseObject::setDeleted() + * @see BaseObject::isDeleted() + */ + public function delete($con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(PmoauthUserAccessTokensPeer::DATABASE_NAME); + } + + try { + $con->begin(); + PmoauthUserAccessTokensPeer::doDelete($this, $con); + $this->setDeleted(true); + $con->commit(); + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Stores the object in the database. If the object is new, + * it inserts it; otherwise an update is performed. This method + * wraps the doSave() worker method in a transaction. + * + * @param Connection $con + * @return int The number of rows affected by this insert/update + * @throws PropelException + * @see doSave() + */ + public function save($con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(PmoauthUserAccessTokensPeer::DATABASE_NAME); + } + + try { + $con->begin(); + $affectedRows = $this->doSave($con); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Stores the object in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param Connection $con + * @return int The number of rows affected by this insert/update and any referring + * @throws PropelException + * @see save() + */ + protected function doSave($con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + + // If this object has been modified, then save it to the database. + if ($this->isModified()) { + if ($this->isNew()) { + $pk = PmoauthUserAccessTokensPeer::doInsert($this, $con); + $affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which + // should always be true here (even though technically + // BasePeer::doInsert() can insert multiple rows). + + $this->setNew(false); + } else { + $affectedRows += PmoauthUserAccessTokensPeer::doUpdate($this, $con); + } + $this->resetModified(); // [HL] After being saved an object is no longer 'modified' + } + + $this->alreadyInSave = false; + } + return $affectedRows; + } // doSave() + + /** + * Array of ValidationFailed objects. + * @var array ValidationFailed[] + */ + protected $validationFailures = array(); + + /** + * Gets any ValidationFailed objects that resulted from last call to validate(). + * + * + * @return array ValidationFailed[] + * @see validate() + */ + public function getValidationFailures() + { + return $this->validationFailures; + } + + /** + * Validates the objects modified field values and all objects related to this table. + * + * If $columns is either a column name or an array of column names + * only those columns are validated. + * + * @param mixed $columns Column name or an array of column names. + * @return boolean Whether all columns pass validation. + * @see doValidate() + * @see getValidationFailures() + */ + public function validate($columns = null) + { + $res = $this->doValidate($columns); + if ($res === true) { + $this->validationFailures = array(); + return true; + } else { + $this->validationFailures = $res; + return false; + } + } + + /** + * This function performs the validation work for complex object models. + * + * In addition to checking the current object, all related objects will + * also be validated. If all pass then true is returned; otherwise + * an aggreagated array of ValidationFailed objects will be returned. + * + * @param array $columns Array of column names to validate. + * @return mixed true if all validations pass; + array of ValidationFailed objects otherwise. + */ + protected function doValidate($columns = null) + { + if (!$this->alreadyInValidation) { + $this->alreadyInValidation = true; + $retval = null; + + $failureMap = array(); + + + if (($retval = PmoauthUserAccessTokensPeer::doValidate($this, $columns)) !== true) { + $failureMap = array_merge($failureMap, $retval); + } + + + + $this->alreadyInValidation = false; + } + + return (!empty($failureMap) ? $failureMap : true); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return mixed Value of field. + */ + public function getByName($name, $type = BasePeer::TYPE_PHPNAME) + { + $pos = PmoauthUserAccessTokensPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->getByPosition($pos); + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch($pos) { + case 0: + return $this->getAccessToken(); + break; + case 1: + return $this->getRefreshToken(); + break; + case 2: + return $this->getUserId(); + break; + case 3: + return $this->getSessionId(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType One of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = BasePeer::TYPE_PHPNAME) + { + $keys = PmoauthUserAccessTokensPeer::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getAccessToken(), + $keys[1] => $this->getRefreshToken(), + $keys[2] => $this->getUserId(), + $keys[3] => $this->getSessionId(), + ); + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name peer name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return void + */ + public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) + { + $pos = PmoauthUserAccessTokensPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch($pos) { + case 0: + $this->setAccessToken($value); + break; + case 1: + $this->setRefreshToken($value); + break; + case 2: + $this->setUserId($value); + break; + case 3: + $this->setSessionId($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, + * TYPE_NUM. The default key type is the column's phpname (e.g. 'authorId') + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) + { + $keys = PmoauthUserAccessTokensPeer::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) { + $this->setAccessToken($arr[$keys[0]]); + } + + if (array_key_exists($keys[1], $arr)) { + $this->setRefreshToken($arr[$keys[1]]); + } + + if (array_key_exists($keys[2], $arr)) { + $this->setUserId($arr[$keys[2]]); + } + + if (array_key_exists($keys[3], $arr)) { + $this->setSessionId($arr[$keys[3]]); + } + + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(PmoauthUserAccessTokensPeer::DATABASE_NAME); + + if ($this->isColumnModified(PmoauthUserAccessTokensPeer::ACCESS_TOKEN)) { + $criteria->add(PmoauthUserAccessTokensPeer::ACCESS_TOKEN, $this->access_token); + } + + if ($this->isColumnModified(PmoauthUserAccessTokensPeer::REFRESH_TOKEN)) { + $criteria->add(PmoauthUserAccessTokensPeer::REFRESH_TOKEN, $this->refresh_token); + } + + if ($this->isColumnModified(PmoauthUserAccessTokensPeer::USER_ID)) { + $criteria->add(PmoauthUserAccessTokensPeer::USER_ID, $this->user_id); + } + + if ($this->isColumnModified(PmoauthUserAccessTokensPeer::SESSION_ID)) { + $criteria->add(PmoauthUserAccessTokensPeer::SESSION_ID, $this->session_id); + } + + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(PmoauthUserAccessTokensPeer::DATABASE_NAME); + + $criteria->add(PmoauthUserAccessTokensPeer::ACCESS_TOKEN, $this->access_token); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return string + */ + public function getPrimaryKey() + { + return $this->getAccessToken(); + } + + /** + * Generic method to set the primary key (access_token column). + * + * @param string $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setAccessToken($key); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of PmoauthUserAccessTokens (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false) + { + + $copyObj->setRefreshToken($this->refresh_token); + + $copyObj->setUserId($this->user_id); + + $copyObj->setSessionId($this->session_id); + + + $copyObj->setNew(true); + + $copyObj->setAccessToken(NULL); // this is a pkey column, so set to default value + + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return PmoauthUserAccessTokens Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + return $copyObj; + } + + /** + * Returns a peer instance associated with this om. + * + * Since Peer classes are not to have any instance attributes, this method returns the + * same instance for all member of this class. The method could therefore + * be static, but this would prevent one from overriding the behavior. + * + * @return PmoauthUserAccessTokensPeer + */ + public function getPeer() + { + if (self::$peer === null) { + self::$peer = new PmoauthUserAccessTokensPeer(); + } + return self::$peer; + } +} + diff --git a/workflow/engine/classes/model/om/BasePmoauthUserAccessTokensPeer.php b/workflow/engine/classes/model/om/BasePmoauthUserAccessTokensPeer.php new file mode 100644 index 000000000..0e3c70f33 --- /dev/null +++ b/workflow/engine/classes/model/om/BasePmoauthUserAccessTokensPeer.php @@ -0,0 +1,582 @@ + array ('AccessToken', 'RefreshToken', 'UserId', 'SessionId', ), + BasePeer::TYPE_COLNAME => array (PmoauthUserAccessTokensPeer::ACCESS_TOKEN, PmoauthUserAccessTokensPeer::REFRESH_TOKEN, PmoauthUserAccessTokensPeer::USER_ID, PmoauthUserAccessTokensPeer::SESSION_ID, ), + BasePeer::TYPE_FIELDNAME => array ('ACCESS_TOKEN', 'REFRESH_TOKEN', 'USER_ID', 'SESSION_ID', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 + */ + private static $fieldKeys = array ( + BasePeer::TYPE_PHPNAME => array ('AccessToken' => 0, 'RefreshToken' => 1, 'UserId' => 2, 'SessionId' => 3, ), + BasePeer::TYPE_COLNAME => array (PmoauthUserAccessTokensPeer::ACCESS_TOKEN => 0, PmoauthUserAccessTokensPeer::REFRESH_TOKEN => 1, PmoauthUserAccessTokensPeer::USER_ID => 2, PmoauthUserAccessTokensPeer::SESSION_ID => 3, ), + BasePeer::TYPE_FIELDNAME => array ('ACCESS_TOKEN' => 0, 'REFRESH_TOKEN' => 1, 'USER_ID' => 2, 'SESSION_ID' => 3, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, ) + ); + + /** + * @return MapBuilder the map builder for this peer + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getMapBuilder() + { + include_once 'classes/model/map/PmoauthUserAccessTokensMapBuilder.php'; + return BasePeer::getMapBuilder('classes.model.map.PmoauthUserAccessTokensMapBuilder'); + } + /** + * Gets a map (hash) of PHP names to DB column names. + * + * @return array The PHP to DB name map for this peer + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @deprecated Use the getFieldNames() and translateFieldName() methods instead of this. + */ + public static function getPhpNameMap() + { + if (self::$phpNameMap === null) { + $map = PmoauthUserAccessTokensPeer::getTableMap(); + $columns = $map->getColumns(); + $nameMap = array(); + foreach ($columns as $column) { + $nameMap[$column->getPhpName()] = $column->getColumnName(); + } + self::$phpNameMap = $nameMap; + } + return self::$phpNameMap; + } + /** + * Translates a fieldname to another type + * + * @param string $name field name + * @param string $fromType One of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @param string $toType One of the class type constants + * @return string translated name of the field. + */ + static public function translateFieldName($name, $fromType, $toType) + { + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; + if ($key === null) { + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); + } + return $toNames[$key]; + } + + /** + * Returns an array of of field names. + * + * @param string $type The type of fieldnames to return: + * One of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return array A list of field names + */ + + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) + { + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.'); + } + return self::$fieldNames[$type]; + } + + /** + * Convenience method which changes table.column to alias.column. + * + * Using this method you can maintain SQL abstraction while using column aliases. + * + * $c->addAlias("alias1", TablePeer::TABLE_NAME); + * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); + * + * @param string $alias The alias for the current table. + * @param string $column The column name for current table. (i.e. PmoauthUserAccessTokensPeer::COLUMN_NAME). + * @return string + */ + public static function alias($alias, $column) + { + return str_replace(PmoauthUserAccessTokensPeer::TABLE_NAME.'.', $alias.'.', $column); + } + + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param criteria object containing the columns to add. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria) + { + + $criteria->addSelectColumn(PmoauthUserAccessTokensPeer::ACCESS_TOKEN); + + $criteria->addSelectColumn(PmoauthUserAccessTokensPeer::REFRESH_TOKEN); + + $criteria->addSelectColumn(PmoauthUserAccessTokensPeer::USER_ID); + + $criteria->addSelectColumn(PmoauthUserAccessTokensPeer::SESSION_ID); + + } + + const COUNT = 'COUNT(PMOAUTH_USER_ACCESS_TOKENS.ACCESS_TOKEN)'; + const COUNT_DISTINCT = 'COUNT(DISTINCT PMOAUTH_USER_ACCESS_TOKENS.ACCESS_TOKEN)'; + + /** + * Returns the number of rows matching criteria. + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria). + * @param Connection $con + * @return int Number of matching rows. + */ + public static function doCount(Criteria $criteria, $distinct = false, $con = null) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // clear out anything that might confuse the ORDER BY clause + $criteria->clearSelectColumns()->clearOrderByColumns(); + if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->addSelectColumn(PmoauthUserAccessTokensPeer::COUNT_DISTINCT); + } else { + $criteria->addSelectColumn(PmoauthUserAccessTokensPeer::COUNT); + } + + // just in case we're grouping: add those columns to the select statement + foreach ($criteria->getGroupByColumns() as $column) { + $criteria->addSelectColumn($column); + } + + $rs = PmoauthUserAccessTokensPeer::doSelectRS($criteria, $con); + if ($rs->next()) { + return $rs->getInt(1); + } else { + // no rows returned; we infer that means 0 matches. + return 0; + } + } + /** + * Method to select one object from the DB. + * + * @param Criteria $criteria object used to create the SELECT statement. + * @param Connection $con + * @return PmoauthUserAccessTokens + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectOne(Criteria $criteria, $con = null) + { + $critcopy = clone $criteria; + $critcopy->setLimit(1); + $objects = PmoauthUserAccessTokensPeer::doSelect($critcopy, $con); + if ($objects) { + return $objects[0]; + } + return null; + } + /** + * Method to do selects. + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param Connection $con + * @return array Array of selected Objects + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelect(Criteria $criteria, $con = null) + { + return PmoauthUserAccessTokensPeer::populateObjects(PmoauthUserAccessTokensPeer::doSelectRS($criteria, $con)); + } + /** + * Prepares the Criteria object and uses the parent doSelect() + * method to get a ResultSet. + * + * Use this method directly if you want to just get the resultset + * (instead of an array of objects). + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param Connection $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return ResultSet The resultset object with numerically-indexed fields. + * @see BasePeer::doSelect() + */ + public static function doSelectRS(Criteria $criteria, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + if (!$criteria->getSelectColumns()) { + $criteria = clone $criteria; + PmoauthUserAccessTokensPeer::addSelectColumns($criteria); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + // BasePeer returns a Creole ResultSet, set to return + // rows indexed numerically. + return BasePeer::doSelect($criteria, $con); + } + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(ResultSet $rs) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = PmoauthUserAccessTokensPeer::getOMClass(); + $cls = Propel::import($cls); + // populate the object(s) + while ($rs->next()) { + + $obj = new $cls(); + $obj->hydrate($rs); + $results[] = $obj; + + } + return $results; + } + /** + * Returns the TableMap related to this peer. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); + } + + /** + * The class that the Peer will make instances of. + * + * This uses a dot-path notation which is tranalted into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @return string path.to.ClassName + */ + public static function getOMClass() + { + return PmoauthUserAccessTokensPeer::CLASS_DEFAULT; + } + + /** + * Method perform an INSERT on the database, given a PmoauthUserAccessTokens or Criteria object. + * + * @param mixed $values Criteria or PmoauthUserAccessTokens object containing data that is used to create the INSERT statement. + * @param Connection $con the connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($values, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } else { + $criteria = $values->buildCriteria(); // build Criteria from PmoauthUserAccessTokens object + } + + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->begin(); + $pk = BasePeer::doInsert($criteria, $con); + $con->commit(); + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + + return $pk; + } + + /** + * Method perform an UPDATE on the database, given a PmoauthUserAccessTokens or Criteria object. + * + * @param mixed $values Criteria or PmoauthUserAccessTokens object containing data create the UPDATE statement. + * @param Connection $con The connection to use (specify Connection exert more control over transactions). + * @return int The number of affected rows (if supported by underlying database driver). + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doUpdate($values, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + $selectCriteria = new Criteria(self::DATABASE_NAME); + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + + $comparison = $criteria->getComparison(PmoauthUserAccessTokensPeer::ACCESS_TOKEN); + $selectCriteria->add(PmoauthUserAccessTokensPeer::ACCESS_TOKEN, $criteria->remove(PmoauthUserAccessTokensPeer::ACCESS_TOKEN), $comparison); + + } else { + $criteria = $values->buildCriteria(); // gets full criteria + $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) + } + + // set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + return BasePeer::doUpdate($selectCriteria, $criteria, $con); + } + + /** + * Method to DELETE all rows from the PMOAUTH_USER_ACCESS_TOKENS table. + * + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll($con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->begin(); + $affectedRows += BasePeer::doDeleteAll(PmoauthUserAccessTokensPeer::TABLE_NAME, $con); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Method perform a DELETE on the database, given a PmoauthUserAccessTokens or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or PmoauthUserAccessTokens object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param Connection $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + * This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(PmoauthUserAccessTokensPeer::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } elseif ($values instanceof PmoauthUserAccessTokens) { + + $criteria = $values->buildPkeyCriteria(); + } else { + // it must be the primary key + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(PmoauthUserAccessTokensPeer::ACCESS_TOKEN, (array) $values, Criteria::IN); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->begin(); + + $affectedRows += BasePeer::doDelete($criteria, $con); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Validates all modified columns of given PmoauthUserAccessTokens object. + * If parameter $columns is either a single column name or an array of column names + * than only those columns are validated. + * + * NOTICE: This does not apply to primary or foreign keys for now. + * + * @param PmoauthUserAccessTokens $obj The object to validate. + * @param mixed $cols Column name or array of column names. + * + * @return mixed TRUE if all columns are valid or the error message of the first invalid column. + */ + public static function doValidate(PmoauthUserAccessTokens $obj, $cols = null) + { + $columns = array(); + + if ($cols) { + $dbMap = Propel::getDatabaseMap(PmoauthUserAccessTokensPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(PmoauthUserAccessTokensPeer::TABLE_NAME); + + if (! is_array($cols)) { + $cols = array($cols); + } + + foreach ($cols as $colName) { + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); + $columns[$colName] = $obj->$get(); + } + } + } else { + + } + + return BasePeer::doValidate(PmoauthUserAccessTokensPeer::DATABASE_NAME, PmoauthUserAccessTokensPeer::TABLE_NAME, $columns); + } + + /** + * Retrieve a single object by pkey. + * + * @param mixed $pk the primary key. + * @param Connection $con the connection to use + * @return PmoauthUserAccessTokens + */ + public static function retrieveByPK($pk, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + $criteria = new Criteria(PmoauthUserAccessTokensPeer::DATABASE_NAME); + + $criteria->add(PmoauthUserAccessTokensPeer::ACCESS_TOKEN, $pk); + + + $v = PmoauthUserAccessTokensPeer::doSelect($criteria, $con); + + return !empty($v) > 0 ? $v[0] : null; + } + + /** + * Retrieve multiple objects by pkey. + * + * @param array $pks List of primary keys + * @param Connection $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function retrieveByPKs($pks, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + $objs = null; + if (empty($pks)) { + $objs = array(); + } else { + $criteria = new Criteria(); + $criteria->add(PmoauthUserAccessTokensPeer::ACCESS_TOKEN, $pks, Criteria::IN); + $objs = PmoauthUserAccessTokensPeer::doSelect($criteria, $con); + } + return $objs; + } +} + + +// static code to register the map builder for this Peer with the main Propel class +if (Propel::isInit()) { + // the MapBuilder classes register themselves with Propel during initialization + // so we need to load them here. + try { + BasePmoauthUserAccessTokensPeer::getMapBuilder(); + } catch (Exception $e) { + Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR); + } +} else { + // even if Propel is not yet initialized, the map builder class can be registered + // now and then it will be loaded when Propel initializes. + require_once 'classes/model/map/PmoauthUserAccessTokensMapBuilder.php'; + Propel::registerMapBuilder('classes.model.map.PmoauthUserAccessTokensMapBuilder'); +} + diff --git a/workflow/engine/config/schema.xml b/workflow/engine/config/schema.xml index 5ddf60a33..5f1843bdf 100755 --- a/workflow/engine/config/schema.xml +++ b/workflow/engine/config/schema.xml @@ -3028,6 +3028,9 @@ + + +
@@ -3042,4 +3045,11 @@
+ + + + + + +
diff --git a/workflow/engine/data/mysql/schema.sql b/workflow/engine/data/mysql/schema.sql index 3ff10f5ad..ea8b7a475 100755 --- a/workflow/engine/data/mysql/schema.sql +++ b/workflow/engine/data/mysql/schema.sql @@ -1516,6 +1516,9 @@ CREATE TABLE `OAUTH_CLIENTS` ( `CLIENT_ID` VARCHAR(80) NOT NULL, `CLIENT_SECRET` VARCHAR(80) NOT NULL, + `CLIENT_NAME` VARCHAR(256) NOT NULL, + `CLIENT_DESCRIPTION` VARCHAR(1024) NOT NULL, + `CLIENT_WEBSITE` VARCHAR(1024) NOT NULL, `REDIRECT_URI` VARCHAR(2000) NOT NULL, PRIMARY KEY (`CLIENT_ID`) )ENGINE=InnoDB ; @@ -1548,5 +1551,20 @@ CREATE TABLE `OAUTH_SCOPES` `SCOPE` VARCHAR(2000), `CLIENT_ID` VARCHAR(80) )ENGINE=InnoDB ; +#----------------------------------------------------------------------------- +#-- PMOAUTH_USER_ACCESS_TOKENS +#----------------------------------------------------------------------------- + +DROP TABLE IF EXISTS `PMOAUTH_USER_ACCESS_TOKENS`; + + +CREATE TABLE `PMOAUTH_USER_ACCESS_TOKENS` +( + `ACCESS_TOKEN` VARCHAR(40) NOT NULL, + `REFRESH_TOKEN` VARCHAR(40) NOT NULL, + `USER_ID` VARCHAR(32), + `SESSION_ID` VARCHAR(40) NOT NULL, + PRIMARY KEY (`ACCESS_TOKEN`) +)ENGINE=InnoDB ; # This restores the fkey checks, after having unset them earlier SET FOREIGN_KEY_CHECKS = 1; diff --git a/workflow/engine/methods/oauth2/authorize.php b/workflow/engine/methods/oauth2/authorize.php new file mode 100644 index 000000000..b6a9bb730 --- /dev/null +++ b/workflow/engine/methods/oauth2/authorize.php @@ -0,0 +1,34 @@ +AddContent( 'view', 'oauth2/authorize' ); + + G::RenderPage('publish', 'minimal'); + break; + + case 'POST': + require_once PATH_CORE . 'services/oauth2/Server.php'; + + list($host, $port) = strpos(DB_HOST, ':') !== false ? explode(':', DB_HOST) : array(DB_HOST, ''); + $port = empty($port) ? '' : ";port=$port"; + + \Api\OAuth2\Server::setDatabaseSource(DB_USER, DB_PASS, DB_ADAPTER.":host=$host;dbname=".DB_NAME.$port); + \Api\OAuth2\Server::setPmClientId('x-pm-local-client'); + + $oauthServer = new \Api\OAuth2\Server(); + $userid = $_SESSION['USER_LOGGED']; + $authorize = isset($_POST['authorize']) ? (bool) $_POST['authorize'] : false; + + + $response = $oauthServer->postAuthorize($authorize, $userid, true); + + $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40); + + echo 'session_id ' . session_id() . '
'; + exit("SUCCESS! ==> Authorization Code: $code"); + + //die($response->send()); + break; +} \ No newline at end of file diff --git a/workflow/engine/methods/services/oauth2_grant.php b/workflow/engine/methods/services/oauth2_grant.php index e8a41f562..b17278580 100644 --- a/workflow/engine/methods/services/oauth2_grant.php +++ b/workflow/engine/methods/services/oauth2_grant.php @@ -1,14 +1,20 @@ '.$_GET['error'] . '
'; + die($_GET['error_description']); +} -$clientId = 'testclient'; -$secret = 'testpass'; + +$host = 'http://pmos/api/1.0/workflow/token'; +$code = empty($_GET['code']) ? 'NN' : $_GET['code']; + +$clientId = 'x-pm-local-client'; +$secret = '179ad45c6ce2cb97cf1029e212046e81'; $data = array( 'grant_type' => 'authorization_code', - 'code' => $_GET['code'] + 'code' => $code ); $ch = curl_init($host); @@ -20,9 +26,26 @@ curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); -$return = @json_decode(curl_exec($ch)); +$data = @json_decode(curl_exec($ch)); + +if (is_object($data)) { + /*$data = (array) $data; + require_once PATH_CORE . 'classes/model/DesignerOauthAccessTokens.php'; + + $model = new DesignerOauthAccessTokens(); + $model->setAccessToken($data['access_token']); + $model->setExpires($data['expires_in']); + $model->setTokenType($data['token_type']); + $model->setScope($data['scope']); + $model->setRefreshToken($data['refresh_token']); + $model->setClientId($clientId); + $model->setUserId($_SESSION['USER_LOGGED']); + + $model->save();*/ +} echo '
';
-print_r($return);
+//print_r($_SESSION);
+print_r($data);
 
 curl_close($ch);
\ No newline at end of file
diff --git a/workflow/engine/services/api/processmaker/Application.php b/workflow/engine/services/api/processmaker/Application.php
index a6ab694cf..3baf8f02a 100644
--- a/workflow/engine/services/api/processmaker/Application.php
+++ b/workflow/engine/services/api/processmaker/Application.php
@@ -3,9 +3,17 @@ namespace Services\Api\ProcessMaker;
 
 class Application extends \ProcessMaker\Api
 {
+    /**
+     * Sample api protected with OAuth2
+     *
+     * For testing the oAuth token
+     *
+     * @access protected
+     */
     public function get($id)
     {
         $data = array(
+            'USSER_LOGGED' => $this->getUserId(),
             "APP_UID" => $id,
             "PRO_UID" => "13885168416038181883131343548151",
             "DUMMY" => "sample data",
@@ -17,7 +25,6 @@ class Application extends \ProcessMaker\Api
 
     public function post($requestData = null)
     {
-        $requestData;
         $requestData['processed'] = true;
 
         return $requestData;
diff --git a/workflow/engine/services/oauth2/Server.php b/workflow/engine/services/oauth2/Server.php
index dce3cecb0..f1bb0ca2b 100644
--- a/workflow/engine/services/oauth2/Server.php
+++ b/workflow/engine/services/oauth2/Server.php
@@ -20,61 +20,58 @@ class Server implements iAuthenticate
     /**
      * @var OAuth2_Server
      */
-    //protected static $server;
     protected $server;
-    protected $storage;
-
     /**
      * @var OAuth2_Storage_Pdo
      */
-    //protected static $storage;
-    /**
-     * @var OAuth2_Request
-     */
-    protected static $request;
+    protected $storage;
+    
+    protected $scope = array();
+
+    protected static $pmClientId;
+    protected static $userId;
+
+    protected static $dbUser;
+    protected static $dbPassword;
+    protected static $dsn;
+
     public function __construct()
     {
-        /*$dir = __DIR__ . '/db/';
-        $file = 'oauth.sqlite';
-        if (!file_exists($dir . $file)) {
-            include_once $dir . 'rebuild_db.php';
-        }
-        static::$storage = new \OAuth2\Storage\Pdo(
-            array('dsn' => 'sqlite:' . $dir . $file)
-        );
-        static::$request = \OAuth2\Request::createFromGlobals();
-        static::$server = new \OAuth2\Server(static::$storage);
-        static::$server->addGrantType(
-            new \OAuth2\GrantType\AuthorizationCode(static::$storage)
-        );*/
-
-        static::$request = \OAuth2\Request::createFromGlobals();
-
         require_once 'PmPdo.php';
 
-        $dsn      = 'mysql:dbname=wf_workflow;host=localhost';
-        $username = 'root';
-        $password = 'sample';
-
-        // error reporting (this is a demo, after all!)
-        //ini_set('display_errors',1);error_reporting(E_ALL);
-
-        // Autoloading (composer is preferred, but for this example let's just do this)
-        //require_once('oauth2-server-php/src/OAuth2/Autoloader.php');
-        //\OAuth2\Autoloader::register();
+        $this->scope = array(
+            'view_processes' => 'View Processes',
+            'edit_processes' => 'Edit Processes'
+        );
 
         // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
-        $storage = new PmPdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
+        $config = array('dsn' => self::$dsn, 'username' => self::$dbUser, 'password' => self::$dbPassword);
+        //var_dump($config); die;
+        $this->storage = new PmPdo($config);
 
         // Pass a storage object or array of storage objects to the OAuth2 server class
-        $this->server = new \OAuth2\Server($storage);
-
-        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
-        $this->server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
+        $this->server = new \OAuth2\Server($this->storage);
 
         // Add the "Authorization Code" grant type (this is where the oauth magic happens)
-        $this->server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));
+        $this->server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->storage));
 
+        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
+        $this->server->addGrantType(new \OAuth2\GrantType\ClientCredentials($this->storage));
+
+        // Add the "Refresh token" grant type
+        $this->server->addGrantType(new \OAuth2\GrantType\RefreshToken($this->storage));
+
+        $scope = new \OAuth2\Scope(array(
+            'supported_scopes' => array_keys($this->scope)
+        ));
+        $this->server->setScopeUtil($scope);
+    }
+
+    public static function setDatabaseSource($user, $password, $dsn)
+    {
+        self::$dbUser = $user;
+        self::$dbPassword = $password;
+        self::$dsn = $dsn;
     }
 
     /**
@@ -83,7 +80,7 @@ class Server implements iAuthenticate
      */
     public function register()
     {
-        static::$server->getResponse(static::$request);
+        static::$server->getResponse(\OAuth2\Request::createFromGlobals());
         return array('queryString' => $_SERVER['QUERY_STRING']);
     }
 
@@ -97,10 +94,22 @@ class Server implements iAuthenticate
      */
     public function authorize()
     {
-        $this->server->getResponse(static::$request);
+        $clientId = \OAuth2\Request::createFromGlobals()->query('client_id', '');
+        $requestedScope = \OAuth2\Request::createFromGlobals()->query('scope', '');
+        $requestedScope = empty($requestedScope) ? array() : explode(' ', $requestedScope);
 
-        return array('queryString' => $_SERVER['QUERY_STRING']);
+        if (! empty($clientId)) {
+            $clientDetails = $this->storage->getClientDetails(\OAuth2\Request::createFromGlobals()->query('client_id'));
+        }
+
+        return array(
+            'client_details' => $clientDetails,
+            'query_string'   => $_SERVER['QUERY_STRING'],
+            'supportedScope' => $this->scope,
+            'requestedScope' => $requestedScope
+        );
     }
+
     /**
      * Stage 2: User response is captured here
      *
@@ -114,7 +123,7 @@ class Server implements iAuthenticate
      *
      * @format JsonFormat,UploadFormat
      */
-    public function postAuthorize($authorize = false)
+    public function postAuthorize($authorize = false, $userId = null, $returnResponse = false)
     {
         $request = \OAuth2\Request::createFromGlobals();
         $response = new \OAuth2\Response();
@@ -122,13 +131,12 @@ class Server implements iAuthenticate
         $response = $this->server->handleAuthorizeRequest(
             $request,
             $response,
-            (bool)$authorize
+            (bool)$authorize,
+            $userId
         );
 
-        if ($authorize) {
-            // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
-            $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
-            //exit("SUCCESS! Authorization Code: $code");
+        if ($returnResponse) {
+            return $response;
         }
 
         die($response->send());
@@ -142,26 +150,35 @@ class Server implements iAuthenticate
      *
      * @format JsonFormat,UploadFormat
      */
-    public function postGrant()
+    public function postToken()
     {
-        $response = static::$server->handleGrantRequest(
-            static::$request
-        );
-        die($response->send());
-    }
-    /**
-     * Sample api protected with OAuth2
-     *
-     * For testing the oAuth token
-     *
-     * @access protected
-     */
-    public function postAccess()
-    {
-        return array(
-            'friends' => array('john', 'matt', 'jane')
-        );
+        // Handle a request for an OAuth2.0 Access Token and send the response to the client
+        $request = \OAuth2\Request::createFromGlobals();
+        $response = $this->server->handleTokenRequest($request);
+
+        /* DEPREACATED
+        $token = $response->getParameters();
+        if (array_key_exists('access_token', $token)) {
+            $data = $this->storage->getAccessToken($token['access_token']);
+
+            // verify if the client is our local PM Designer client
+            if ($data['client_id'] == self::getPmClientId()) {
+                error_log('do stuff - is a request from local pm client');
+                require_once "classes/model/PmoauthUserAccessTokens.php";
+
+                $userToken = new \PmoauthUserAccessTokens();
+                $userToken->setAccessToken($token['access_token']);
+                $userToken->setRefreshToken($token['refresh_token']);
+                $userToken->setUserId($data['user_id']);
+                $userToken->setSessionId(session_id());
+
+                $userToken->save();
+            }
+        }*/
+
+        $response->send();
     }
+
     /**
      * Access verification method.
      *
@@ -171,21 +188,41 @@ class Server implements iAuthenticate
      */
     public function __isAllowed()
     {
-        return $this->server->verifyResourceRequest(\OAuth2\Request::createFromGlobals());
+        $request = \OAuth2\Request::createFromGlobals();
+        $allowed = $this->server->verifyResourceRequest($request);
+        $token = $this->server->getAccessTokenData($request);
+
+        self::$userId = $token['user_id'];
+
+        // verify if the client is our local PM Designer client
+        if ($token['client_id'] != self::getPmClientId()) {
+            return $allowed;
+        }
+
+        if (! isset($_SESSION) || ! array_key_exists('USER_LOGGED', $_SESSION)) {
+            return false;
+        }
+
+        return true;
     }
 
-
-
-    /****************************************/
-
-    /**
-     * Stage 3: Client directly calls this api to exchange access token
-     *
-     * It can then use this access token to make calls to protected api
-     */
-    public function postToken()
+    public static function setPmClientId($clientId)
     {
-        // Handle a request for an OAuth2.0 Access Token and send the response to the client
-        return $this->server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
+        self::$pmClientId = $clientId;
+    }
+
+    public static function getPmClientId()
+    {
+        return self::$pmClientId;
+    }
+
+    public function getServer()
+    {
+        return $this->server;
+    }
+
+    public function getUserId()
+    {
+        return self::$userId;
     }
 }
\ No newline at end of file
diff --git a/workflow/engine/services/oauth2/views/oauth2/server/authorize.php b/workflow/engine/services/oauth2/views/oauth2/server/authorize.php
index 8e8ffd459..c9a43e998 100644
--- a/workflow/engine/services/oauth2/views/oauth2/server/authorize.php
+++ b/workflow/engine/services/oauth2/views/oauth2/server/authorize.php
@@ -1,30 +1,29 @@
 
-    

- Demo App would like to access the following data: -

- -

It will use this data to:

- - +

+ would like to access the following data: +

+ +

It will use this data to:

+ + diff --git a/workflow/engine/templates/oauth2/authorize.php b/workflow/engine/templates/oauth2/authorize.php new file mode 100644 index 000000000..569c62289 --- /dev/null +++ b/workflow/engine/templates/oauth2/authorize.php @@ -0,0 +1,135 @@ +scope = array( + 'view_processes' => 'View Processes', + 'edit_processes' => 'Edit Processes' +); + +// $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost" +$storage = new Api\OAuth2\PmPdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password)); + + + +$clientId = $_GET['client_id']; +$requestedScope = isset($_GET['scope']) ? $_GET['scope'] : ''; +$requestedScope = empty($requestedScope) ? array() : explode(' ', $requestedScope); + +if (! empty($clientId)) { + $clientDetails = $storage->getClientDetails($clientId); + //g::pr($clientDetails); die; +} + +$response = array( + 'client_details' => $clientDetails, + 'query_string' => $_SERVER['QUERY_STRING'], + 'supportedScope' => $this->scope, + 'requestedScope' => $requestedScope +); + +?> + + + + + + + + + +
+
+ + + + + + +
+
+ +
+
+
+
+ + + + +
+ + + + + + + + + + + + + + + + + + + +
+ + would like to access the following data: + +
+ + +
    + +
  • + +
+

It will use this data to:

+
    +
  • integrate with ProcessMaker
  • +
  • make your life better
  • +
  • miscellaneous nefarious purposes
  • +
+ +
+ + + + + +
+ + +
+
+
+
+
+
+ + + + + +
+
+
+
+ + + \ No newline at end of file