1
0

VerifyUserData.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Settings\BackgroundJobs;
  8. use OCP\Accounts\IAccountManager;
  9. use OCP\Accounts\PropertyDoesNotExistException;
  10. use OCP\AppFramework\Http;
  11. use OCP\AppFramework\Utility\ITimeFactory;
  12. use OCP\BackgroundJob\IJobList;
  13. use OCP\BackgroundJob\Job;
  14. use OCP\Http\Client\IClientService;
  15. use OCP\IConfig;
  16. use OCP\IUserManager;
  17. use Psr\Log\LoggerInterface;
  18. class VerifyUserData extends Job {
  19. /** @var bool */
  20. private bool $retainJob = true;
  21. /** @var int max number of attempts to send the request */
  22. private int $maxTry = 24;
  23. /** @var int how much time should be between two tries (1 hour) */
  24. private int $interval = 3600;
  25. private string $lookupServerUrl;
  26. public function __construct(
  27. private IAccountManager $accountManager,
  28. private IUserManager $userManager,
  29. private IClientService $httpClientService,
  30. private LoggerInterface $logger,
  31. ITimeFactory $timeFactory,
  32. private IConfig $config,
  33. ) {
  34. parent::__construct($timeFactory);
  35. $lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
  36. $this->lookupServerUrl = rtrim($lookupServerUrl, '/');
  37. }
  38. public function start(IJobList $jobList): void {
  39. if ($this->shouldRun($this->argument)) {
  40. parent::start($jobList);
  41. $jobList->remove($this, $this->argument);
  42. if ($this->retainJob) {
  43. $this->reAddJob($jobList, $this->argument);
  44. } else {
  45. $this->resetVerificationState();
  46. }
  47. }
  48. }
  49. protected function run($argument) {
  50. $try = (int)$argument['try'] + 1;
  51. switch ($argument['type']) {
  52. case IAccountManager::PROPERTY_WEBSITE:
  53. $result = $this->verifyWebsite($argument);
  54. break;
  55. case IAccountManager::PROPERTY_TWITTER:
  56. case IAccountManager::PROPERTY_EMAIL:
  57. $result = $this->verifyViaLookupServer($argument, $argument['type']);
  58. break;
  59. default:
  60. // no valid type given, no need to retry
  61. $this->logger->error($argument['type'] . ' is no valid type for user account data.');
  62. $result = true;
  63. }
  64. if ($result === true || $try > $this->maxTry) {
  65. $this->retainJob = false;
  66. }
  67. }
  68. /**
  69. * verify web page
  70. *
  71. * @param array $argument
  72. * @return bool true if we could check the verification code, otherwise false
  73. */
  74. protected function verifyWebsite(array $argument) {
  75. $result = false;
  76. $url = rtrim($argument['data'], '/') . '/.well-known/' . 'CloudIdVerificationCode.txt';
  77. $client = $this->httpClientService->newClient();
  78. try {
  79. $response = $client->get($url);
  80. } catch (\Exception $e) {
  81. return false;
  82. }
  83. if ($response->getStatusCode() === Http::STATUS_OK) {
  84. $result = true;
  85. $publishedCode = $response->getBody();
  86. // remove new lines and spaces
  87. $publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
  88. $user = $this->userManager->get($argument['uid']);
  89. // we don't check a valid user -> give up
  90. if ($user === null) {
  91. $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
  92. return $result;
  93. }
  94. $userAccount = $this->accountManager->getAccount($user);
  95. $websiteProp = $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE);
  96. $websiteProp->setVerified($publishedCodeSanitized === $argument['verificationCode']
  97. ? IAccountManager::VERIFIED
  98. : IAccountManager::NOT_VERIFIED
  99. );
  100. $this->accountManager->updateAccount($userAccount);
  101. }
  102. return $result;
  103. }
  104. protected function verifyViaLookupServer(array $argument, string $dataType): bool {
  105. if (empty($this->lookupServerUrl) ||
  106. $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes') !== 'yes' ||
  107. $this->config->getSystemValue('has_internet_connection', true) === false) {
  108. return true;
  109. }
  110. $user = $this->userManager->get($argument['uid']);
  111. // we don't check a valid user -> give up
  112. if ($user === null) {
  113. $this->logger->info($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
  114. return true;
  115. }
  116. $cloudId = $user->getCloudId();
  117. $lookupServerData = $this->queryLookupServer($cloudId);
  118. // for some reasons we couldn't read any data from the lookup server, try again later
  119. if (empty($lookupServerData) || empty($lookupServerData[$dataType])) {
  120. return false;
  121. }
  122. // lookup server has verification data for wrong user data (e.g. email address), try again later
  123. if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
  124. return false;
  125. }
  126. // lookup server hasn't verified the email address so far, try again later
  127. if ($lookupServerData[$dataType]['verified'] === IAccountManager::NOT_VERIFIED) {
  128. return false;
  129. }
  130. try {
  131. $userAccount = $this->accountManager->getAccount($user);
  132. $property = $userAccount->getProperty($dataType);
  133. $property->setVerified(IAccountManager::VERIFIED);
  134. $this->accountManager->updateAccount($userAccount);
  135. } catch (PropertyDoesNotExistException $e) {
  136. return false;
  137. }
  138. return true;
  139. }
  140. /**
  141. * @param string $cloudId
  142. * @return array
  143. */
  144. protected function queryLookupServer($cloudId) {
  145. try {
  146. $client = $this->httpClientService->newClient();
  147. $response = $client->get(
  148. $this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
  149. [
  150. 'timeout' => 10,
  151. 'connect_timeout' => 3,
  152. ]
  153. );
  154. $body = json_decode($response->getBody(), true);
  155. if (is_array($body) && isset($body['federationId']) && $body['federationId'] === $cloudId) {
  156. return $body;
  157. }
  158. } catch (\Exception $e) {
  159. // do nothing, we will just re-try later
  160. }
  161. return [];
  162. }
  163. /**
  164. * re-add background job with new arguments
  165. *
  166. * @param IJobList $jobList
  167. * @param array $argument
  168. */
  169. protected function reAddJob(IJobList $jobList, array $argument) {
  170. $jobList->add(VerifyUserData::class,
  171. [
  172. 'verificationCode' => $argument['verificationCode'],
  173. 'data' => $argument['data'],
  174. 'type' => $argument['type'],
  175. 'uid' => $argument['uid'],
  176. 'try' => (int)$argument['try'] + 1,
  177. 'lastRun' => time()
  178. ]
  179. );
  180. }
  181. /**
  182. * test if it is time for the next run
  183. *
  184. * @param array $argument
  185. * @return bool
  186. */
  187. protected function shouldRun(array $argument) {
  188. $lastRun = (int)$argument['lastRun'];
  189. return ((time() - $lastRun) > $this->interval);
  190. }
  191. /**
  192. * reset verification state after max tries are reached
  193. */
  194. protected function resetVerificationState(): void {
  195. $user = $this->userManager->get($this->argument['uid']);
  196. if ($user !== null) {
  197. $userAccount = $this->accountManager->getAccount($user);
  198. try {
  199. $property = $userAccount->getProperty($this->argument['type']);
  200. $property->setVerified(IAccountManager::NOT_VERIFIED);
  201. $this->accountManager->updateAccount($userAccount);
  202. } catch (PropertyDoesNotExistException $e) {
  203. return;
  204. }
  205. }
  206. }
  207. }