VerifyUserData.php 7.9 KB

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