Cassandra.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. try {
  121. // __data key set as C* requires a field
  122. $cf->remove($key, array('__data'));
  123. } catch (\Exception $e) {
  124. return false;
  125. }
  126. return true;
  127. }
  128. /* AuthorizationCodeInterface */
  129. public function getAuthorizationCode($code)
  130. {
  131. return $this->getValue($this->config['code_key'] . $code);
  132. }
  133. public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
  134. {
  135. return $this->setValue(
  136. $this->config['code_key'] . $authorization_code,
  137. compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'),
  138. $expires
  139. );
  140. }
  141. public function expireAuthorizationCode($code)
  142. {
  143. $key = $this->config['code_key'] . $code;
  144. unset($this->cache[$key]);
  145. return $this->expireValue($key);
  146. }
  147. /* UserCredentialsInterface */
  148. public function checkUserCredentials($username, $password)
  149. {
  150. if ($user = $this->getUser($username)) {
  151. return $this->checkPassword($user, $password);
  152. }
  153. return false;
  154. }
  155. // plaintext passwords are bad! Override this for your application
  156. protected function checkPassword($user, $password)
  157. {
  158. return $user['password'] == sha1($password);
  159. }
  160. public function getUserDetails($username)
  161. {
  162. return $this->getUser($username);
  163. }
  164. public function getUser($username)
  165. {
  166. if (!$userInfo = $this->getValue($this->config['user_key'] . $username)) {
  167. return false;
  168. }
  169. // the default behavior is to use "username" as the user_id
  170. return array_merge(array(
  171. 'user_id' => $username,
  172. ), $userInfo);
  173. }
  174. public function setUser($username, $password, $first_name = null, $last_name = null)
  175. {
  176. $password = sha1($password);
  177. return $this->setValue(
  178. $this->config['user_key'] . $username,
  179. compact('username', 'password', 'first_name', 'last_name')
  180. );
  181. }
  182. /* ClientCredentialsInterface */
  183. public function checkClientCredentials($client_id, $client_secret = null)
  184. {
  185. if (!$client = $this->getClientDetails($client_id)) {
  186. return false;
  187. }
  188. return isset($client['client_secret'])
  189. && $client['client_secret'] == $client_secret;
  190. }
  191. public function isPublicClient($client_id)
  192. {
  193. if (!$client = $this->getClientDetails($client_id)) {
  194. return false;
  195. }
  196. return empty($result['client_secret']);;
  197. }
  198. /* ClientInterface */
  199. public function getClientDetails($client_id)
  200. {
  201. return $this->getValue($this->config['client_key'] . $client_id);
  202. }
  203. public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
  204. {
  205. return $this->setValue(
  206. $this->config['client_key'] . $client_id,
  207. compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id')
  208. );
  209. }
  210. public function checkRestrictedGrantType($client_id, $grant_type)
  211. {
  212. $details = $this->getClientDetails($client_id);
  213. if (isset($details['grant_types'])) {
  214. $grant_types = explode(' ', $details['grant_types']);
  215. return in_array($grant_type, (array) $grant_types);
  216. }
  217. // if grant_types are not defined, then none are restricted
  218. return true;
  219. }
  220. /* RefreshTokenInterface */
  221. public function getRefreshToken($refresh_token)
  222. {
  223. return $this->getValue($this->config['refresh_token_key'] . $refresh_token);
  224. }
  225. public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
  226. {
  227. return $this->setValue(
  228. $this->config['refresh_token_key'] . $refresh_token,
  229. compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'),
  230. $expires
  231. );
  232. }
  233. public function unsetRefreshToken($refresh_token)
  234. {
  235. return $this->expireValue($this->config['refresh_token_key'] . $refresh_token);
  236. }
  237. /* AccessTokenInterface */
  238. public function getAccessToken($access_token)
  239. {
  240. return $this->getValue($this->config['access_token_key'].$access_token);
  241. }
  242. public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
  243. {
  244. return $this->setValue(
  245. $this->config['access_token_key'].$access_token,
  246. compact('access_token', 'client_id', 'user_id', 'expires', 'scope'),
  247. $expires
  248. );
  249. }
  250. public function unsetAccessToken($access_token)
  251. {
  252. return $this->expireValue($this->config['access_token_key'] . $access_token);
  253. }
  254. /* ScopeInterface */
  255. public function scopeExists($scope)
  256. {
  257. $scope = explode(' ', $scope);
  258. $result = $this->getValue($this->config['scope_key'].'supported:global');
  259. $supportedScope = explode(' ', (string) $result);
  260. return (count(array_diff($scope, $supportedScope)) == 0);
  261. }
  262. public function getDefaultScope($client_id = null)
  263. {
  264. if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) {
  265. $result = $this->getValue($this->config['scope_key'].'default:global');
  266. }
  267. return $result;
  268. }
  269. public function setScope($scope, $client_id = null, $type = 'supported')
  270. {
  271. if (!in_array($type, array('default', 'supported'))) {
  272. throw new \InvalidArgumentException('"$type" must be one of "default", "supported"');
  273. }
  274. if (is_null($client_id)) {
  275. $key = $this->config['scope_key'].$type.':global';
  276. } else {
  277. $key = $this->config['scope_key'].$type.':'.$client_id;
  278. }
  279. return $this->setValue($key, $scope);
  280. }
  281. /*JWTBearerInterface */
  282. public function getClientKey($client_id, $subject)
  283. {
  284. if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) {
  285. return false;
  286. }
  287. if (isset($jwt['subject']) && $jwt['subject'] == $subject ) {
  288. return $jwt['key'];
  289. }
  290. return null;
  291. }
  292. public function setClientKey($client_id, $key, $subject = null)
  293. {
  294. return $this->setValue($this->config['jwt_key'] . $client_id, array(
  295. 'key' => $key,
  296. 'subject' => $subject
  297. ));
  298. }
  299. /*ScopeInterface */
  300. public function getClientScope($client_id)
  301. {
  302. if (!$clientDetails = $this->getClientDetails($client_id)) {
  303. return false;
  304. }
  305. if (isset($clientDetails['scope'])) {
  306. return $clientDetails['scope'];
  307. }
  308. return null;
  309. }
  310. public function getJti($client_id, $subject, $audience, $expiration, $jti)
  311. {
  312. //TODO: Needs cassandra implementation.
  313. throw new \Exception('getJti() for the Cassandra driver is currently unimplemented.');
  314. }
  315. public function setJti($client_id, $subject, $audience, $expiration, $jti)
  316. {
  317. //TODO: Needs cassandra implementation.
  318. throw new \Exception('setJti() for the Cassandra driver is currently unimplemented.');
  319. }
  320. /* PublicKeyInterface */
  321. public function getPublicKey($client_id = '')
  322. {
  323. $public_key = $this->getValue($this->config['public_key_key'] . $client_id);
  324. if (is_array($public_key)) {
  325. return $public_key['public_key'];
  326. }
  327. $public_key = $this->getValue($this->config['public_key_key']);
  328. if (is_array($public_key)) {
  329. return $public_key['public_key'];
  330. }
  331. }
  332. public function getPrivateKey($client_id = '')
  333. {
  334. $public_key = $this->getValue($this->config['public_key_key'] . $client_id);
  335. if (is_array($public_key)) {
  336. return $public_key['private_key'];
  337. }
  338. $public_key = $this->getValue($this->config['public_key_key']);
  339. if (is_array($public_key)) {
  340. return $public_key['private_key'];
  341. }
  342. }
  343. public function getEncryptionAlgorithm($client_id = null)
  344. {
  345. $public_key = $this->getValue($this->config['public_key_key'] . $client_id);
  346. if (is_array($public_key)) {
  347. return $public_key['encryption_algorithm'];
  348. }
  349. $public_key = $this->getValue($this->config['public_key_key']);
  350. if (is_array($public_key)) {
  351. return $public_key['encryption_algorithm'];
  352. }
  353. return 'RS256';
  354. }
  355. /* UserClaimsInterface */
  356. public function getUserClaims($user_id, $claims)
  357. {
  358. $userDetails = $this->getUserDetails($user_id);
  359. if (!is_array($userDetails)) {
  360. return false;
  361. }
  362. $claims = explode(' ', trim($claims));
  363. $userClaims = array();
  364. // for each requested claim, if the user has the claim, set it in the response
  365. $validClaims = explode(' ', self::VALID_CLAIMS);
  366. foreach ($validClaims as $validClaim) {
  367. if (in_array($validClaim, $claims)) {
  368. if ($validClaim == 'address') {
  369. // address is an object with subfields
  370. $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails);
  371. } else {
  372. $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails));
  373. }
  374. }
  375. }
  376. return $userClaims;
  377. }
  378. protected function getUserClaim($claim, $userDetails)
  379. {
  380. $userClaims = array();
  381. $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim)));
  382. $claimValues = explode(' ', $claimValuesString);
  383. foreach ($claimValues as $value) {
  384. if ($value == 'email_verified') {
  385. $userClaims[$value] = $userDetails[$value]=='true' ? true : false;
  386. } else {
  387. $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null;
  388. }
  389. }
  390. return $userClaims;
  391. }
  392. }