PublicKeyTokenMapper.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Authentication\Token;
  8. use OCP\AppFramework\Db\DoesNotExistException;
  9. use OCP\AppFramework\Db\QBMapper;
  10. use OCP\Authentication\Token\IToken;
  11. use OCP\DB\QueryBuilder\IQueryBuilder;
  12. use OCP\IDBConnection;
  13. /**
  14. * @template-extends QBMapper<PublicKeyToken>
  15. */
  16. class PublicKeyTokenMapper extends QBMapper {
  17. public function __construct(IDBConnection $db) {
  18. parent::__construct($db, 'authtoken');
  19. }
  20. /**
  21. * Invalidate (delete) a given token
  22. */
  23. public function invalidate(string $token) {
  24. /* @var $qb IQueryBuilder */
  25. $qb = $this->db->getQueryBuilder();
  26. $qb->delete($this->tableName)
  27. ->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  28. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  29. ->execute();
  30. }
  31. /**
  32. * @param int $olderThan
  33. * @param int $remember
  34. */
  35. public function invalidateOld(int $olderThan, int $remember = IToken::DO_NOT_REMEMBER) {
  36. /* @var $qb IQueryBuilder */
  37. $qb = $this->db->getQueryBuilder();
  38. $qb->delete($this->tableName)
  39. ->where($qb->expr()->lt('last_activity', $qb->createNamedParameter($olderThan, IQueryBuilder::PARAM_INT)))
  40. ->andWhere($qb->expr()->eq('type', $qb->createNamedParameter(IToken::TEMPORARY_TOKEN, IQueryBuilder::PARAM_INT)))
  41. ->andWhere($qb->expr()->eq('remember', $qb->createNamedParameter($remember, IQueryBuilder::PARAM_INT)))
  42. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  43. ->execute();
  44. }
  45. public function invalidateLastUsedBefore(string $uid, int $before): int {
  46. $qb = $this->db->getQueryBuilder();
  47. $qb->delete($this->tableName)
  48. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  49. ->andWhere($qb->expr()->lt('last_activity', $qb->createNamedParameter($before, IQueryBuilder::PARAM_INT)))
  50. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  51. return $qb->executeStatement();
  52. }
  53. /**
  54. * Get the user UID for the given token
  55. *
  56. * @throws DoesNotExistException
  57. */
  58. public function getToken(string $token): PublicKeyToken {
  59. /* @var $qb IQueryBuilder */
  60. $qb = $this->db->getQueryBuilder();
  61. $result = $qb->select('*')
  62. ->from($this->tableName)
  63. ->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  64. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  65. ->execute();
  66. $data = $result->fetch();
  67. $result->closeCursor();
  68. if ($data === false) {
  69. throw new DoesNotExistException('token does not exist');
  70. }
  71. return PublicKeyToken::fromRow($data);
  72. }
  73. /**
  74. * Get the token for $id
  75. *
  76. * @throws DoesNotExistException
  77. */
  78. public function getTokenById(int $id): PublicKeyToken {
  79. /* @var $qb IQueryBuilder */
  80. $qb = $this->db->getQueryBuilder();
  81. $result = $qb->select('*')
  82. ->from($this->tableName)
  83. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  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 all tokens of a user
  95. *
  96. * The provider may limit the number of result rows in case of an abuse
  97. * where a high number of (session) tokens is generated
  98. *
  99. * @param string $uid
  100. * @return PublicKeyToken[]
  101. */
  102. public function getTokenByUser(string $uid): array {
  103. /* @var $qb IQueryBuilder */
  104. $qb = $this->db->getQueryBuilder();
  105. $qb->select('*')
  106. ->from($this->tableName)
  107. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  108. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  109. ->setMaxResults(1000);
  110. $result = $qb->execute();
  111. $data = $result->fetchAll();
  112. $result->closeCursor();
  113. $entities = array_map(function ($row) {
  114. return PublicKeyToken::fromRow($row);
  115. }, $data);
  116. return $entities;
  117. }
  118. public function getTokenByUserAndId(string $uid, int $id): ?string {
  119. /* @var $qb IQueryBuilder */
  120. $qb = $this->db->getQueryBuilder();
  121. $qb->select('token')
  122. ->from($this->tableName)
  123. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  124. ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  125. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  126. return $qb->executeQuery()->fetchOne() ?: null;
  127. }
  128. /**
  129. * delete all auth token which belong to a specific client if the client was deleted
  130. *
  131. * @param string $name
  132. */
  133. public function deleteByName(string $name) {
  134. $qb = $this->db->getQueryBuilder();
  135. $qb->delete($this->tableName)
  136. ->where($qb->expr()->eq('name', $qb->createNamedParameter($name), IQueryBuilder::PARAM_STR))
  137. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  138. $qb->execute();
  139. }
  140. public function deleteTempToken(PublicKeyToken $except) {
  141. $qb = $this->db->getQueryBuilder();
  142. $qb->delete($this->tableName)
  143. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($except->getUID())))
  144. ->andWhere($qb->expr()->eq('type', $qb->createNamedParameter(IToken::TEMPORARY_TOKEN)))
  145. ->andWhere($qb->expr()->neq('id', $qb->createNamedParameter($except->getId())))
  146. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  147. $qb->execute();
  148. }
  149. public function hasExpiredTokens(string $uid): bool {
  150. $qb = $this->db->getQueryBuilder();
  151. $qb->select('*')
  152. ->from($this->tableName)
  153. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  154. ->andWhere($qb->expr()->eq('password_invalid', $qb->createNamedParameter(true), IQueryBuilder::PARAM_BOOL))
  155. ->setMaxResults(1);
  156. $cursor = $qb->execute();
  157. $data = $cursor->fetchAll();
  158. $cursor->closeCursor();
  159. return count($data) === 1;
  160. }
  161. /**
  162. * Update the last activity timestamp
  163. *
  164. * In highly concurrent setups it can happen that two parallel processes
  165. * trigger the update at (nearly) the same time. In that special case it's
  166. * not necessary to hit the database with two actual updates. Therefore the
  167. * target last activity is included in the WHERE clause with a few seconds
  168. * of tolerance.
  169. *
  170. * Example:
  171. * - process 1 (P1) reads the token at timestamp 1500
  172. * - process 1 (P2) reads the token at timestamp 1501
  173. * - activity update interval is 100
  174. *
  175. * This means
  176. *
  177. * - P1 will see a last_activity smaller than the current time and update
  178. * the token row
  179. * - If P2 reads after P1 had written, it will see 1600 as last activity
  180. * and the comparison on last_activity won't be truthy. This means no rows
  181. * need to be updated a second time
  182. * - If P2 reads before P1 had written, it will see 1501 as last activity,
  183. * but the comparison on last_activity will still not be truthy and the
  184. * token row is not updated a second time
  185. *
  186. * @param IToken $token
  187. * @param int $now
  188. */
  189. public function updateActivity(IToken $token, int $now): void {
  190. $qb = $this->db->getQueryBuilder();
  191. $update = $qb->update($this->getTableName())
  192. ->set('last_activity', $qb->createNamedParameter($now, IQueryBuilder::PARAM_INT))
  193. ->where(
  194. $qb->expr()->eq('id', $qb->createNamedParameter($token->getId(), IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
  195. $qb->expr()->lt('last_activity', $qb->createNamedParameter($now - 15, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT)
  196. );
  197. $update->executeStatement();
  198. }
  199. public function updateHashesForUser(string $userId, string $passwordHash): void {
  200. $qb = $this->db->getQueryBuilder();
  201. $update = $qb->update($this->getTableName())
  202. ->set('password_hash', $qb->createNamedParameter($passwordHash))
  203. ->where(
  204. $qb->expr()->eq('uid', $qb->createNamedParameter($userId))
  205. );
  206. $update->executeStatement();
  207. }
  208. public function getFirstTokenForUser(string $userId): ?PublicKeyToken {
  209. $qb = $this->db->getQueryBuilder();
  210. $qb->select('*')
  211. ->from($this->getTableName())
  212. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($userId)))
  213. ->setMaxResults(1)
  214. ->orderBy('id');
  215. $result = $qb->executeQuery();
  216. $data = $result->fetch();
  217. $result->closeCursor();
  218. if ($data === false) {
  219. return null;
  220. }
  221. return PublicKeyToken::fromRow($data);
  222. }
  223. }