Pdo.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. return $stmt->execute(compact('access_token'));
  138. }
  139. /* OAuth2\Storage\AuthorizationCodeInterface */
  140. public function getAuthorizationCode($code)
  141. {
  142. $stmt = $this->db->prepare(sprintf('SELECT * from %s where authorization_code = :code', $this->config['code_table']));
  143. $stmt->execute(compact('code'));
  144. if ($code = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  145. // convert date string back to timestamp
  146. $code['expires'] = strtotime($code['expires']);
  147. }
  148. return $code;
  149. }
  150. public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
  151. {
  152. if (func_num_args() > 6) {
  153. // we are calling with an id token
  154. return call_user_func_array(array($this, 'setAuthorizationCodeWithIdToken'), func_get_args());
  155. }
  156. // convert expires to datestring
  157. $expires = date('Y-m-d H:i:s', $expires);
  158. // if it exists, update it.
  159. if ($this->getAuthorizationCode($code)) {
  160. $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']));
  161. } else {
  162. $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']));
  163. }
  164. return $stmt->execute(compact('code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope'));
  165. }
  166. private function setAuthorizationCodeWithIdToken($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
  167. {
  168. // convert expires to datestring
  169. $expires = date('Y-m-d H:i:s', $expires);
  170. // if it exists, update it.
  171. if ($this->getAuthorizationCode($code)) {
  172. $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']));
  173. } else {
  174. $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']));
  175. }
  176. return $stmt->execute(compact('code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'));
  177. }
  178. public function expireAuthorizationCode($code)
  179. {
  180. $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE authorization_code = :code', $this->config['code_table']));
  181. return $stmt->execute(compact('code'));
  182. }
  183. /* OAuth2\Storage\UserCredentialsInterface */
  184. public function checkUserCredentials($username, $password)
  185. {
  186. if ($user = $this->getUser($username)) {
  187. return $this->checkPassword($user, $password);
  188. }
  189. return false;
  190. }
  191. public function getUserDetails($username)
  192. {
  193. return $this->getUser($username);
  194. }
  195. /* UserClaimsInterface */
  196. public function getUserClaims($user_id, $claims)
  197. {
  198. if (!$userDetails = $this->getUserDetails($user_id)) {
  199. return false;
  200. }
  201. $claims = explode(' ', trim($claims));
  202. $userClaims = array();
  203. // for each requested claim, if the user has the claim, set it in the response
  204. $validClaims = explode(' ', self::VALID_CLAIMS);
  205. foreach ($validClaims as $validClaim) {
  206. if (in_array($validClaim, $claims)) {
  207. if ($validClaim == 'address') {
  208. // address is an object with subfields
  209. $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails);
  210. } else {
  211. $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails));
  212. }
  213. }
  214. }
  215. return $userClaims;
  216. }
  217. protected function getUserClaim($claim, $userDetails)
  218. {
  219. $userClaims = array();
  220. $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim)));
  221. $claimValues = explode(' ', $claimValuesString);
  222. foreach ($claimValues as $value) {
  223. $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null;
  224. }
  225. return $userClaims;
  226. }
  227. /* OAuth2\Storage\RefreshTokenInterface */
  228. public function getRefreshToken($refresh_token)
  229. {
  230. $stmt = $this->db->prepare(sprintf('SELECT * FROM %s WHERE refresh_token = :refresh_token', $this->config['refresh_token_table']));
  231. $token = $stmt->execute(compact('refresh_token'));
  232. if ($token = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  233. // convert expires to epoch time
  234. $token['expires'] = strtotime($token['expires']);
  235. }
  236. return $token;
  237. }
  238. public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
  239. {
  240. // convert expires to datestring
  241. $expires = date('Y-m-d H:i:s', $expires);
  242. $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']));
  243. return $stmt->execute(compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'));
  244. }
  245. public function unsetRefreshToken($refresh_token)
  246. {
  247. $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE refresh_token = :refresh_token', $this->config['refresh_token_table']));
  248. return $stmt->execute(compact('refresh_token'));
  249. }
  250. // plaintext passwords are bad! Override this for your application
  251. protected function checkPassword($user, $password)
  252. {
  253. return $user['password'] == sha1($password);
  254. }
  255. public function getUser($username)
  256. {
  257. $stmt = $this->db->prepare($sql = sprintf('SELECT * from %s where username=:username', $this->config['user_table']));
  258. $stmt->execute(array('username' => $username));
  259. if (!$userInfo = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  260. return false;
  261. }
  262. // the default behavior is to use "username" as the user_id
  263. return array_merge(array(
  264. 'user_id' => $username
  265. ), $userInfo);
  266. }
  267. public function setUser($username, $password, $firstName = null, $lastName = null)
  268. {
  269. // do not store in plaintext
  270. $password = sha1($password);
  271. // if it exists, update it.
  272. if ($this->getUser($username)) {
  273. $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET password=:password, first_name=:firstName, last_name=:lastName where username=:username', $this->config['user_table']));
  274. } else {
  275. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (username, password, first_name, last_name) VALUES (:username, :password, :firstName, :lastName)', $this->config['user_table']));
  276. }
  277. return $stmt->execute(compact('username', 'password', 'firstName', 'lastName'));
  278. }
  279. /* ScopeInterface */
  280. public function scopeExists($scope)
  281. {
  282. $scope = explode(' ', $scope);
  283. $whereIn = implode(',', array_fill(0, count($scope), '?'));
  284. $stmt = $this->db->prepare(sprintf('SELECT count(scope) as count FROM %s WHERE scope IN (%s)', $this->config['scope_table'], $whereIn));
  285. $stmt->execute($scope);
  286. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  287. return $result['count'] == count($scope);
  288. }
  289. return false;
  290. }
  291. public function getDefaultScope($client_id = null)
  292. {
  293. $stmt = $this->db->prepare(sprintf('SELECT scope FROM %s WHERE is_default=:is_default', $this->config['scope_table']));
  294. $stmt->execute(array('is_default' => true));
  295. if ($result = $stmt->fetchAll(\PDO::FETCH_ASSOC)) {
  296. $defaultScope = array_map(function ($row) {
  297. return $row['scope'];
  298. }, $result);
  299. return implode(' ', $defaultScope);
  300. }
  301. return null;
  302. }
  303. /* JWTBearerInterface */
  304. public function getClientKey($client_id, $subject)
  305. {
  306. $stmt = $this->db->prepare($sql = sprintf('SELECT public_key from %s where client_id=:client_id AND subject=:subject', $this->config['jwt_table']));
  307. $stmt->execute(array('client_id' => $client_id, 'subject' => $subject));
  308. return $stmt->fetchColumn();
  309. }
  310. public function getClientScope($client_id)
  311. {
  312. if (!$clientDetails = $this->getClientDetails($client_id)) {
  313. return false;
  314. }
  315. if (isset($clientDetails['scope'])) {
  316. return $clientDetails['scope'];
  317. }
  318. return null;
  319. }
  320. public function getJti($client_id, $subject, $audience, $expires, $jti)
  321. {
  322. $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']));
  323. $stmt->execute(compact('client_id', 'subject', 'audience', 'expires', 'jti'));
  324. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  325. return array(
  326. 'issuer' => $result['issuer'],
  327. 'subject' => $result['subject'],
  328. 'audience' => $result['audience'],
  329. 'expires' => $result['expires'],
  330. 'jti' => $result['jti'],
  331. );
  332. }
  333. return null;
  334. }
  335. public function setJti($client_id, $subject, $audience, $expires, $jti)
  336. {
  337. $stmt = $this->db->prepare(sprintf('INSERT INTO %s (issuer, subject, audience, expires, jti) VALUES (:client_id, :subject, :audience, :expires, :jti)', $this->config['jti_table']));
  338. return $stmt->execute(compact('client_id', 'subject', 'audience', 'expires', 'jti'));
  339. }
  340. /* PublicKeyInterface */
  341. public function getPublicKey($client_id = null)
  342. {
  343. $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']));
  344. $stmt->execute(compact('client_id'));
  345. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  346. return $result['public_key'];
  347. }
  348. }
  349. public function getPrivateKey($client_id = null)
  350. {
  351. $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']));
  352. $stmt->execute(compact('client_id'));
  353. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  354. return $result['private_key'];
  355. }
  356. }
  357. public function getEncryptionAlgorithm($client_id = null)
  358. {
  359. $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']));
  360. $stmt->execute(compact('client_id'));
  361. if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  362. return $result['encryption_algorithm'];
  363. }
  364. return 'RS256';
  365. }
  366. /**
  367. * DDL to create OAuth2 database and tables for PDO storage
  368. *
  369. * @see https://github.com/dsquier/oauth2-server-php-mysql
  370. */
  371. public function getBuildSql($dbName = 'oauth2_server_php')
  372. {
  373. $sql = "
  374. CREATE TABLE {$this->config['client_table']} (
  375. client_id VARCHAR(80) NOT NULL,
  376. client_secret VARCHAR(80) NOT NULL,
  377. redirect_uri VARCHAR(2000),
  378. grant_types VARCHAR(80),
  379. scope VARCHAR(4000),
  380. user_id VARCHAR(80),
  381. PRIMARY KEY (client_id)
  382. );
  383. CREATE TABLE {$this->config['access_token_table']} (
  384. access_token VARCHAR(40) NOT NULL,
  385. client_id VARCHAR(80) NOT NULL,
  386. user_id VARCHAR(80),
  387. expires TIMESTAMP NOT NULL,
  388. scope VARCHAR(4000),
  389. PRIMARY KEY (access_token)
  390. );
  391. CREATE TABLE {$this->config['code_table']} (
  392. authorization_code VARCHAR(40) NOT NULL,
  393. client_id VARCHAR(80) NOT NULL,
  394. user_id VARCHAR(80),
  395. redirect_uri VARCHAR(2000),
  396. expires TIMESTAMP NOT NULL,
  397. scope VARCHAR(4000),
  398. id_token VARCHAR(1000),
  399. PRIMARY KEY (authorization_code)
  400. );
  401. CREATE TABLE {$this->config['refresh_token_table']} (
  402. refresh_token VARCHAR(40) NOT NULL,
  403. client_id VARCHAR(80) NOT NULL,
  404. user_id VARCHAR(80),
  405. expires TIMESTAMP NOT NULL,
  406. scope VARCHAR(4000),
  407. PRIMARY KEY (refresh_token)
  408. );
  409. CREATE TABLE {$this->config['user_table']} (
  410. username VARCHAR(80),
  411. password VARCHAR(80),
  412. first_name VARCHAR(80),
  413. last_name VARCHAR(80),
  414. email VARCHAR(80),
  415. email_verified BOOLEAN,
  416. scope VARCHAR(4000)
  417. );
  418. CREATE TABLE {$this->config['scope_table']} (
  419. scope VARCHAR(80) NOT NULL,
  420. is_default BOOLEAN,
  421. PRIMARY KEY (scope)
  422. );
  423. CREATE TABLE {$this->config['jwt_table']} (
  424. client_id VARCHAR(80) NOT NULL,
  425. subject VARCHAR(80),
  426. public_key VARCHAR(2000) NOT NULL
  427. );
  428. CREATE TABLE {$this->config['jti_table']} (
  429. issuer VARCHAR(80) NOT NULL,
  430. subject VARCHAR(80),
  431. audiance VARCHAR(80),
  432. expires TIMESTAMP NOT NULL,
  433. jti VARCHAR(2000) NOT NULL
  434. );
  435. CREATE TABLE {$this->config['public_key_table']} (
  436. client_id VARCHAR(80),
  437. public_key VARCHAR(2000),
  438. private_key VARCHAR(2000),
  439. encryption_algorithm VARCHAR(100) DEFAULT 'RS256'
  440. )
  441. ";
  442. return $sql;
  443. }
  444. }