1
0

VerifyUserData.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 OC\Accounts\AccountManager;
  32. use OCP\Accounts\IAccountManager;
  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 AccountManager */
  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(AccountManager $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. $userData = $this->accountManager->getUser($user);
  139. if ($publishedCodeSanitized === $argument['verificationCode']) {
  140. $userData[IAccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFIED;
  141. } else {
  142. $userData[IAccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::NOT_VERIFIED;
  143. }
  144. $this->accountManager->updateUser($user, $userData);
  145. }
  146. return $result;
  147. }
  148. /**
  149. * verify email address
  150. *
  151. * @param array $argument
  152. * @param string $dataType
  153. * @return bool true if we could check the verification code, otherwise false
  154. */
  155. protected function verifyViaLookupServer(array $argument, $dataType) {
  156. if (empty($this->lookupServerUrl) ||
  157. $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes') !== 'yes' ||
  158. $this->config->getSystemValue('has_internet_connection', true) === false) {
  159. return false;
  160. }
  161. $user = $this->userManager->get($argument['uid']);
  162. // we don't check a valid user -> give up
  163. if ($user === null) {
  164. $this->logger->info($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
  165. return true;
  166. }
  167. $localUserData = $this->accountManager->getUser($user);
  168. $cloudId = $user->getCloudId();
  169. // ask lookup-server for user data
  170. $lookupServerData = $this->queryLookupServer($cloudId);
  171. // for some reasons we couldn't read any data from the lookup server, try again later
  172. if (empty($lookupServerData) || empty($lookupServerData[$dataType])) {
  173. return false;
  174. }
  175. // lookup server has verification data for wrong user data (e.g. email address), try again later
  176. if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
  177. return false;
  178. }
  179. // lookup server hasn't verified the email address so far, try again later
  180. if ($lookupServerData[$dataType]['verified'] === AccountManager::NOT_VERIFIED) {
  181. return false;
  182. }
  183. $localUserData[$dataType]['verified'] = AccountManager::VERIFIED;
  184. $this->accountManager->updateUser($user, $localUserData);
  185. return true;
  186. }
  187. /**
  188. * @param string $cloudId
  189. * @return array
  190. */
  191. protected function queryLookupServer($cloudId) {
  192. try {
  193. $client = $this->httpClientService->newClient();
  194. $response = $client->get(
  195. $this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
  196. [
  197. 'timeout' => 10,
  198. 'connect_timeout' => 3,
  199. ]
  200. );
  201. $body = json_decode($response->getBody(), true);
  202. if (is_array($body) && isset($body['federationId']) && $body['federationId'] === $cloudId) {
  203. return $body;
  204. }
  205. } catch (\Exception $e) {
  206. // do nothing, we will just re-try later
  207. }
  208. return [];
  209. }
  210. /**
  211. * re-add background job with new arguments
  212. *
  213. * @param IJobList $jobList
  214. * @param array $argument
  215. */
  216. protected function reAddJob(IJobList $jobList, array $argument) {
  217. $jobList->add(VerifyUserData::class,
  218. [
  219. 'verificationCode' => $argument['verificationCode'],
  220. 'data' => $argument['data'],
  221. 'type' => $argument['type'],
  222. 'uid' => $argument['uid'],
  223. 'try' => (int)$argument['try'] + 1,
  224. 'lastRun' => time()
  225. ]
  226. );
  227. }
  228. /**
  229. * test if it is time for the next run
  230. *
  231. * @param array $argument
  232. * @return bool
  233. */
  234. protected function shouldRun(array $argument) {
  235. $lastRun = (int)$argument['lastRun'];
  236. return ((time() - $lastRun) > $this->interval);
  237. }
  238. /**
  239. * reset verification state after max tries are reached
  240. */
  241. protected function resetVerificationState() {
  242. $user = $this->userManager->get($this->argument['uid']);
  243. if ($user !== null) {
  244. $accountData = $this->accountManager->getUser($user);
  245. $accountData[$this->argument['type']]['verified'] = AccountManager::NOT_VERIFIED;
  246. $this->accountManager->updateUser($user, $accountData);
  247. }
  248. }
  249. }