PublicKeyTokenMapper.php 8.7 KB

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