-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathAccountService.php
More file actions
567 lines (507 loc) · 19.4 KB
/
AccountService.php
File metadata and controls
567 lines (507 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Libresign\Service;
use InvalidArgumentException;
use OC\Files\Filesystem;
use OCA\Libresign\AppInfo\Application;
use OCA\Libresign\Db\File as FileEntity;
use OCA\Libresign\Db\FileMapper;
use OCA\Libresign\Db\FileTypeMapper;
use OCA\Libresign\Db\IdentifyMethodMapper;
use OCA\Libresign\Db\SignRequest;
use OCA\Libresign\Db\SignRequestMapper;
use OCA\Libresign\Db\UserElement;
use OCA\Libresign\Db\UserElementMapper;
use OCA\Libresign\Exception\InvalidPasswordException;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory;
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
use OCA\Libresign\Helper\ValidateHelper;
use OCA\Settings\Mailer\NewUserMailHelper;
use OCP\Accounts\IAccountManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Files\Config\IMountProviderCollection;
use OCP\Files\File;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Http\Client\IClientService;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use Sabre\DAV\UUIDUtil;
use Throwable;
class AccountService {
private ?SignRequest $signRequest = null;
private ?\OCA\Libresign\Db\File $fileData = null;
private \OCP\Files\File $fileToSign;
public function __construct(
private IL10N $l10n,
private SignRequestMapper $signRequestMapper,
private IUserManager $userManager,
private IAccountManager $accountManager,
private IRootFolder $root,
private IMimeTypeDetector $mimeTypeDetector,
private FileMapper $fileMapper,
private FileTypeMapper $fileTypeMapper,
private SignFileService $signFileService,
private RequestSignatureService $requestSignatureService,
private CertificateEngineFactory $certificateEngineFactory,
private IConfig $config,
private IAppConfig $appConfig,
private IMountProviderCollection $mountProviderCollection,
private NewUserMailHelper $newUserMail,
private IdentifyMethodService $identifyMethodService,
private IdentifyMethodMapper $identifyMethodMapper,
private ValidateHelper $validateHelper,
private IURLGenerator $urlGenerator,
private Pkcs12Handler $pkcs12Handler,
private IGroupManager $groupManager,
private IdDocsService $idDocsService,
private SignerElementsService $signerElementsService,
private UserElementMapper $userElementMapper,
private FolderService $folderService,
private IClientService $clientService,
private ITimeFactory $timeFactory,
) {
}
public function validateCreateToSign(array $data): void {
if (!UUIDUtil::validateUUID($data['uuid'])) {
throw new LibresignException($this->l10n->t('Invalid UUID'), 1);
}
try {
$signRequest = $this->getSignRequestByUuid($data['uuid']);
} catch (\Throwable) {
throw new LibresignException($this->l10n->t('UUID not found'), 1);
}
$identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
if (!array_key_exists('identify', $data['user'])) {
throw new LibresignException($this->l10n->t('Invalid identification method'), 1);
}
foreach ($data['user']['identify'] as $method => $value) {
if (!array_key_exists($method, $identifyMethods)) {
throw new LibresignException($this->l10n->t('Invalid identification method'), 1);
}
foreach ($identifyMethods[$method] as $identifyMethod) {
$identifyMethod->validateToCreateAccount($value);
}
}
if (empty($data['password'])) {
throw new LibresignException($this->l10n->t('Password is mandatory'), 1);
}
$file = $this->getFileByUuid($data['uuid']);
if (empty($file['fileToSign'])) {
throw new LibresignException($this->l10n->t('File not found'));
}
}
public function getFileByUuid(string $uuid): array {
$signRequest = $this->getSignRequestByUuid($uuid);
if (!$this->fileData instanceof \OCA\Libresign\Db\File) {
$this->fileData = $this->fileMapper->getById($signRequest->getFileId());
$nodeId = $this->fileData->getNodeId();
$fileToSign = $this->root->getUserFolder($this->fileData->getUserId())->getFirstNodeById($nodeId);
if ($fileToSign) {
$this->fileToSign = $fileToSign;
}
}
return [
'fileData' => $this->fileData,
'fileToSign' => $this->fileToSign
];
}
public function validateCertificateData(array $data): void {
if (array_key_exists('email', $data['user']) && empty($data['user']['email'])) {
throw new LibresignException($this->l10n->t('You must have an email. You can define the email in your profile.'), 1);
}
if (!empty($data['user']['email']) && !filter_var($data['user']['email'], FILTER_VALIDATE_EMAIL)) {
throw new LibresignException($this->l10n->t('Invalid email'), 1);
}
if (empty($data['signPassword'])) {
throw new LibresignException($this->l10n->t('Password to sign is mandatory'), 1);
}
}
/**
* Get signRequest by Uuid
*/
public function getSignRequestByUuid(string $uuid): SignRequest {
if (!$this->signRequest instanceof SignRequest) {
$this->signRequest = $this->signRequestMapper->getByUuid($uuid);
}
return $this->signRequest;
}
public function createToSign(string $uuid, string $email, string $password, ?string $signPassword): void {
$signRequest = $this->getSignRequestByUuid($uuid);
$newUser = $this->userManager->createUser($email, $password);
$newUser->setDisplayName($signRequest->getDisplayName());
$newUser->setSystemEMailAddress($email);
$this->updateIdentifyMethodToAccount($signRequest->getId(), $email, $newUser->getUID());
if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') {
try {
$emailTemplate = $this->newUserMail->generateTemplate($newUser, false);
$this->newUserMail->sendMail($newUser, $emailTemplate);
} catch (\Exception) {
throw new LibresignException('Unable to send the invitation', 1);
}
}
if ($signPassword) {
$certificate = $this->pkcs12Handler->generateCertificate(
[
'host' => $newUser->getPrimaryEMailAddress(),
'uid' => 'account:' . $newUser->getUID(),
'name' => $newUser->getDisplayName()
],
$signPassword,
$newUser->getDisplayName()
);
$this->pkcs12Handler->savePfx($newUser->getPrimaryEMailAddress(), $certificate);
}
}
public function getCertificateEngineName(): string {
return $this->certificateEngineFactory->getEngine()->getName();
}
/**
* @return array<string, mixed>
*/
public function getConfig(?IUser $user = null): array {
$info['identificationDocumentsFlow'] = $this->appConfig->getValueBool(Application::APP_ID, 'identification_documents', false);
$info['hasSignatureFile'] = $this->hasSignatureFile($user);
$info['phoneNumber'] = $this->getPhoneNumber($user);
$info['isApprover'] = $this->validateHelper->userCanApproveValidationDocuments($user, false);
$info['id_docs_filters'] = $this->getUserConfigIdDocsFilters($user);
$info['id_docs_sort'] = $this->getUserConfigIdDocsSort($user);
$info['crl_filters'] = $this->getUserConfigCrlFilters($user);
$info['crl_sort'] = $this->getUserConfigCrlSort($user);
$info['grid_view'] = $this->getUserConfigByKey('grid_view', $user) === '1';
$info['signer_identify_tab'] = $this->getUserConfigByKey('signer_identify_tab', $user);
return array_filter($info);
}
public function getConfigFilters(?IUser $user = null): array {
$info['filter_modified'] = $this->getUserConfigByKey('filter_modified', $user);
$info['filter_status'] = $this->getUserConfigByKey('filter_status', $user);
return $info;
}
private function updateIdentifyMethodToAccount(int $signRequestId, string $email, string $uid): void {
$identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequestId);
foreach ($identifyMethods as $name => $methods) {
if ($name === IdentifyMethodService::IDENTIFY_EMAIL) {
foreach ($methods as $identifyMethod) {
$entity = $identifyMethod->getEntity();
if ($entity->getIdentifierValue() === $email) {
$entity->setIdentifierKey(IdentifyMethodService::IDENTIFY_ACCOUNT);
$entity->setIdentifierValue($uid);
$this->identifyMethodMapper->update($entity);
}
}
}
}
}
private function getPhoneNumber(?IUser $user): string {
if (!$user) {
return '';
}
$userAccount = $this->accountManager->getAccount($user);
return $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue();
}
public function hasSignatureFile(?IUser $user = null): bool {
if (!$user) {
return false;
}
try {
$this->pkcs12Handler->getPfxOfCurrentSigner($user->getUID());
return true;
} catch (LibresignException) {
return false;
}
}
private function getUserConfigByKey(string $key, ?IUser $user = null): string {
if (!$user) {
return '';
}
return $this->config->getUserValue($user->getUID(), Application::APP_ID, $key);
}
private function getUserConfigIdDocsFilters(?IUser $user = null): array {
if (!$user) {
return [];
}
$value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'id_docs_filters', '');
if (empty($value)) {
return [];
}
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : [];
}
private function getUserConfigCrlFilters(?IUser $user = null): array {
if (!$user || !$this->groupManager->isAdmin($user->getUID())) {
return [];
}
$value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'crl_filters', '');
if (empty($value)) {
return [];
}
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : [];
}
private function getUserConfigCrlSort(?IUser $user): array {
if (!$user || !$this->groupManager->isAdmin($user->getUID())) {
return ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
}
$value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'crl_sort', '');
if (empty($value)) {
return ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
}
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
}
private function getUserConfigIdDocsSort(?IUser $user): array {
if (!$user || !$this->validateHelper->userCanApproveValidationDocuments($user, false)) {
return ['sortBy' => null, 'sortOrder' => null];
}
$value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'id_docs_sort', '');
if (empty($value)) {
return ['sortBy' => null, 'sortOrder' => null];
}
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : ['sortBy' => null, 'sortOrder' => null];
}
/**
* Get PDF node by UUID
*
* @psalm-suppress MixedReturnStatement
* @throws Throwable
* @return \OCP\Files\File
*/
public function getPdfByUuid(string $uuid): File {
$fileData = $this->fileMapper->getByUuid($uuid);
if (in_array($fileData->getStatus(), [FileEntity::STATUS_PARTIAL_SIGNED, FileEntity::STATUS_SIGNED])) {
$nodeId = $fileData->getSignedNodeId();
} else {
$nodeId = $fileData->getNodeId();
}
$file = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
if (!$file instanceof File) {
throw new DoesNotExistException('Not found');
}
return $file;
}
public function getFileByNodeId(int $nodeId): File {
try {
return $this->folderService->getFileById($nodeId);
} catch (NotFoundException) {
throw new DoesNotExistException('Not found');
}
}
public function canRequestSign(?IUser $user = null): bool {
if (!$user) {
return false;
}
$authorized = $this->appConfig->getValueArray(Application::APP_ID, 'groups_request_sign', ['admin']);
if (empty($authorized)) {
return false;
}
$userGroups = $this->groupManager->getUserGroupIds($user);
if (!array_intersect($userGroups, $authorized)) {
return false;
}
return true;
}
public function getSettings(?IUser $user = null): array {
$return['canRequestSign'] = $this->canRequestSign($user);
$return['hasSignatureFile'] = $this->hasSignatureFile($user);
return $return;
}
public function addFilesToAccount(array $files, IUser $user): void {
$this->idDocsService->addIdDocs($files, $user);
}
public function deleteFileFromAccount(int $nodeId, IUser $user): void {
$this->idDocsService->deleteIdDoc($nodeId, $user);
}
public function saveVisibleElements(array $elements, string $sessionId, ?IUser $user): void {
foreach ($elements as $element) {
$this->saveVisibleElement($element, $sessionId, $user);
}
}
public function saveVisibleElement(array $data, string $sessionId, ?IUser $user): void {
if (isset($data['elementId'])) {
$this->updateFileOfVisibleElement($data);
$this->updateDataOfVisibleElement($data);
} elseif ($user instanceof IUser) {
$file = $this->saveFileOfVisibleElementUsingUser($data, $user);
$this->insertVisibleElement($data, $user, $file);
} else {
$file = $this->saveFileOfVisibleElementUsingSession($data, $sessionId);
}
}
private function updateFileOfVisibleElement(array $data): void {
if (!isset($data['file'])) {
return;
}
$userElement = $this->userElementMapper->findOne(['id' => $data['elementId']]);
$file = $this->folderService->getFileById($userElement->getFileId());
$file->putContent($this->getFileRaw($data));
}
private function updateDataOfVisibleElement(array $data): void {
if (!isset($data['starred'])) {
return;
}
$userElement = $this->userElementMapper->findOne(['id' => $data['elementId']]);
$userElement->setStarred($data['starred'] ? 1 : 0);
$this->userElementMapper->update($userElement);
}
private function saveFileOfVisibleElementUsingUser(array $data, IUser $user): File {
$rootSignatureFolder = $this->folderService->getFolder();
$folderName = $this->folderService->getFolderName($data, $user);
$folderToFile = $rootSignatureFolder->newFolder($folderName);
return $folderToFile->newFile(UUIDUtil::getUUID() . '.png', $this->getFileRaw($data));
}
private function saveFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
if (!empty($data['nodeId'])) {
return $this->updateFileOfVisibleElementUsingSession($data, $sessionId);
}
return $this->createFileOfVisibleElementUsingSession($data, $sessionId);
}
private function updateFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
$fileList = $this->signerElementsService->getElementsFromSession();
$element = array_filter($fileList, fn (File $element) => $element->getId() === $data['nodeId']);
$element = current($element);
if (!$element instanceof File) {
throw new \Exception($this->l10n->t('File not found'));
}
$element->putContent($this->getFileRaw($data));
return $element;
}
private function createFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
$rootSignatureFolder = $this->folderService->getFolder();
$folderName = $sessionId;
$folderToFile = $rootSignatureFolder->newFolder($folderName);
$filename = implode(
'_',
[
$data['type'],
$this->timeFactory->getDateTime()->getTimestamp(),
]
) . '.png';
return $folderToFile->newFile($filename, $this->getFileRaw($data));
}
private function insertVisibleElement(array $data, IUser $user, File $file): void {
$userElement = new UserElement();
$userElement->setType($data['type']);
$userElement->setFileId($file->getId());
$userElement->setUserId($user->getUID());
$userElement->setStarred(isset($data['starred']) && $data['starred'] ? 1 : 0);
$userElement->setCreatedAt($this->timeFactory->getDateTime());
$this->userElementMapper->insert($userElement);
}
private function getFileRaw(array $data): string {
if (!empty($data['file']['url'])) {
if (!filter_var($data['file']['url'], FILTER_VALIDATE_URL)) {
throw new \Exception($this->l10n->t('Invalid URL file'));
}
$response = $this->clientService->newClient()->get($data['file']['url']);
$contentType = $response->getHeader('Content-Type');
if ($contentType !== 'image/png') {
throw new \Exception($this->l10n->t('Visible element file must be png.'));
}
$content = (string)$response->getBody();
if (empty($content)) {
throw new \Exception($this->l10n->t('Empty file'));
}
$this->validateHelper->validateBase64($content, ValidateHelper::TYPE_VISIBLE_ELEMENT_USER);
return $content;
}
$this->validateHelper->validateBase64($data['file']['base64'], ValidateHelper::TYPE_VISIBLE_ELEMENT_USER);
$withMime = explode(',', (string)$data['file']['base64']);
if (count($withMime) === 2) {
$content = base64_decode($withMime[1]);
} else {
$content = base64_decode((string)$data['file']['base64']);
}
if (!$content) {
return '';
}
return $content;
}
public function deleteSignatureElement(?IUser $user, string $sessionId, int $nodeId): void {
if ($user instanceof IUser) {
$element = $this->userElementMapper->findOne([
'file_id' => $nodeId,
'user_id' => $user->getUID(),
]);
$this->userElementMapper->delete($element);
try {
$file = $this->folderService->getFileById($element->getFileId());
$file->delete();
} catch (NotFoundException) {
}
} else {
$rootSignatureFolder = $this->folderService->getFolder();
$folderName = $sessionId;
$rootSignatureFolder->delete($folderName);
}
}
/**
* @throws LibresignException at savePfx
* @throws InvalidArgumentException
*/
public function uploadPfx(array $file, IUser $user): void {
if (
$file['error'] !== 0
|| !is_uploaded_file($file['tmp_name'])
|| Filesystem::isFileBlacklisted($file['tmp_name'])
) {
// TRANSLATORS Error when the uploaded certificate file is not valid
throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
}
if ($file['size'] > 10 * 1024) {
// TRANSLATORS Error when the certificate file is bigger than normal
throw new InvalidArgumentException($this->l10n->t('File is too big'));
}
$content = file_get_contents($file['tmp_name']);
$mimetype = $this->mimeTypeDetector->detectString($content);
if ($mimetype !== 'application/octet-stream') {
// TRANSLATORS Error when the mimetype of uploaded file is not valid
throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
}
$extension = strtolower(pathinfo((string)$file['name'], PATHINFO_EXTENSION));
if ($extension !== 'pfx') {
// TRANSLATORS Error when the certificate file is not a pfx file
throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
}
unlink($file['tmp_name']);
$this->pkcs12Handler->savePfx($user->getUID(), $content);
}
public function deletePfx(IUser $user): void {
$this->pkcs12Handler->deletePfx($user->getUID());
}
/**
* @throws LibresignException when have not a certificate file
*/
public function updatePfxPassword(IUser $user, string $current, string $new): void {
try {
$pfx = $this->pkcs12Handler->updatePassword($user->getUID(), $current, $new);
} catch (InvalidPasswordException) {
throw new LibresignException($this->l10n->t('Invalid user or password'));
}
}
/**
* @throws LibresignException when have not a certificate file
*/
public function readPfxData(IUser $user, string $password): array {
try {
return $this->pkcs12Handler
->setCertificate($this->pkcs12Handler->getPfxOfCurrentSigner($user->getUID()))
->setPassword($password)
->readCertificate();
} catch (InvalidPasswordException) {
throw new LibresignException($this->l10n->t('Invalid user or password'));
}
}
}