PublicKeyTokenMapper.php 9.4 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\Authentication\Token\IToken;
  30. use OCP\DB\QueryBuilder\IQueryBuilder;
  31. use OCP\IDBConnection;
  32. /**
  33. * @template-extends QBMapper<PublicKeyToken>
  34. */
  35. class PublicKeyTokenMapper extends QBMapper {
  36. public function __construct(IDBConnection $db) {
  37. parent::__construct($db, 'authtoken');
  38. }
  39. /**
  40. * Invalidate (delete) a given token
  41. */
  42. public function invalidate(string $token) {
  43. /* @var $qb IQueryBuilder */
  44. $qb = $this->db->getQueryBuilder();
  45. $qb->delete($this->tableName)
  46. ->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  47. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  48. ->execute();
  49. }
  50. /**
  51. * @param int $olderThan
  52. * @param int $remember
  53. */
  54. public function invalidateOld(int $olderThan, int $remember = IToken::DO_NOT_REMEMBER) {
  55. /* @var $qb IQueryBuilder */
  56. $qb = $this->db->getQueryBuilder();
  57. $qb->delete($this->tableName)
  58. ->where($qb->expr()->lt('last_activity', $qb->createNamedParameter($olderThan, IQueryBuilder::PARAM_INT)))
  59. ->andWhere($qb->expr()->eq('type', $qb->createNamedParameter(IToken::TEMPORARY_TOKEN, IQueryBuilder::PARAM_INT)))
  60. ->andWhere($qb->expr()->eq('remember', $qb->createNamedParameter($remember, IQueryBuilder::PARAM_INT)))
  61. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  62. ->execute();
  63. }
  64. public function invalidateLastUsedBefore(string $uid, int $before): int {
  65. $qb = $this->db->getQueryBuilder();
  66. $qb->delete($this->tableName)
  67. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  68. ->andWhere($qb->expr()->lt('last_activity', $qb->createNamedParameter($before, IQueryBuilder::PARAM_INT)))
  69. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
  70. return $qb->executeStatement();
  71. }
  72. /**
  73. * Get the user UID for the given token
  74. *
  75. * @throws DoesNotExistException
  76. */
  77. public function getToken(string $token): PublicKeyToken {
  78. /* @var $qb IQueryBuilder */
  79. $qb = $this->db->getQueryBuilder();
  80. $result = $qb->select('*')
  81. ->from($this->tableName)
  82. ->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  83. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  84. ->execute();
  85. $data = $result->fetch();
  86. $result->closeCursor();
  87. if ($data === false) {
  88. throw new DoesNotExistException('token does not exist');
  89. }
  90. return PublicKeyToken::fromRow($data);
  91. }
  92. /**
  93. * Get the token for $id
  94. *
  95. * @throws DoesNotExistException
  96. */
  97. public function getTokenById(int $id): PublicKeyToken {
  98. /* @var $qb IQueryBuilder */
  99. $qb = $this->db->getQueryBuilder();
  100. $result = $qb->select('*')
  101. ->from($this->tableName)
  102. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  103. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  104. ->execute();
  105. $data = $result->fetch();
  106. $result->closeCursor();
  107. if ($data === false) {
  108. throw new DoesNotExistException('token does not exist');
  109. }
  110. return PublicKeyToken::fromRow($data);
  111. }
  112. /**
  113. * Get all tokens of a user
  114. *
  115. * The provider may limit the number of result rows in case of an abuse
  116. * where a high number of (session) tokens is generated
  117. *
  118. * @param string $uid
  119. * @return PublicKeyToken[]
  120. */
  121. public function getTokenByUser(string $uid): array {
  122. /* @var $qb IQueryBuilder */
  123. $qb = $this->db->getQueryBuilder();
  124. $qb->select('*')
  125. ->from($this->tableName)
  126. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  127. ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)))
  128. ->setMaxResults(1000);
  129. $result = $qb->execute();
  130. $data = $result->fetchAll();
  131. $result->closeCursor();
  132. $entities = array_map(function ($row) {
  133. return PublicKeyToken::fromRow($row);
  134. }, $data);
  135. return $entities;
  136. }
  137. public function getTokenByUserAndId(string $uid, int $id): ?string {
  138. /* @var $qb IQueryBuilder */
  139. $qb = $this->db->getQueryBuilder();
  140. $qb->select('token')
  141. ->from($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. return $qb->executeQuery()->fetchOne() ?: null;
  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. }