Cassandra.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. namespace OAuth2\Storage;
  3. use phpcassa\ColumnFamily;
  4. use phpcassa\ColumnSlice;
  5. use phpcassa\Connection\ConnectionPool;
  6. use OAuth2\OpenID\Storage\UserClaimsInterface;
  7. use OAuth2\OpenID\Storage\AuthorizationCodeInterface as OpenIDAuthorizationCodeInterface;
  8. /**
  9. * Cassandra storage for all storage types
  10. *
  11. * To use, install "thobbs/phpcassa" via composer
  12. * <code>
  13. * composer require thobbs/phpcassa:dev-master
  14. * </code>
  15. *
  16. * Once this is done, instantiate the
  17. * <code>
  18. * $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_server', array('127.0.0.1:9160'));
  19. * </code>
  20. *
  21. * Then, register the storage client:
  22. * <code>
  23. * $storage = new OAuth2\Storage\Cassandra($cassandra);
  24. * $storage->setClientDetails($client_id, $client_secret, $redirect_uri);
  25. * </code>
  26. *
  27. * @see test/lib/OAuth2/Storage/Bootstrap::getCassandraStorage
  28. */
  29. class Cassandra implements AuthorizationCodeInterface,
  30. AccessTokenInterface,
  31. ClientCredentialsInterface,
  32. UserCredentialsInterface,
  33. RefreshTokenInterface,
  34. JwtBearerInterface,
  35. ScopeInterface,
  36. PublicKeyInterface,
  37. UserClaimsInterface,
  38. OpenIDAuthorizationCodeInterface
  39. {
  40. private $cache;
  41. /* The cassandra client */
  42. protected $cassandra;
  43. /* Configuration array */
  44. protected $config;
  45. /**
  46. * Cassandra Storage! uses phpCassa
  47. *
  48. * @param \phpcassa\ConnectionPool $cassandra
  49. * @param array $config
  50. */
  51. public function __construct($connection = array(), array $config = array())
  52. {
  53. if ($connection instanceof ConnectionPool) {
  54. $this->cassandra = $connection;
  55. } else {
  56. if (!is_array($connection)) {
  57. throw new \InvalidArgumentException('First argument to OAuth2\Storage\Cassandra must be an instance of phpcassa\Connection\ConnectionPool or a configuration array');
  58. }
  59. $connection = array_merge(array(
  60. 'keyspace' => 'oauth2',
  61. 'servers' => null,
  62. ), $connection);
  63. $this->cassandra = new ConnectionPool($connection['keyspace'], $connection['servers']);
  64. }
  65. $this->config = array_merge(array(
  66. // cassandra config
  67. 'column_family' => 'auth',
  68. // key names
  69. 'client_key' => 'oauth_clients:',
  70. 'access_token_key' => 'oauth_access_tokens:',
  71. 'refresh_token_key' => 'oauth_refresh_tokens:',
  72. 'code_key' => 'oauth_authorization_codes:',
  73. 'user_key' => 'oauth_users:',
  74. 'jwt_key' => 'oauth_jwt:',
  75. 'scope_key' => 'oauth_scopes:',
  76. 'public_key_key' => 'oauth_public_keys:',
  77. ), $config);
  78. }
  79. protected function getValue($key)
  80. {
  81. if (isset($this->cache[$key])) {
  82. return $this->cache[$key];
  83. }
  84. $cf = new ColumnFamily($this->cassandra, $this->config['column_family']);
  85. try {
  86. $value = $cf->get($key, new ColumnSlice("", ""));
  87. $value = array_shift($value);
  88. } catch (\cassandra\NotFoundException $e) {
  89. return false;
  90. }
  91. return json_decode($value, true);
  92. }
  93. protected function setValue($key, $value, $expire = 0)
  94. {
  95. $this->cache[$key] = $value;
  96. $cf = new ColumnFamily($this->cassandra, $this->config['column_family']);
  97. $str = json_encode($value);
  98. if ($expire > 0) {
  99. try {
  100. $seconds = $expire - time();
  101. // __data key set as C* requires a field, note: max TTL can only be 630720000 seconds
  102. $cf->insert($key, array('__data' => $str), null, $seconds);
  103. } catch (\Exception $e) {
  104. return false;
  105. }
  106. } else {
  107. try {
  108. // __data key set as C* requires a field
  109. $cf->insert($key, array('__data' => $str));
  110. } catch (\Exception $e) {
  111. return false;
  112. }
  113. }
  114. return true;
  115. }
  116. protected function expireValue($key)
  117. {
  118. unset($this->cache[$key]);
  119. $cf = new ColumnFamily($this->cassandra, $this->config['column_family']);
  120. if ($cf->get_count($key) > 0) {
  121. try {
  122. // __data key set as C* requires a field
  123. $cf->remove($key, array('__data'));
  124. } catch (\Exception $e) {
  125. return false;
  126. }
  127. return true;
  128. }
  129. return false;
  130. }
  131. /* AuthorizationCodeInterface */
  132. public function getAuthorizationCode($code)
  133. {
  134. return $this->getValue($this->config['code_key'] . $code);
  135. }
  136. public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
  137. {
  138. return $this->setValue(
  139. $this->config['code_key'] . $authorization_code,
  140. compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'),
  141. $expires
  142. );
  143. }
  144. public function expireAuthorizationCode($code)
  145. {
  146. $key = $this->config['code_key'] . $code;
  147. unset($this->cache[$key]);
  148. return $this->expireValue($key);
  149. }
  150. /* UserCredentialsInterface */
  151. public function checkUserCredentials($username, $password)
  152. {
  153. if ($user = $this->getUser($username)) {
  154. return $this->checkPassword($user, $password);
  155. }
  156. return false;
  157. }
  158. // plaintext passwords are bad! Override this for your application
  159. protected function checkPassword($user, $password)
  160. {
  161. return $user['password'] == $this->hashPassword($password);
  162. }
  163. // use a secure hashing algorithm when storing passwords. Override this for your application
  164. protected function hashPassword($password)
  165. {
  166. return sha1($password);
  167. }
  168. public function getUserDetails($username)
  169. {
  170. return $this->getUser($username);
  171. }
  172. public function getUser($username)
  173. {
  174. if (!$userInfo = $this->getValue($this->config['user_key'] . $username)) {
  175. return false;
  176. }
  177. // the default behavior is to use "username" as the user_id
  178. return array_merge(array(
  179. 'user_id' => $username,
  180. ), $userInfo);
  181. }
  182. public function setUser($username, $password, $first_name = null, $last_name = null)
  183. {
  184. $password = $this->hashPassword($password);
  185. return $this->setValue(
  186. $this->config['user_key'] . $username,
  187. compact('username', 'password', 'first_name', 'last_name')
  188. );
  189. }
  190. /* ClientCredentialsInterface */
  191. public function checkClientCredentials($client_id, $client_secret = null)
  192. {
  193. if (!$client = $this->getClientDetails($client_id)) {
  194. return false;
  195. }
  196. return isset($client['client_secret'])
  197. && $client['client_secret'] == $client_secret;
  198. }
  199. public function isPublicClient($client_id)
  200. {
  201. if (!$client = $this->getClientDetails($client_id)) {
  202. return false;
  203. }
  204. return empty($client['client_secret']);
  205. }
  206. /* ClientInterface */
  207. public function getClientDetails($client_id)
  208. {
  209. return $this->getValue($this->config['client_key'] . $client_id);
  210. }
  211. public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
  212. {
  213. return $this->setValue(
  214. $this->config['client_key'] . $client_id,
  215. compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id')
  216. );
  217. }
  218. public function checkRestrictedGrantType($client_id, $grant_type)
  219. {
  220. $details = $this->getClientDetails($client_id);
  221. if (isset($details['grant_types'])) {
  222. $grant_types = explode(' ', $details['grant_types']);
  223. return in_array($grant_type, (array) $grant_types);
  224. }
  225. // if grant_types are not defined, then none are restricted
  226. return true;
  227. }
  228. /* RefreshTokenInterface */
  229. public function getRefreshToken($refresh_token)
  230. {
  231. return $this->getValue($this->config['refresh_token_key'] . $refresh_token);
  232. }
  233. public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
  234. {
  235. return $this->setValue(
  236. $this->config['refresh_token_key'] . $refresh_token,
  237. compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'),
  238. $expires
  239. );
  240. }
  241. public function unsetRefreshToken($refresh_token)
  242. {
  243. return $this->expireValue($this->config['refresh_token_key'] . $refresh_token);
  244. }
  245. /* AccessTokenInterface */
  246. public function getAccessToken($access_token)
  247. {
  248. return $this->getValue($this->config['access_token_key'].$access_token);
  249. }
  250. public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
  251. {
  252. return $this->setValue(
  253. $this->config['access_token_key'].$access_token,
  254. compact('access_token', 'client_id', 'user_id', 'expires', 'scope'),
  255. $expires
  256. );
  257. }
  258. public function unsetAccessToken($access_token)
  259. {
  260. return $this->expireValue($this->config['access_token_key'] . $access_token);
  261. }
  262. /* ScopeInterface */
  263. public function scopeExists($scope)
  264. {
  265. $scope = explode(' ', $scope);
  266. $result = $this->getValue($this->config['scope_key'].'supported:global');
  267. $supportedScope = explode(' ', (string) $result);
  268. return (count(array_diff($scope, $supportedScope)) == 0);
  269. }
  270. public function getDefaultScope($client_id = null)
  271. {
  272. if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) {
  273. $result = $this->getValue($this->config['scope_key'].'default:global');
  274. }
  275. return $result;
  276. }
  277. public function setScope($scope, $client_id = null, $type = 'supported')
  278. {
  279. if (!in_array($type, array('default', 'supported'))) {
  280. throw new \InvalidArgumentException('"$type" must be one of "default", "supported"');
  281. }
  282. if (is_null($client_id)) {
  283. $key = $this->config['scope_key'].$type.':global';
  284. } else {
  285. $key = $this->config['scope_key'].$type.':'.$client_id;
  286. }
  287. return $this->setValue($key, $scope);
  288. }
  289. /*JWTBearerInterface */
  290. public function getClientKey($client_id, $subject)
  291. {
  292. if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) {
  293. return false;
  294. }
  295. if (isset($jwt['subject']) && $jwt['subject'] == $subject ) {
  296. return $jwt['key'];
  297. }
  298. return null;
  299. }
  300. public function setClientKey($client_id, $key, $subject = null)
  301. {
  302. return $this->setValue($this->config['jwt_key'] . $client_id, array(
  303. 'key' => $key,
  304. 'subject' => $subject
  305. ));
  306. }
  307. /*ScopeInterface */
  308. public function getClientScope($client_id)
  309. {
  310. if (!$clientDetails = $this->getClientDetails($client_id)) {
  311. return false;
  312. }
  313. if (isset($clientDetails['scope'])) {
  314. return $clientDetails['scope'];
  315. }
  316. return null;
  317. }
  318. public function getJti($client_id, $subject, $audience, $expiration, $jti)
  319. {
  320. //TODO: Needs cassandra implementation.
  321. throw new \Exception('getJti() for the Cassandra driver is currently unimplemented.');
  322. }
  323. public function setJti($client_id, $subject, $audience, $expiration, $jti)
  324. {
  325. //TODO: Needs cassandra implementation.
  326. throw new \Exception('setJti() for the Cassandra driver is currently unimplemented.');
  327. }
  328. /* PublicKeyInterface */
  329. public function getPublicKey($client_id = '')
  330. {
  331. $public_key = $this->getValue($this->config['public_key_key'] . $client_id);
  332. if (is_array($public_key)) {
  333. return $public_key['public_key'];
  334. }
  335. $public_key = $this->getValue($this->config['public_key_key']);
  336. if (is_array($public_key)) {
  337. return $public_key['public_key'];
  338. }
  339. }
  340. public function getPrivateKey($client_id = '')
  341. {
  342. $public_key = $this->getValue($this->config['public_key_key'] . $client_id);
  343. if (is_array($public_key)) {
  344. return $public_key['private_key'];
  345. }
  346. $public_key = $this->getValue($this->config['public_key_key']);
  347. if (is_array($public_key)) {
  348. return $public_key['private_key'];
  349. }
  350. }
  351. public function getEncryptionAlgorithm($client_id = null)
  352. {
  353. $public_key = $this->getValue($this->config['public_key_key'] . $client_id);
  354. if (is_array($public_key)) {
  355. return $public_key['encryption_algorithm'];
  356. }
  357. $public_key = $this->getValue($this->config['public_key_key']);
  358. if (is_array($public_key)) {
  359. return $public_key['encryption_algorithm'];
  360. }
  361. return 'RS256';
  362. }
  363. /* UserClaimsInterface */
  364. public function getUserClaims($user_id, $claims)
  365. {
  366. $userDetails = $this->getUserDetails($user_id);
  367. if (!is_array($userDetails)) {
  368. return false;
  369. }
  370. $claims = explode(' ', trim($claims));
  371. $userClaims = array();
  372. // for each requested claim, if the user has the claim, set it in the response
  373. $validClaims = explode(' ', self::VALID_CLAIMS);
  374. foreach ($validClaims as $validClaim) {
  375. if (in_array($validClaim, $claims)) {
  376. if ($validClaim == 'address') {
  377. // address is an object with subfields
  378. $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails);
  379. } else {
  380. $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails));
  381. }
  382. }
  383. }
  384. return $userClaims;
  385. }
  386. protected function getUserClaim($claim, $userDetails)
  387. {
  388. $userClaims = array();
  389. $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim)));
  390. $claimValues = explode(' ', $claimValuesString);
  391. foreach ($claimValues as $value) {
  392. if ($value == 'email_verified') {
  393. $userClaims[$value] = $userDetails[$value]=='true' ? true : false;
  394. } else {
  395. $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null;
  396. }
  397. }
  398. return $userClaims;
  399. }
  400. }