Redis.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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($result['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. return $this->expireValue($this->config['refresh_token_key'] . $refresh_token);
  179. }
  180. /* AccessTokenInterface */
  181. public function getAccessToken($access_token)
  182. {
  183. return $this->getValue($this->config['access_token_key'].$access_token);
  184. }
  185. public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
  186. {
  187. return $this->setValue(
  188. $this->config['access_token_key'].$access_token,
  189. compact('access_token', 'client_id', 'user_id', 'expires', 'scope'),
  190. $expires
  191. );
  192. }
  193. public function unsetAccessToken($access_token)
  194. {
  195. return $this->expireValue($this->config['access_token_key'] . $access_token);
  196. }
  197. /* ScopeInterface */
  198. public function scopeExists($scope)
  199. {
  200. $scope = explode(' ', $scope);
  201. $result = $this->getValue($this->config['scope_key'].'supported:global');
  202. $supportedScope = explode(' ', (string) $result);
  203. return (count(array_diff($scope, $supportedScope)) == 0);
  204. }
  205. public function getDefaultScope($client_id = null)
  206. {
  207. if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) {
  208. $result = $this->getValue($this->config['scope_key'].'default:global');
  209. }
  210. return $result;
  211. }
  212. public function setScope($scope, $client_id = null, $type = 'supported')
  213. {
  214. if (!in_array($type, array('default', 'supported'))) {
  215. throw new \InvalidArgumentException('"$type" must be one of "default", "supported"');
  216. }
  217. if (is_null($client_id)) {
  218. $key = $this->config['scope_key'].$type.':global';
  219. } else {
  220. $key = $this->config['scope_key'].$type.':'.$client_id;
  221. }
  222. return $this->setValue($key, $scope);
  223. }
  224. /*JWTBearerInterface */
  225. public function getClientKey($client_id, $subject)
  226. {
  227. if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) {
  228. return false;
  229. }
  230. if (isset($jwt['subject']) && $jwt['subject'] == $subject) {
  231. return $jwt['key'];
  232. }
  233. return null;
  234. }
  235. public function setClientKey($client_id, $key, $subject = null)
  236. {
  237. return $this->setValue($this->config['jwt_key'] . $client_id, array(
  238. 'key' => $key,
  239. 'subject' => $subject
  240. ));
  241. }
  242. public function getClientScope($client_id)
  243. {
  244. if (!$clientDetails = $this->getClientDetails($client_id)) {
  245. return false;
  246. }
  247. if (isset($clientDetails['scope'])) {
  248. return $clientDetails['scope'];
  249. }
  250. return null;
  251. }
  252. public function getJti($client_id, $subject, $audience, $expiration, $jti)
  253. {
  254. //TODO: Needs redis implementation.
  255. throw new \Exception('getJti() for the Redis driver is currently unimplemented.');
  256. }
  257. public function setJti($client_id, $subject, $audience, $expiration, $jti)
  258. {
  259. //TODO: Needs redis implementation.
  260. throw new \Exception('setJti() for the Redis driver is currently unimplemented.');
  261. }
  262. }