Redis.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <?php
  2. namespace OAuth2\Storage;
  3. use OAuth2\OpenID\Storage\AuthorizationCodeInterface as OpenIDAuthorizationCodeInterface;
  4. /**
  5. * redis storage for all storage types
  6. *
  7. * To use, install "predis/predis" via composer
  8. *
  9. * Register client:
  10. * <code>
  11. * $storage = new OAuth2\Storage\Redis($redis);
  12. * $storage->setClientDetails($client_id, $client_secret, $redirect_uri);
  13. * </code>
  14. */
  15. class Redis implements AuthorizationCodeInterface,
  16. AccessTokenInterface,
  17. ClientCredentialsInterface,
  18. UserCredentialsInterface,
  19. RefreshTokenInterface,
  20. JwtBearerInterface,
  21. ScopeInterface,
  22. OpenIDAuthorizationCodeInterface
  23. {
  24. private $cache;
  25. /* The redis client */
  26. protected $redis;
  27. /* Configuration array */
  28. protected $config;
  29. /**
  30. * Redis Storage!
  31. *
  32. * @param \Predis\Client $redis
  33. * @param array $config
  34. */
  35. public function __construct($redis, $config=array())
  36. {
  37. $this->redis = $redis;
  38. $this->config = array_merge(array(
  39. 'client_key' => 'oauth_clients:',
  40. 'access_token_key' => 'oauth_access_tokens:',
  41. 'refresh_token_key' => 'oauth_refresh_tokens:',
  42. 'code_key' => 'oauth_authorization_codes:',
  43. 'user_key' => 'oauth_users:',
  44. 'jwt_key' => 'oauth_jwt:',
  45. 'scope_key' => 'oauth_scopes:',
  46. ), $config);
  47. }
  48. protected function getValue($key)
  49. {
  50. if ( isset($this->cache[$key]) ) {
  51. return $this->cache[$key];
  52. }
  53. $value = $this->redis->get($key);
  54. if ( isset($value) ) {
  55. return json_decode($value, true);
  56. } else {
  57. return false;
  58. }
  59. }
  60. protected function setValue($key, $value, $expire=0)
  61. {
  62. $this->cache[$key] = $value;
  63. $str = json_encode($value);
  64. if ($expire > 0) {
  65. $seconds = $expire - time();
  66. $ret = $this->redis->setex($key, $seconds, $str);
  67. } else {
  68. $ret = $this->redis->set($key, $str);
  69. }
  70. // check that the key was set properly
  71. // if this fails, an exception will usually thrown, so this step isn't strictly necessary
  72. return is_bool($ret) ? $ret : $ret->getPayload() == 'OK';
  73. }
  74. protected function expireValue($key)
  75. {
  76. unset($this->cache[$key]);
  77. return $this->redis->del($key);
  78. }
  79. /* AuthorizationCodeInterface */
  80. public function getAuthorizationCode($code)
  81. {
  82. return $this->getValue($this->config['code_key'] . $code);
  83. }
  84. public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
  85. {
  86. return $this->setValue(
  87. $this->config['code_key'] . $authorization_code,
  88. compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'),
  89. $expires
  90. );
  91. }
  92. public function expireAuthorizationCode($code)
  93. {
  94. $key = $this->config['code_key'] . $code;
  95. unset($this->cache[$key]);
  96. return $this->expireValue($key);
  97. }
  98. /* UserCredentialsInterface */
  99. public function checkUserCredentials($username, $password)
  100. {
  101. $user = $this->getUserDetails($username);
  102. return $user && $user['password'] === $password;
  103. }
  104. public function getUserDetails($username)
  105. {
  106. return $this->getUser($username);
  107. }
  108. public function getUser($username)
  109. {
  110. if (!$userInfo = $this->getValue($this->config['user_key'] . $username)) {
  111. return false;
  112. }
  113. // the default behavior is to use "username" as the user_id
  114. return array_merge(array(
  115. 'user_id' => $username,
  116. ), $userInfo);
  117. }
  118. public function setUser($username, $password, $first_name = null, $last_name = null)
  119. {
  120. return $this->setValue(
  121. $this->config['user_key'] . $username,
  122. compact('username', 'password', 'first_name', 'last_name')
  123. );
  124. }
  125. /* ClientCredentialsInterface */
  126. public function checkClientCredentials($client_id, $client_secret = null)
  127. {
  128. if (!$client = $this->getClientDetails($client_id)) {
  129. return false;
  130. }
  131. return isset($client['client_secret'])
  132. && $client['client_secret'] == $client_secret;
  133. }
  134. public function isPublicClient($client_id)
  135. {
  136. if (!$client = $this->getClientDetails($client_id)) {
  137. return false;
  138. }
  139. return empty($client['client_secret']);
  140. }
  141. /* ClientInterface */
  142. public function getClientDetails($client_id)
  143. {
  144. return $this->getValue($this->config['client_key'] . $client_id);
  145. }
  146. public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
  147. {
  148. return $this->setValue(
  149. $this->config['client_key'] . $client_id,
  150. compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id')
  151. );
  152. }
  153. public function checkRestrictedGrantType($client_id, $grant_type)
  154. {
  155. $details = $this->getClientDetails($client_id);
  156. if (isset($details['grant_types'])) {
  157. $grant_types = explode(' ', $details['grant_types']);
  158. return in_array($grant_type, (array) $grant_types);
  159. }
  160. // if grant_types are not defined, then none are restricted
  161. return true;
  162. }
  163. /* RefreshTokenInterface */
  164. public function getRefreshToken($refresh_token)
  165. {
  166. return $this->getValue($this->config['refresh_token_key'] . $refresh_token);
  167. }
  168. public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
  169. {
  170. return $this->setValue(
  171. $this->config['refresh_token_key'] . $refresh_token,
  172. compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'),
  173. $expires
  174. );
  175. }
  176. public function unsetRefreshToken($refresh_token)
  177. {
  178. $result = $this->expireValue($this->config['refresh_token_key'] . $refresh_token);
  179. return $result > 0;
  180. }
  181. /* AccessTokenInterface */
  182. public function getAccessToken($access_token)
  183. {
  184. return $this->getValue($this->config['access_token_key'].$access_token);
  185. }
  186. public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
  187. {
  188. return $this->setValue(
  189. $this->config['access_token_key'].$access_token,
  190. compact('access_token', 'client_id', 'user_id', 'expires', 'scope'),
  191. $expires
  192. );
  193. }
  194. public function unsetAccessToken($access_token)
  195. {
  196. $result = $this->expireValue($this->config['access_token_key'] . $access_token);
  197. return $result > 0;
  198. }
  199. /* ScopeInterface */
  200. public function scopeExists($scope)
  201. {
  202. $scope = explode(' ', $scope);
  203. $result = $this->getValue($this->config['scope_key'].'supported:global');
  204. $supportedScope = explode(' ', (string) $result);
  205. return (count(array_diff($scope, $supportedScope)) == 0);
  206. }
  207. public function getDefaultScope($client_id = null)
  208. {
  209. if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) {
  210. $result = $this->getValue($this->config['scope_key'].'default:global');
  211. }
  212. return $result;
  213. }
  214. public function setScope($scope, $client_id = null, $type = 'supported')
  215. {
  216. if (!in_array($type, array('default', 'supported'))) {
  217. throw new \InvalidArgumentException('"$type" must be one of "default", "supported"');
  218. }
  219. if (is_null($client_id)) {
  220. $key = $this->config['scope_key'].$type.':global';
  221. } else {
  222. $key = $this->config['scope_key'].$type.':'.$client_id;
  223. }
  224. return $this->setValue($key, $scope);
  225. }
  226. /*JWTBearerInterface */
  227. public function getClientKey($client_id, $subject)
  228. {
  229. if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) {
  230. return false;
  231. }
  232. if (isset($jwt['subject']) && $jwt['subject'] == $subject) {
  233. return $jwt['key'];
  234. }
  235. return null;
  236. }
  237. public function setClientKey($client_id, $key, $subject = null)
  238. {
  239. return $this->setValue($this->config['jwt_key'] . $client_id, array(
  240. 'key' => $key,
  241. 'subject' => $subject
  242. ));
  243. }
  244. public function getClientScope($client_id)
  245. {
  246. if (!$clientDetails = $this->getClientDetails($client_id)) {
  247. return false;
  248. }
  249. if (isset($clientDetails['scope'])) {
  250. return $clientDetails['scope'];
  251. }
  252. return null;
  253. }
  254. public function getJti($client_id, $subject, $audience, $expiration, $jti)
  255. {
  256. //TODO: Needs redis implementation.
  257. throw new \Exception('getJti() for the Redis driver is currently unimplemented.');
  258. }
  259. public function setJti($client_id, $subject, $audience, $expiration, $jti)
  260. {
  261. //TODO: Needs redis implementation.
  262. throw new \Exception('setJti() for the Redis driver is currently unimplemented.');
  263. }
  264. }