PublicKeyTokenMapper.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018 Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OC\Authentication\Token;
  27. use OCP\AppFramework\Db\DoesNotExistException;
  28. use OCP\AppFramework\Db\QBMapper;
  29. use OCP\DB\QueryBuilder\IQueryBuilder;
  30. use OCP\IDBConnection;
  31. /**
  32. * @template-extends QBMapper<PublicKeyToken>
  33. */
  34. class PublicKeyTokenMapper extends QBMapper {
  35. public function __construct(IDBConnection $db) {
  36. parent::__construct($db, 'authtoken');
  37. }
  38. /**
  39. * Invalidate (delete) a given token
  40. *
  41. * @param string $token
  42. */
  43. public function invalidate(string $token) {
  44. /* @var $qb IQueryBuilder */
  45. $qb = $this->db->getQueryBuilder();
  46. $qb->delete($this->tableName)
  47. ->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  48. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  49. ->execute();
  50. }
  51. /**
  52. * @param int $olderThan
  53. * @param int $remember
  54. */
  55. public function invalidateOld(int $olderThan, int $remember = IToken::DO_NOT_REMEMBER) {
  56. /* @var $qb IQueryBuilder */
  57. $qb = $this->db->getQueryBuilder();
  58. $qb->delete($this->tableName)
  59. ->where($qb->expr()->lt('last_activity', $qb->createNamedParameter($olderThan, IQueryBuilder::PARAM_INT)))
  60. ->andWhere($qb->expr()->eq('type', $qb->createNamedParameter(IToken::TEMPORARY_TOKEN, IQueryBuilder::PARAM_INT)))
  61. ->andWhere($qb->expr()->eq('remember', $qb->createNamedParameter($remember, IQueryBuilder::PARAM_INT)))
  62. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  63. ->execute();
  64. }
  65. public function invalidateLastUsedBefore(string $uid, int $before): int {
  66. $qb = $this->db->getQueryBuilder();
  67. $qb->delete($this->tableName)
  68. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  69. ->andWhere($qb->expr()->lt('last_activity', $qb->createNamedParameter($before, IQueryBuilder::PARAM_INT)))
  70. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  71. return $qb->executeStatement();
  72. }
  73. /**
  74. * Get the user UID for the given token
  75. *
  76. * @throws DoesNotExistException
  77. */
  78. public function getToken(string $token): PublicKeyToken {
  79. /* @var $qb IQueryBuilder */
  80. $qb = $this->db->getQueryBuilder();
  81. $result = $qb->select('*')
  82. ->from($this->tableName)
  83. ->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  84. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  85. ->execute();
  86. $data = $result->fetch();
  87. $result->closeCursor();
  88. if ($data === false) {
  89. throw new DoesNotExistException('token does not exist');
  90. }
  91. return PublicKeyToken::fromRow($data);
  92. }
  93. /**
  94. * Get the token for $id
  95. *
  96. * @throws DoesNotExistException
  97. */
  98. public function getTokenById(int $id): PublicKeyToken {
  99. /* @var $qb IQueryBuilder */
  100. $qb = $this->db->getQueryBuilder();
  101. $result = $qb->select('*')
  102. ->from($this->tableName)
  103. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  104. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  105. ->execute();
  106. $data = $result->fetch();
  107. $result->closeCursor();
  108. if ($data === false) {
  109. throw new DoesNotExistException('token does not exist');
  110. }
  111. return PublicKeyToken::fromRow($data);
  112. }
  113. /**
  114. * Get all tokens of a user
  115. *
  116. * The provider may limit the number of result rows in case of an abuse
  117. * where a high number of (session) tokens is generated
  118. *
  119. * @param string $uid
  120. * @return PublicKeyToken[]
  121. */
  122. public function getTokenByUser(string $uid): array {
  123. /* @var $qb IQueryBuilder */
  124. $qb = $this->db->getQueryBuilder();
  125. $qb->select('*')
  126. ->from($this->tableName)
  127. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  128. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  129. ->setMaxResults(1000);
  130. $result = $qb->execute();
  131. $data = $result->fetchAll();
  132. $result->closeCursor();
  133. $entities = array_map(function ($row) {
  134. return PublicKeyToken::fromRow($row);
  135. }, $data);
  136. return $entities;
  137. }
  138. public function deleteById(string $uid, int $id) {
  139. /* @var $qb IQueryBuilder */
  140. $qb = $this->db->getQueryBuilder();
  141. $qb->delete($this->tableName)
  142. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  143. ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  144. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  145. $qb->execute();
  146. }
  147. /**
  148. * delete all auth token which belong to a specific client if the client was deleted
  149. *
  150. * @param string $name
  151. */
  152. public function deleteByName(string $name) {
  153. $qb = $this->db->getQueryBuilder();
  154. $qb->delete($this->tableName)
  155. ->where($qb->expr()->eq('name', $qb->createNamedParameter($name), IQueryBuilder::PARAM_STR))
  156. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  157. $qb->execute();
  158. }
  159. public function deleteTempToken(PublicKeyToken $except) {
  160. $qb = $this->db->getQueryBuilder();
  161. $qb->delete($this->tableName)
  162. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($except->getUID())))
  163. ->andWhere($qb->expr()->eq('type', $qb->createNamedParameter(IToken::TEMPORARY_TOKEN)))
  164. ->andWhere($qb->expr()->neq('id', $qb->createNamedParameter($except->getId())))
  165. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  166. $qb->execute();
  167. }
  168. public function hasExpiredTokens(string $uid): bool {
  169. $qb = $this->db->getQueryBuilder();
  170. $qb->select('*')
  171. ->from($this->tableName)
  172. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  173. ->andWhere($qb->expr()->eq('password_invalid', $qb->createNamedParameter(true), IQueryBuilder::PARAM_BOOL))
  174. ->setMaxResults(1);
  175. $cursor = $qb->execute();
  176. $data = $cursor->fetchAll();
  177. $cursor->closeCursor();
  178. return count($data) === 1;
  179. }
  180. /**
  181. * Update the last activity timestamp
  182. *
  183. * In highly concurrent setups it can happen that two parallel processes
  184. * trigger the update at (nearly) the same time. In that special case it's
  185. * not necessary to hit the database with two actual updates. Therefore the
  186. * target last activity is included in the WHERE clause with a few seconds
  187. * of tolerance.
  188. *
  189. * Example:
  190. * - process 1 (P1) reads the token at timestamp 1500
  191. * - process 1 (P2) reads the token at timestamp 1501
  192. * - activity update interval is 100
  193. *
  194. * This means
  195. *
  196. * - P1 will see a last_activity smaller than the current time and update
  197. * the token row
  198. * - If P2 reads after P1 had written, it will see 1600 as last activity
  199. * and the comparison on last_activity won't be truthy. This means no rows
  200. * need to be updated a second time
  201. * - If P2 reads before P1 had written, it will see 1501 as last activity,
  202. * but the comparison on last_activity will still not be truthy and the
  203. * token row is not updated a second time
  204. *
  205. * @param IToken $token
  206. * @param int $now
  207. */
  208. public function updateActivity(IToken $token, int $now): void {
  209. $qb = $this->db->getQueryBuilder();
  210. $update = $qb->update($this->getTableName())
  211. ->set('last_activity', $qb->createNamedParameter($now, IQueryBuilder::PARAM_INT))
  212. ->where(
  213. $qb->expr()->eq('id', $qb->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
  214. $qb->expr()->lt('last_activity', $qb->createNamedParameter($now - 15, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT)
  215. );
  216. $update->executeStatement();
  217. }
  218. public function updateHashesForUser(string $userId, string $passwordHash): void {
  219. $qb = $this->db->getQueryBuilder();
  220. $update = $qb->update($this->getTableName())
  221. ->set('password_hash', $qb->createNamedParameter($passwordHash))
  222. ->where(
  223. $qb->expr()->eq('uid', $qb->createNamedParameter($userId))
  224. );
  225. $update->executeStatement();
  226. }
  227. public function getFirstTokenForUser(string $userId): ?PublicKeyToken {
  228. $qb = $this->db->getQueryBuilder();
  229. $qb->select('*')
  230. ->from($this->getTableName())
  231. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($userId)))
  232. ->setMaxResults(1)
  233. ->orderBy('id');
  234. $result = $qb->executeQuery();
  235. $data = $result->fetch();
  236. $result->closeCursor();
  237. if ($data === false) {
  238. return null;
  239. }
  240. return PublicKeyToken::fromRow($data);
  241. }
  242. }