1
0

Pdo.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. <?php
  2. namespace OAuth2\Storage;
  3. use OAuth2\OpenID\Storage\UserClaimsInterface;
  4. use OAuth2\OpenID\Storage\AuthorizationCodeInterface as OpenIDAuthorizationCodeInterface;
  5. /**
  6. * Simple PDO storage for all storage types
  7. *
  8. * NOTE: This class is meant to get users started
  9. * quickly. If your application requires further
  10. * customization, extend this class or create your own.
  11. *
  12. * NOTE: Passwords are stored in plaintext, which is never
  13. * a good idea. Be sure to override this for your application
  14. *
  15. * @author Brent Shaffer <bshafs at gmail dot com>
  16. */
  17. class Pdo implements
  18. AuthorizationCodeInterface,
  19. AccessTokenInterface,
  20. ClientCredentialsInterface,
  21. UserCredentialsInterface,
  22. RefreshTokenInterface,
  23. JwtBearerInterface,
  24. ScopeInterface,
  25. PublicKeyInterface,
  26. UserClaimsInterface,
  27. OpenIDAuthorizationCodeInterface
  28. {
  29. protected $db;
  30. protected $config;
  31. public function __construct($connection, $config = array())
  32. {
  33. if (!$connection instanceof \PDO) {
  34. if (is_string($connection)) {
  35. $connection = array('dsn' => $connection);
  36. }
  37. if (!is_array($connection)) {
  38. throw new \InvalidArgumentException('First argument to OAuth2\Storage\Pdo must be an instance of PDO, a DSN string, or a configuration array');
  39. }
  40. if (!isset($connection['dsn'])) {
  41. throw new \InvalidArgumentException('configuration array must contain "dsn"');
  42. }
  43. // merge optional parameters
  44. $connection = array_merge(array(
  45. 'username' => null,
  46. 'password' => null,
  47. 'options' => array(),
  48. ), $connection);
  49. $connection = new \PDO($connection['dsn'], $connection['username'], $connection['password'], $connection['options']);
  50. }
  51. $this->db = $connection;
  52. // debugging
  53. $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  54. $this->config = array_merge(array(
  55. 'client_table' => 'oauth_clients',
  56. 'access_token_table' => 'oauth_access_tokens',
  57. 'refresh_token_table' => 'oauth_refresh_tokens',
  58. 'code_table' => 'oauth_authorization_codes',
  59. 'user_table' => 'oauth_users',
  60. 'jwt_table' => 'oauth_jwt',
  61. 'jti_table' => 'oauth_jti',
  62. 'scope_table' => 'oauth_scopes',
  63. 'public_key_table' => 'oauth_public_keys',
  64. ), $config);
  65. }
  66. /* OAuth2\Storage\ClientCredentialsInterface */
  67. public function checkClientCredentials($client_id, $client_secret = null)
  68. {
  69. $stmt = $this->db->prepare(sprintf('SELECT * from %s where client_id = :client_id', $this->config['client_table']));
  70. $stmt->execute(compact('client_id'));
  71. $result = $stmt->fetch(\PDO::FETCH_ASSOC);
  72. // make this extensible
  73. return $result && $result['client_secret'] == $client_secret;
  74. }
  75. public function isPublicClient($client_id)
  76. {
  77. $stmt = $this->db->prepare(sprintf('SELECT * from %s where client_id = :client_id', $this->config['client_table']));
  78. $stmt->execute(compact('client_id'));
  79. if (!$result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  80. return false;
  81. }
  82. return empty($result['client_secret']);
  83. }
  84. /* OAuth2\Storage\ClientInterface */
  85. public function getClientDetails($client_id)
  86. {
  87. $stmt = $this->db->prepare(sprintf('SELECT * from %s where client_id = :client_id', $this->config['client_table']));
  88. $stmt->execute(compact('client_id'));
  89. return $stmt->fetch(\PDO::FETCH_ASSOC);
  90. }
  91. public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
  92. {
  93. // if it exists, update it.
  94. if ($this->getClientDetails($client_id)) {
  95. $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET client_secret=:client_secret, redirect_uri=:redirect_uri, grant_types=:grant_types, scope=:scope, user_id=:user_id where client_id=:client_id', $this->config['client_table']));
  96. } else {
  97. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (client_id, client_secret, redirect_uri, grant_types, scope, user_id) VALUES (:client_id, :client_secret, :redirect_uri, :grant_types, :scope, :user_id)', $this->config['client_table']));
  98. }
  99. return $stmt->execute(compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id'));
  100. }
  101. public function checkRestrictedGrantType($client_id, $grant_type)
  102. {
  103. $details = $this->getClientDetails($client_id);
  104. if (isset($details['grant_types'])) {
  105. $grant_types = explode(' ', $details['grant_types']);
  106. return in_array($grant_type, (array) $grant_types);
  107. }
  108. // if grant_types are not defined, then none are restricted
  109. return true;
  110. }
  111. /* OAuth2\Storage\AccessTokenInterface */
  112. public function getAccessToken($access_token)
  113. {
  114. $stmt = $this->db->prepare(sprintf('SELECT * from %s where access_token = :access_token', $this->config['access_token_table']));
  115. $token = $stmt->execute(compact('access_token'));
  116. if ($token = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  117. // convert date string back to timestamp
  118. $token['expires'] = strtotime($token['expires']);
  119. }
  120. return $token;
  121. }
  122. public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
  123. {
  124. // convert expires to datestring
  125. $expires = date('Y-m-d H:i:s', $expires);
  126. // if it exists, update it.
  127. if ($this->getAccessToken($access_token)) {
  128. $stmt = $this->db->prepare(sprintf('UPDATE %s SET client_id=:client_id, expires=:expires, user_id=:user_id, scope=:scope where access_token=:access_token', $this->config['access_token_table']));
  129. } else {
  130. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (access_token, client_id, expires, user_id, scope) VALUES (:access_token, :client_id, :expires, :user_id, :scope)', $this->config['access_token_table']));
  131. }
  132. return $stmt->execute(compact('access_token', 'client_id', 'user_id', 'expires', 'scope'));
  133. }
  134. public function unsetAccessToken($access_token)
  135. {
  136. $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE access_token = :access_token', $this->config['access_token_table']));
  137. $stmt->execute(compact('access_token'));
  138. return $stmt->rowCount() > 0;
  139. }
  140. /* OAuth2\Storage\AuthorizationCodeInterface */
  141. public function getAuthorizationCode($code)
  142. {
  143. $stmt = $this->db->prepare(sprintf('SELECT * from %s where authorization_code = :code', $this->config['code_table']));
  144. $stmt->execute(compact('code'));
  145. if ($code = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  146. // convert date string back to timestamp
  147. $code['expires'] = strtotime($code['expires']);
  148. }
  149. return $code;
  150. }
  151. public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
  152. {
  153. if (func_num_args() > 6) {
  154. // we are calling with an id token
  155. return call_user_func_array(array($this, 'setAuthorizationCodeWithIdToken'), func_get_args());
  156. }
  157. // convert expires to datestring
  158. $expires = date('Y-m-d H:i:s', $expires);
  159. // if it exists, update it.
  160. if ($this->getAuthorizationCode($code)) {
  161. $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET client_id=:client_id, user_id=:user_id, redirect_uri=:redirect_uri, expires=:expires, scope=:scope where authorization_code=:code', $this->config['code_table']));
  162. } else {
  163. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (authorization_code, client_id, user_id, redirect_uri, expires, scope) VALUES (:code, :client_id, :user_id, :redirect_uri, :expires, :scope)', $this->config['code_table']));
  164. }
  165. return $stmt->execute(compact('code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope'));
  166. }
  167. private function setAuthorizationCodeWithIdToken($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
  168. {
  169. // convert expires to datestring
  170. $expires = date('Y-m-d H:i:s', $expires);
  171. // if it exists, update it.
  172. if ($this->getAuthorizationCode($code)) {
  173. $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET client_id=:client_id, user_id=:user_id, redirect_uri=:redirect_uri, expires=:expires, scope=:scope, id_token =:id_token where authorization_code=:code', $this->config['code_table']));
  174. } else {
  175. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (authorization_code, client_id, user_id, redirect_uri, expires, scope, id_token) VALUES (:code, :client_id, :user_id, :redirect_uri, :expires, :scope, :id_token)', $this->config['code_table']));
  176. }
  177. return $stmt->execute(compact('code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'));
  178. }
  179. public function expireAuthorizationCode($code)
  180. {
  181. $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE authorization_code = :code', $this->config['code_table']));
  182. return $stmt->execute(compact('code'));
  183. }
  184. /* OAuth2\Storage\UserCredentialsInterface */
  185. public function checkUserCredentials($username, $password)
  186. {
  187. if ($user = $this->getUser($username)) {
  188. return $this->checkPassword($user, $password);
  189. }
  190. return false;
  191. }
  192. public function getUserDetails($username)
  193. {
  194. return $this->getUser($username);
  195. }
  196. /* UserClaimsInterface */
  197. public function getUserClaims($user_id, $claims)
  198. {
  199. if (!$userDetails = $this->getUserDetails($user_id)) {
  200. return false;
  201. }
  202. $claims = explode(' ', trim($claims));
  203. $userClaims = array();
  204. // for each requested claim, if the user has the claim, set it in the response
  205. $validClaims = explode(' ', self::VALID_CLAIMS);
  206. foreach ($validClaims as $validClaim) {
  207. if (in_array($validClaim, $claims)) {
  208. if ($validClaim == 'address') {
  209. // address is an object with subfields
  210. $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails);
  211. } else {
  212. $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails));
  213. }
  214. }
  215. }
  216. return $userClaims;
  217. }
  218. protected function getUserClaim($claim, $userDetails)
  219. {
  220. $userClaims = array();
  221. $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim)));
  222. $claimValues = explode(' ', $claimValuesString);
  223. foreach ($claimValues as $value) {
  224. $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null;
  225. }
  226. return $userClaims;
  227. }
  228. /* OAuth2\Storage\RefreshTokenInterface */
  229. public function getRefreshToken($refresh_token)
  230. {
  231. $stmt = $this->db->prepare(sprintf('SELECT * FROM %s WHERE refresh_token = :refresh_token', $this->config['refresh_token_table']));
  232. $token = $stmt->execute(compact('refresh_token'));
  233. if ($token = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  234. // convert expires to epoch time
  235. $token['expires'] = strtotime($token['expires']);
  236. }
  237. return $token;
  238. }
  239. public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
  240. {
  241. // convert expires to datestring
  242. $expires = date('Y-m-d H:i:s', $expires);
  243. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (refresh_token, client_id, user_id, expires, scope) VALUES (:refresh_token, :client_id, :user_id, :expires, :scope)', $this->config['refresh_token_table']));
  244. return $stmt->execute(compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'));
  245. }
  246. public function unsetRefreshToken($refresh_token)
  247. {
  248. $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE refresh_token = :refresh_token', $this->config['refresh_token_table']));
  249. $stmt->execute(compact('refresh_token'));
  250. return $stmt->rowCount() > 0;
  251. }
  252. // plaintext passwords are bad! Override this for your application
  253. protected function checkPassword($user, $password)
  254. {
  255. return $user['password'] == $this->hashPassword($password);
  256. }
  257. // use a secure hashing algorithm when storing passwords. Override this for your application
  258. protected function hashPassword($password)
  259. {
  260. return sha1($password);
  261. }
  262. public function getUser($username)
  263. {
  264. $stmt = $this->db->prepare($sql = sprintf('SELECT * from %s where username=:username', $this->config['user_table']));
  265. $stmt->execute(array('username' => $username));
  266. if (!$userInfo = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  267. return false;
  268. }
  269. // the default behavior is to use "username" as the user_id
  270. return array_merge(array(
  271. 'user_id' => $username
  272. ), $userInfo);
  273. }
  274. public function setUser($username, $password, $firstName = null, $lastName = null)
  275. {
  276. // do not store in plaintext
  277. $password = $this->hashPassword($password);
  278. // if it exists, update it.
  279. if ($this->getUser($username)) {
  280. $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET password=:password, first_name=:firstName, last_name=:lastName where username=:username', $this->config['user_table']));
  281. } else {
  282. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (username, password, first_name, last_name) VALUES (:username, :password, :firstName, :lastName)', $this->config['user_table']));
  283. }
  284. return $stmt->execute(compact('username', 'password', 'firstName', 'lastName'));
  285. }
  286. /* ScopeInterface */
  287. public function scopeExists($scope)
  288. {
  289. $scope = explode(' ', $scope);
  290. $whereIn = implode(',', array_fill(0, count($scope), '?'));
  291. $stmt = $this->db->prepare(sprintf('SELECT count(scope) as count FROM %s WHERE scope IN (%s)', $this->config['scope_table'], $whereIn));
  292. $stmt->execute($scope);
  293. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  294. return $result['count'] == count($scope);
  295. }
  296. return false;
  297. }
  298. public function getDefaultScope($client_id = null)
  299. {
  300. $stmt = $this->db->prepare(sprintf('SELECT scope FROM %s WHERE is_default=:is_default', $this->config['scope_table']));
  301. $stmt->execute(array('is_default' => true));
  302. if ($result = $stmt->fetchAll(\PDO::FETCH_ASSOC)) {
  303. $defaultScope = array_map(function ($row) {
  304. return $row['scope'];
  305. }, $result);
  306. return implode(' ', $defaultScope);
  307. }
  308. return null;
  309. }
  310. /* JWTBearerInterface */
  311. public function getClientKey($client_id, $subject)
  312. {
  313. $stmt = $this->db->prepare($sql = sprintf('SELECT public_key from %s where client_id=:client_id AND subject=:subject', $this->config['jwt_table']));
  314. $stmt->execute(array('client_id' => $client_id, 'subject' => $subject));
  315. return $stmt->fetchColumn();
  316. }
  317. public function getClientScope($client_id)
  318. {
  319. if (!$clientDetails = $this->getClientDetails($client_id)) {
  320. return false;
  321. }
  322. if (isset($clientDetails['scope'])) {
  323. return $clientDetails['scope'];
  324. }
  325. return null;
  326. }
  327. public function getJti($client_id, $subject, $audience, $expires, $jti)
  328. {
  329. $stmt = $this->db->prepare($sql = sprintf('SELECT * FROM %s WHERE issuer=:client_id AND subject=:subject AND audience=:audience AND expires=:expires AND jti=:jti', $this->config['jti_table']));
  330. $stmt->execute(compact('client_id', 'subject', 'audience', 'expires', 'jti'));
  331. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  332. return array(
  333. 'issuer' => $result['issuer'],
  334. 'subject' => $result['subject'],
  335. 'audience' => $result['audience'],
  336. 'expires' => $result['expires'],
  337. 'jti' => $result['jti'],
  338. );
  339. }
  340. return null;
  341. }
  342. public function setJti($client_id, $subject, $audience, $expires, $jti)
  343. {
  344. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (issuer, subject, audience, expires, jti) VALUES (:client_id, :subject, :audience, :expires, :jti)', $this->config['jti_table']));
  345. return $stmt->execute(compact('client_id', 'subject', 'audience', 'expires', 'jti'));
  346. }
  347. /* PublicKeyInterface */
  348. public function getPublicKey($client_id = null)
  349. {
  350. $stmt = $this->db->prepare($sql = sprintf('SELECT public_key FROM %s WHERE client_id=:client_id OR client_id IS NULL ORDER BY client_id IS NOT NULL DESC', $this->config['public_key_table']));
  351. $stmt->execute(compact('client_id'));
  352. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  353. return $result['public_key'];
  354. }
  355. }
  356. public function getPrivateKey($client_id = null)
  357. {
  358. $stmt = $this->db->prepare($sql = sprintf('SELECT private_key FROM %s WHERE client_id=:client_id OR client_id IS NULL ORDER BY client_id IS NOT NULL DESC', $this->config['public_key_table']));
  359. $stmt->execute(compact('client_id'));
  360. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  361. return $result['private_key'];
  362. }
  363. }
  364. public function getEncryptionAlgorithm($client_id = null)
  365. {
  366. $stmt = $this->db->prepare($sql = sprintf('SELECT encryption_algorithm FROM %s WHERE client_id=:client_id OR client_id IS NULL ORDER BY client_id IS NOT NULL DESC', $this->config['public_key_table']));
  367. $stmt->execute(compact('client_id'));
  368. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  369. return $result['encryption_algorithm'];
  370. }
  371. return 'RS256';
  372. }
  373. /**
  374. * DDL to create OAuth2 database and tables for PDO storage
  375. *
  376. * @see https://github.com/dsquier/oauth2-server-php-mysql
  377. */
  378. public function getBuildSql($dbName = 'oauth2_server_php')
  379. {
  380. $sql = "
  381. CREATE TABLE {$this->config['client_table']} (
  382. client_id VARCHAR(80) NOT NULL,
  383. client_secret VARCHAR(80),
  384. redirect_uri VARCHAR(2000),
  385. grant_types VARCHAR(80),
  386. scope VARCHAR(4000),
  387. user_id VARCHAR(80),
  388. PRIMARY KEY (client_id)
  389. );
  390. CREATE TABLE {$this->config['access_token_table']} (
  391. access_token VARCHAR(40) NOT NULL,
  392. client_id VARCHAR(80) NOT NULL,
  393. user_id VARCHAR(80),
  394. expires TIMESTAMP NOT NULL,
  395. scope VARCHAR(4000),
  396. PRIMARY KEY (access_token)
  397. );
  398. CREATE TABLE {$this->config['code_table']} (
  399. authorization_code VARCHAR(40) NOT NULL,
  400. client_id VARCHAR(80) NOT NULL,
  401. user_id VARCHAR(80),
  402. redirect_uri VARCHAR(2000),
  403. expires TIMESTAMP NOT NULL,
  404. scope VARCHAR(4000),
  405. id_token VARCHAR(1000),
  406. PRIMARY KEY (authorization_code)
  407. );
  408. CREATE TABLE {$this->config['refresh_token_table']} (
  409. refresh_token VARCHAR(40) NOT NULL,
  410. client_id VARCHAR(80) NOT NULL,
  411. user_id VARCHAR(80),
  412. expires TIMESTAMP NOT NULL,
  413. scope VARCHAR(4000),
  414. PRIMARY KEY (refresh_token)
  415. );
  416. CREATE TABLE {$this->config['user_table']} (
  417. username VARCHAR(80),
  418. password VARCHAR(80),
  419. first_name VARCHAR(80),
  420. last_name VARCHAR(80),
  421. email VARCHAR(80),
  422. email_verified BOOLEAN,
  423. scope VARCHAR(4000)
  424. );
  425. CREATE TABLE {$this->config['scope_table']} (
  426. scope VARCHAR(80) NOT NULL,
  427. is_default BOOLEAN,
  428. PRIMARY KEY (scope)
  429. );
  430. CREATE TABLE {$this->config['jwt_table']} (
  431. client_id VARCHAR(80) NOT NULL,
  432. subject VARCHAR(80),
  433. public_key VARCHAR(2000) NOT NULL
  434. );
  435. CREATE TABLE {$this->config['jti_table']} (
  436. issuer VARCHAR(80) NOT NULL,
  437. subject VARCHAR(80),
  438. audience VARCHAR(80),
  439. expires TIMESTAMP NOT NULL,
  440. jti VARCHAR(2000) NOT NULL
  441. );
  442. CREATE TABLE {$this->config['public_key_table']} (
  443. client_id VARCHAR(80),
  444. public_key VARCHAR(2000),
  445. private_key VARCHAR(2000),
  446. encryption_algorithm VARCHAR(100) DEFAULT 'RS256'
  447. )
  448. ";
  449. return $sql;
  450. }
  451. }