AccountManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2016, Björn Schießle
  5. *
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  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, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Accounts;
  31. use OCA\Settings\BackgroundJobs\VerifyUserData;
  32. use OCP\Accounts\IAccount;
  33. use OCP\Accounts\IAccountManager;
  34. use OCP\BackgroundJob\IJobList;
  35. use OCP\IDBConnection;
  36. use OCP\ILogger;
  37. use OCP\IUser;
  38. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  39. use Symfony\Component\EventDispatcher\GenericEvent;
  40. use function json_decode;
  41. use function json_last_error;
  42. /**
  43. * Class AccountManager
  44. *
  45. * Manage system accounts table
  46. *
  47. * @group DB
  48. * @package OC\Accounts
  49. */
  50. class AccountManager implements IAccountManager {
  51. /** @var IDBConnection database connection */
  52. private $connection;
  53. /** @var string table name */
  54. private $table = 'accounts';
  55. /** @var EventDispatcherInterface */
  56. private $eventDispatcher;
  57. /** @var IJobList */
  58. private $jobList;
  59. /** @var ILogger */
  60. private $logger;
  61. /**
  62. * AccountManager constructor.
  63. *
  64. * @param IDBConnection $connection
  65. * @param EventDispatcherInterface $eventDispatcher
  66. * @param IJobList $jobList
  67. */
  68. public function __construct(IDBConnection $connection,
  69. EventDispatcherInterface $eventDispatcher,
  70. IJobList $jobList,
  71. ILogger $logger) {
  72. $this->connection = $connection;
  73. $this->eventDispatcher = $eventDispatcher;
  74. $this->jobList = $jobList;
  75. $this->logger = $logger;
  76. }
  77. /**
  78. * update user record
  79. *
  80. * @param IUser $user
  81. * @param $data
  82. */
  83. public function updateUser(IUser $user, $data) {
  84. $userData = $this->getUser($user);
  85. $updated = true;
  86. if (empty($userData)) {
  87. $this->insertNewUser($user, $data);
  88. } elseif ($userData !== $data) {
  89. $data = $this->checkEmailVerification($userData, $data, $user);
  90. $data = $this->updateVerifyStatus($userData, $data);
  91. $this->updateExistingUser($user, $data);
  92. } else {
  93. // nothing needs to be done if new and old data set are the same
  94. $updated = false;
  95. }
  96. if ($updated) {
  97. $this->eventDispatcher->dispatch(
  98. 'OC\AccountManager::userUpdated',
  99. new GenericEvent($user, $data)
  100. );
  101. }
  102. }
  103. /**
  104. * delete user from accounts table
  105. *
  106. * @param IUser $user
  107. */
  108. public function deleteUser(IUser $user) {
  109. $uid = $user->getUID();
  110. $query = $this->connection->getQueryBuilder();
  111. $query->delete($this->table)
  112. ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
  113. ->execute();
  114. }
  115. /**
  116. * get stored data from a given user
  117. *
  118. * @param IUser $user
  119. * @return array
  120. */
  121. public function getUser(IUser $user) {
  122. $uid = $user->getUID();
  123. $query = $this->connection->getQueryBuilder();
  124. $query->select('data')->from($this->table)
  125. ->where($query->expr()->eq('uid', $query->createParameter('uid')))
  126. ->setParameter('uid', $uid);
  127. $query->execute();
  128. $result = $query->execute()->fetchAll();
  129. if (empty($result)) {
  130. $userData = $this->buildDefaultUserRecord($user);
  131. $this->insertNewUser($user, $userData);
  132. return $userData;
  133. }
  134. $userDataArray = json_decode($result[0]['data'], true);
  135. $jsonError = json_last_error();
  136. if ($userDataArray === null || $jsonError !== JSON_ERROR_NONE) {
  137. $this->logger->critical("User data of $uid contained invalid JSON (error $jsonError), hence falling back to a default user record");
  138. return $this->buildDefaultUserRecord($user);
  139. }
  140. $userDataArray = $this->addMissingDefaultValues($userDataArray);
  141. return $userDataArray;
  142. }
  143. /**
  144. * check if we need to ask the server for email verification, if yes we create a cronjob
  145. *
  146. * @param $oldData
  147. * @param $newData
  148. * @param IUser $user
  149. * @return array
  150. */
  151. protected function checkEmailVerification($oldData, $newData, IUser $user) {
  152. if ($oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']) {
  153. $this->jobList->add(VerifyUserData::class,
  154. [
  155. 'verificationCode' => '',
  156. 'data' => $newData[self::PROPERTY_EMAIL]['value'],
  157. 'type' => self::PROPERTY_EMAIL,
  158. 'uid' => $user->getUID(),
  159. 'try' => 0,
  160. 'lastRun' => time()
  161. ]
  162. );
  163. $newData[AccountManager::PROPERTY_EMAIL]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
  164. }
  165. return $newData;
  166. }
  167. /**
  168. * make sure that all expected data are set
  169. *
  170. * @param array $userData
  171. * @return array
  172. */
  173. protected function addMissingDefaultValues(array $userData) {
  174. foreach ($userData as $key => $value) {
  175. if (!isset($userData[$key]['verified'])) {
  176. $userData[$key]['verified'] = self::NOT_VERIFIED;
  177. }
  178. }
  179. return $userData;
  180. }
  181. /**
  182. * reset verification status if personal data changed
  183. *
  184. * @param array $oldData
  185. * @param array $newData
  186. * @return array
  187. */
  188. protected function updateVerifyStatus($oldData, $newData) {
  189. // which account was already verified successfully?
  190. $twitterVerified = isset($oldData[self::PROPERTY_TWITTER]['verified']) && $oldData[self::PROPERTY_TWITTER]['verified'] === self::VERIFIED;
  191. $websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
  192. $emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
  193. // keep old verification status if we don't have a new one
  194. if(!isset($newData[self::PROPERTY_TWITTER]['verified'])) {
  195. // keep old verification status if value didn't changed and an old value exists
  196. $keepOldStatus = $newData[self::PROPERTY_TWITTER]['value'] === $oldData[self::PROPERTY_TWITTER]['value'] && isset($oldData[self::PROPERTY_TWITTER]['verified']);
  197. $newData[self::PROPERTY_TWITTER]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_TWITTER]['verified'] : self::NOT_VERIFIED;
  198. }
  199. if(!isset($newData[self::PROPERTY_WEBSITE]['verified'])) {
  200. // keep old verification status if value didn't changed and an old value exists
  201. $keepOldStatus = $newData[self::PROPERTY_WEBSITE]['value'] === $oldData[self::PROPERTY_WEBSITE]['value'] && isset($oldData[self::PROPERTY_WEBSITE]['verified']);
  202. $newData[self::PROPERTY_WEBSITE]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_WEBSITE]['verified'] : self::NOT_VERIFIED;
  203. }
  204. if(!isset($newData[self::PROPERTY_EMAIL]['verified'])) {
  205. // keep old verification status if value didn't changed and an old value exists
  206. $keepOldStatus = $newData[self::PROPERTY_EMAIL]['value'] === $oldData[self::PROPERTY_EMAIL]['value'] && isset($oldData[self::PROPERTY_EMAIL]['verified']);
  207. $newData[self::PROPERTY_EMAIL]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_EMAIL]['verified'] : self::VERIFICATION_IN_PROGRESS;
  208. }
  209. // reset verification status if a value from a previously verified data was changed
  210. if($twitterVerified &&
  211. $oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
  212. ) {
  213. $newData[self::PROPERTY_TWITTER]['verified'] = self::NOT_VERIFIED;
  214. }
  215. if($websiteVerified &&
  216. $oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
  217. ) {
  218. $newData[self::PROPERTY_WEBSITE]['verified'] = self::NOT_VERIFIED;
  219. }
  220. if($emailVerified &&
  221. $oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
  222. ) {
  223. $newData[self::PROPERTY_EMAIL]['verified'] = self::NOT_VERIFIED;
  224. }
  225. return $newData;
  226. }
  227. /**
  228. * add new user to accounts table
  229. *
  230. * @param IUser $user
  231. * @param array $data
  232. */
  233. protected function insertNewUser(IUser $user, $data) {
  234. $uid = $user->getUID();
  235. $jsonEncodedData = json_encode($data);
  236. $query = $this->connection->getQueryBuilder();
  237. $query->insert($this->table)
  238. ->values(
  239. [
  240. 'uid' => $query->createNamedParameter($uid),
  241. 'data' => $query->createNamedParameter($jsonEncodedData),
  242. ]
  243. )
  244. ->execute();
  245. }
  246. /**
  247. * update existing user in accounts table
  248. *
  249. * @param IUser $user
  250. * @param array $data
  251. */
  252. protected function updateExistingUser(IUser $user, $data) {
  253. $uid = $user->getUID();
  254. $jsonEncodedData = json_encode($data);
  255. $query = $this->connection->getQueryBuilder();
  256. $query->update($this->table)
  257. ->set('data', $query->createNamedParameter($jsonEncodedData))
  258. ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
  259. ->execute();
  260. }
  261. /**
  262. * build default user record in case not data set exists yet
  263. *
  264. * @param IUser $user
  265. * @return array
  266. */
  267. protected function buildDefaultUserRecord(IUser $user) {
  268. return [
  269. self::PROPERTY_DISPLAYNAME =>
  270. [
  271. 'value' => $user->getDisplayName(),
  272. 'scope' => self::VISIBILITY_CONTACTS_ONLY,
  273. 'verified' => self::NOT_VERIFIED,
  274. ],
  275. self::PROPERTY_ADDRESS =>
  276. [
  277. 'value' => '',
  278. 'scope' => self::VISIBILITY_PRIVATE,
  279. 'verified' => self::NOT_VERIFIED,
  280. ],
  281. self::PROPERTY_WEBSITE =>
  282. [
  283. 'value' => '',
  284. 'scope' => self::VISIBILITY_PRIVATE,
  285. 'verified' => self::NOT_VERIFIED,
  286. ],
  287. self::PROPERTY_EMAIL =>
  288. [
  289. 'value' => $user->getEMailAddress(),
  290. 'scope' => self::VISIBILITY_CONTACTS_ONLY,
  291. 'verified' => self::NOT_VERIFIED,
  292. ],
  293. self::PROPERTY_AVATAR =>
  294. [
  295. 'scope' => self::VISIBILITY_CONTACTS_ONLY
  296. ],
  297. self::PROPERTY_PHONE =>
  298. [
  299. 'value' => '',
  300. 'scope' => self::VISIBILITY_PRIVATE,
  301. 'verified' => self::NOT_VERIFIED,
  302. ],
  303. self::PROPERTY_TWITTER =>
  304. [
  305. 'value' => '',
  306. 'scope' => self::VISIBILITY_PRIVATE,
  307. 'verified' => self::NOT_VERIFIED,
  308. ],
  309. ];
  310. }
  311. private function parseAccountData(IUser $user, $data): Account {
  312. $account = new Account($user);
  313. foreach($data as $property => $accountData) {
  314. $account->setProperty($property, $accountData['value'] ?? '', $accountData['scope'] ?? self::VISIBILITY_PRIVATE, $accountData['verified'] ?? self::NOT_VERIFIED);
  315. }
  316. return $account;
  317. }
  318. public function getAccount(IUser $user): IAccount {
  319. return $this->parseAccountData($user, $this->getUser($user));
  320. }
  321. }