VerifyUserData.php 8.3 KB

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