VerifyUserData.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Bjoern Schiessle <bjoern@schiessle.org>
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Patrik Kernstock <info@pkern.at>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. *
  14. * @license GNU AGPL version 3 or any later version
  15. *
  16. * This program is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License as
  18. * published by the Free Software Foundation, either version 3 of the
  19. * License, or (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. *
  29. */
  30. namespace OCA\Settings\BackgroundJobs;
  31. use OCP\Accounts\IAccountManager;
  32. use OCP\Accounts\PropertyDoesNotExistException;
  33. use OCP\AppFramework\Http;
  34. use OCP\AppFramework\Utility\ITimeFactory;
  35. use OCP\BackgroundJob\IJobList;
  36. use OCP\BackgroundJob\Job;
  37. use OCP\Http\Client\IClientService;
  38. use OCP\IConfig;
  39. use OCP\ILogger;
  40. use OCP\IUserManager;
  41. class VerifyUserData extends Job {
  42. /** @var bool */
  43. private $retainJob = true;
  44. /** @var int max number of attempts to send the request */
  45. private $maxTry = 24;
  46. /** @var int how much time should be between two tries (1 hour) */
  47. private $interval = 3600;
  48. /** @var IAccountManager */
  49. private $accountManager;
  50. /** @var IUserManager */
  51. private $userManager;
  52. /** @var IClientService */
  53. private $httpClientService;
  54. /** @var ILogger */
  55. private $logger;
  56. /** @var string */
  57. private $lookupServerUrl;
  58. /** @var IConfig */
  59. private $config;
  60. public function __construct(IAccountManager $accountManager,
  61. IUserManager $userManager,
  62. IClientService $clientService,
  63. ILogger $logger,
  64. ITimeFactory $timeFactory,
  65. IConfig $config
  66. ) {
  67. parent::__construct($timeFactory);
  68. $this->accountManager = $accountManager;
  69. $this->userManager = $userManager;
  70. $this->httpClientService = $clientService;
  71. $this->logger = $logger;
  72. $lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
  73. $this->lookupServerUrl = rtrim($lookupServerUrl, '/');
  74. $this->config = $config;
  75. }
  76. /**
  77. * run the job, then remove it from the jobList
  78. *
  79. * @param IJobList $jobList
  80. * @param ILogger|null $logger
  81. */
  82. public function execute(IJobList $jobList, ILogger $logger = null) {
  83. if ($this->shouldRun($this->argument)) {
  84. parent::execute($jobList, $logger);
  85. $jobList->remove($this, $this->argument);
  86. if ($this->retainJob) {
  87. $this->reAddJob($jobList, $this->argument);
  88. } else {
  89. $this->resetVerificationState();
  90. }
  91. }
  92. }
  93. protected function run($argument) {
  94. $try = (int)$argument['try'] + 1;
  95. switch ($argument['type']) {
  96. case IAccountManager::PROPERTY_WEBSITE:
  97. $result = $this->verifyWebsite($argument);
  98. break;
  99. case IAccountManager::PROPERTY_TWITTER:
  100. case IAccountManager::PROPERTY_EMAIL:
  101. $result = $this->verifyViaLookupServer($argument, $argument['type']);
  102. break;
  103. default:
  104. // no valid type given, no need to retry
  105. $this->logger->error($argument['type'] . ' is no valid type for user account data.');
  106. $result = true;
  107. }
  108. if ($result === true || $try > $this->maxTry) {
  109. $this->retainJob = false;
  110. }
  111. }
  112. /**
  113. * verify web page
  114. *
  115. * @param array $argument
  116. * @return bool true if we could check the verification code, otherwise false
  117. */
  118. protected function verifyWebsite(array $argument) {
  119. $result = false;
  120. $url = rtrim($argument['data'], '/') . '/.well-known/' . 'CloudIdVerificationCode.txt';
  121. $client = $this->httpClientService->newClient();
  122. try {
  123. $response = $client->get($url);
  124. } catch (\Exception $e) {
  125. return false;
  126. }
  127. if ($response->getStatusCode() === Http::STATUS_OK) {
  128. $result = true;
  129. $publishedCode = $response->getBody();
  130. // remove new lines and spaces
  131. $publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
  132. $user = $this->userManager->get($argument['uid']);
  133. // we don't check a valid user -> give up
  134. if ($user === null) {
  135. $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
  136. return $result;
  137. }
  138. $userAccount = $this->accountManager->getAccount($user);
  139. $websiteProp = $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE);
  140. $websiteProp->setVerified($publishedCodeSanitized === $argument['verificationCode']
  141. ? IAccountManager::VERIFIED
  142. : IAccountManager::NOT_VERIFIED
  143. );
  144. $this->accountManager->updateAccount($userAccount);
  145. }
  146. return $result;
  147. }
  148. protected function verifyViaLookupServer(array $argument, string $dataType): bool {
  149. if (empty($this->lookupServerUrl) ||
  150. $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes') !== 'yes' ||
  151. $this->config->getSystemValue('has_internet_connection', true) === false) {
  152. return true;
  153. }
  154. $user = $this->userManager->get($argument['uid']);
  155. // we don't check a valid user -> give up
  156. if ($user === null) {
  157. $this->logger->info($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
  158. return true;
  159. }
  160. $cloudId = $user->getCloudId();
  161. $lookupServerData = $this->queryLookupServer($cloudId);
  162. // for some reasons we couldn't read any data from the lookup server, try again later
  163. if (empty($lookupServerData) || empty($lookupServerData[$dataType])) {
  164. return false;
  165. }
  166. // lookup server has verification data for wrong user data (e.g. email address), try again later
  167. if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
  168. return false;
  169. }
  170. // lookup server hasn't verified the email address so far, try again later
  171. if ($lookupServerData[$dataType]['verified'] === IAccountManager::NOT_VERIFIED) {
  172. return false;
  173. }
  174. try {
  175. $userAccount = $this->accountManager->getAccount($user);
  176. $property = $userAccount->getProperty($dataType);
  177. $property->setVerified(IAccountManager::VERIFIED);
  178. $this->accountManager->updateAccount($userAccount);
  179. } catch (PropertyDoesNotExistException $e) {
  180. return false;
  181. }
  182. return true;
  183. }
  184. /**
  185. * @param string $cloudId
  186. * @return array
  187. */
  188. protected function queryLookupServer($cloudId) {
  189. try {
  190. $client = $this->httpClientService->newClient();
  191. $response = $client->get(
  192. $this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
  193. [
  194. 'timeout' => 10,
  195. 'connect_timeout' => 3,
  196. ]
  197. );
  198. $body = json_decode($response->getBody(), true);
  199. if (is_array($body) && isset($body['federationId']) && $body['federationId'] === $cloudId) {
  200. return $body;
  201. }
  202. } catch (\Exception $e) {
  203. // do nothing, we will just re-try later
  204. }
  205. return [];
  206. }
  207. /**
  208. * re-add background job with new arguments
  209. *
  210. * @param IJobList $jobList
  211. * @param array $argument
  212. */
  213. protected function reAddJob(IJobList $jobList, array $argument) {
  214. $jobList->add(VerifyUserData::class,
  215. [
  216. 'verificationCode' => $argument['verificationCode'],
  217. 'data' => $argument['data'],
  218. 'type' => $argument['type'],
  219. 'uid' => $argument['uid'],
  220. 'try' => (int)$argument['try'] + 1,
  221. 'lastRun' => time()
  222. ]
  223. );
  224. }
  225. /**
  226. * test if it is time for the next run
  227. *
  228. * @param array $argument
  229. * @return bool
  230. */
  231. protected function shouldRun(array $argument) {
  232. $lastRun = (int)$argument['lastRun'];
  233. return ((time() - $lastRun) > $this->interval);
  234. }
  235. /**
  236. * reset verification state after max tries are reached
  237. */
  238. protected function resetVerificationState(): void {
  239. $user = $this->userManager->get($this->argument['uid']);
  240. if ($user !== null) {
  241. $userAccount = $this->accountManager->getAccount($user);
  242. try {
  243. $property = $userAccount->getProperty($this->argument['type']);
  244. $property->setVerified(IAccountManager::NOT_VERIFIED);
  245. $this->accountManager->updateAccount($userAccount);
  246. } catch (PropertyDoesNotExistException $e) {
  247. return;
  248. }
  249. }
  250. }
  251. }