VerifyUserData.php 8.1 KB

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