• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

LibreSign / libresign / 19861903261

02 Dec 2025 02:26PM UTC coverage: 40.76%. First build
19861903261

Pull #5919

github

GitHub
Merge 994ee1a8b into 9adaadaec
Pull Request #5919:

3 of 10 new or added lines in 1 file covered. (30.0%)

4978 of 12213 relevant lines covered (40.76%)

3.98 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

24.34
/lib/Service/AccountService.php
1
<?php
2

3
declare(strict_types=1);
4
/**
5
 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6
 * SPDX-License-Identifier: AGPL-3.0-or-later
7
 */
8

9
namespace OCA\Libresign\Service;
10

11
use InvalidArgumentException;
12
use OC\Files\Filesystem;
13
use OCA\Libresign\AppInfo\Application;
14
use OCA\Libresign\Db\AccountFileMapper;
15
use OCA\Libresign\Db\File as FileEntity;
16
use OCA\Libresign\Db\FileMapper;
17
use OCA\Libresign\Db\FileTypeMapper;
18
use OCA\Libresign\Db\IdentifyMethodMapper;
19
use OCA\Libresign\Db\SignRequest;
20
use OCA\Libresign\Db\SignRequestMapper;
21
use OCA\Libresign\Db\UserElement;
22
use OCA\Libresign\Db\UserElementMapper;
23
use OCA\Libresign\Exception\InvalidPasswordException;
24
use OCA\Libresign\Exception\LibresignException;
25
use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory;
26
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
27
use OCA\Libresign\Helper\ValidateHelper;
28
use OCA\Settings\Mailer\NewUserMailHelper;
29
use OCP\Accounts\IAccountManager;
30
use OCP\AppFramework\Db\DoesNotExistException;
31
use OCP\AppFramework\Utility\ITimeFactory;
32
use OCP\Files\Config\IMountProviderCollection;
33
use OCP\Files\File;
34
use OCP\Files\IMimeTypeDetector;
35
use OCP\Files\IRootFolder;
36
use OCP\Files\NotFoundException;
37
use OCP\Http\Client\IClientService;
38
use OCP\IAppConfig;
39
use OCP\IConfig;
40
use OCP\IGroupManager;
41
use OCP\IL10N;
42
use OCP\IURLGenerator;
43
use OCP\IUser;
44
use OCP\IUserManager;
45
use Sabre\DAV\UUIDUtil;
46
use Throwable;
47

48
class AccountService {
49
        private ?SignRequest $signRequest = null;
50
        private ?\OCA\Libresign\Db\File $fileData = null;
51
        private \OCP\Files\File $fileToSign;
52

53
        public function __construct(
54
                private IL10N $l10n,
55
                private SignRequestMapper $signRequestMapper,
56
                private IUserManager $userManager,
57
                private IAccountManager $accountManager,
58
                private IRootFolder $root,
59
                private IMimeTypeDetector $mimeTypeDetector,
60
                private FileMapper $fileMapper,
61
                private FileTypeMapper $fileTypeMapper,
62
                private AccountFileMapper $accountFileMapper,
63
                private SignFileService $signFileService,
64
                private RequestSignatureService $requestSignatureService,
65
                private CertificateEngineFactory $certificateEngineFactory,
66
                private IConfig $config,
67
                private IAppConfig $appConfig,
68
                private IMountProviderCollection $mountProviderCollection,
69
                private NewUserMailHelper $newUserMail,
70
                private IdentifyMethodService $identifyMethodService,
71
                private IdentifyMethodMapper $identifyMethodMapper,
72
                private ValidateHelper $validateHelper,
73
                private IURLGenerator $urlGenerator,
74
                private Pkcs12Handler $pkcs12Handler,
75
                private IGroupManager $groupManager,
76
                private AccountFileService $accountFileService,
77
                private SignerElementsService $signerElementsService,
78
                private UserElementMapper $userElementMapper,
79
                private FolderService $folderService,
80
                private IClientService $clientService,
81
                private ITimeFactory $timeFactory,
82
        ) {
83
        }
41✔
84

85
        public function validateCreateToSign(array $data): void {
86
                if (!UUIDUtil::validateUUID($data['uuid'])) {
1✔
87
                        throw new LibresignException($this->l10n->t('Invalid UUID'), 1);
1✔
88
                }
89
                try {
90
                        $signRequest = $this->getSignRequestByUuid($data['uuid']);
×
91
                } catch (\Throwable) {
×
92
                        throw new LibresignException($this->l10n->t('UUID not found'), 1);
×
93
                }
94
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
95
                if (!array_key_exists('identify', $data['user'])) {
×
96
                        throw new LibresignException($this->l10n->t('Invalid identification method'), 1);
×
97
                }
98
                foreach ($data['user']['identify'] as $method => $value) {
×
99
                        if (!array_key_exists($method, $identifyMethods)) {
×
100
                                throw new LibresignException($this->l10n->t('Invalid identification method'), 1);
×
101
                        }
102
                        foreach ($identifyMethods[$method] as $identifyMethod) {
×
103
                                $identifyMethod->validateToCreateAccount($value);
×
104
                        }
105
                }
106
                if (empty($data['password'])) {
×
107
                        throw new LibresignException($this->l10n->t('Password is mandatory'), 1);
×
108
                }
109
                $file = $this->getFileByUuid($data['uuid']);
×
110
                if (empty($file['fileToSign'])) {
×
111
                        throw new LibresignException($this->l10n->t('File not found'));
×
112
                }
113
        }
114

115
        public function getFileByUuid(string $uuid): array {
116
                $signRequest = $this->getSignRequestByUuid($uuid);
×
117
                if (!$this->fileData instanceof \OCA\Libresign\Db\File) {
×
118
                        $this->fileData = $this->fileMapper->getById($signRequest->getFileId());
×
119

120
                        $nodeId = $this->fileData->getNodeId();
×
121

122
                        $fileToSign = $this->root->getUserFolder($this->fileData->getUserId())->getFirstNodeById($nodeId);
×
123
                        if ($fileToSign) {
×
124
                                $this->fileToSign = $fileToSign;
×
125
                        }
126
                }
127
                return [
×
128
                        'fileData' => $this->fileData,
×
129
                        'fileToSign' => $this->fileToSign
×
130
                ];
×
131
        }
132

133
        public function validateCertificateData(array $data): void {
134
                if (array_key_exists('email', $data['user']) && empty($data['user']['email'])) {
4✔
135
                        throw new LibresignException($this->l10n->t('You must have an email. You can define the email in your profile.'), 1);
1✔
136
                }
137
                if (!empty($data['user']['email']) && !filter_var($data['user']['email'], FILTER_VALIDATE_EMAIL)) {
3✔
138
                        throw new LibresignException($this->l10n->t('Invalid email'), 1);
1✔
139
                }
140
                if (empty($data['signPassword'])) {
2✔
141
                        throw new LibresignException($this->l10n->t('Password to sign is mandatory'), 1);
1✔
142
                }
143
        }
144

145
        public function validateAccountFiles(array $files, IUser $user): void {
146
                foreach ($files as $fileIndex => $file) {
5✔
147
                        $this->validateAccountFile($fileIndex, $file, $user);
5✔
148
                }
149
        }
150

151
        private function validateAccountFile(int $fileIndex, array $file, IUser $user): void {
152
                $profileFileTypes = $this->fileTypeMapper->getTypes();
5✔
153
                if (!array_key_exists($file['type'], $profileFileTypes)) {
5✔
154
                        throw new LibresignException(json_encode([
2✔
155
                                'type' => 'danger',
2✔
156
                                'file' => $fileIndex,
2✔
157
                                'message' => $this->l10n->t('Invalid file type.')
2✔
158
                        ]));
2✔
159
                }
160

161
                try {
162
                        $this->validateHelper->validateFileTypeExists($file['type']);
3✔
163
                        $this->validateHelper->validateNewFile($file, ValidateHelper::TYPE_ACCOUNT_DOCUMENT, $user);
3✔
164
                        $this->validateHelper->validateUserHasNoFileWithThisType($user->getUID(), $file['type']);
3✔
165
                } catch (\Exception $e) {
×
166
                        throw new LibresignException(json_encode([
×
167
                                'type' => 'danger',
×
168
                                'file' => $fileIndex,
×
169
                                'message' => $e->getMessage()
×
170
                        ]));
×
171
                }
172
        }
173

174
        /**
175
         * Get signRequest by Uuid
176
         */
177
        public function getSignRequestByUuid(string $uuid): SignRequest {
178
                if (!$this->signRequest instanceof SignRequest) {
1✔
179
                        $this->signRequest = $this->signRequestMapper->getByUuid($uuid);
1✔
180
                }
181
                return $this->signRequest;
1✔
182
        }
183

184
        public function createToSign(string $uuid, string $email, string $password, ?string $signPassword): void {
185
                $signRequest = $this->getSignRequestByUuid($uuid);
1✔
186

187
                $newUser = $this->userManager->createUser($email, $password);
1✔
188
                $newUser->setDisplayName($signRequest->getDisplayName());
1✔
189
                $newUser->setSystemEMailAddress($email);
1✔
190

191
                $this->updateIdentifyMethodToAccount($signRequest->getId(), $email, $newUser->getUID());
1✔
192

193
                if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') {
1✔
194
                        try {
195
                                $emailTemplate = $this->newUserMail->generateTemplate($newUser, false);
1✔
196
                                $this->newUserMail->sendMail($newUser, $emailTemplate);
1✔
197
                        } catch (\Exception) {
1✔
198
                                throw new LibresignException('Unable to send the invitation', 1);
1✔
199
                        }
200
                }
201

202
                if ($signPassword) {
×
203
                        $certificate = $this->pkcs12Handler->generateCertificate(
×
204
                                [
×
205
                                        'host' => $newUser->getPrimaryEMailAddress(),
×
206
                                        'uid' => 'account:' . $newUser->getUID(),
×
207
                                        'name' => $newUser->getDisplayName()
×
208
                                ],
×
209
                                $signPassword,
×
210
                                $newUser->getDisplayName()
×
211
                        );
×
212
                        $this->pkcs12Handler->savePfx($newUser->getPrimaryEMailAddress(), $certificate);
×
213
                }
214
        }
215

216
        public function getCertificateEngineName(): string {
217
                return $this->certificateEngineFactory->getEngine()->getName();
×
218
        }
219

220
        /**
221
         * @return array[]
222
         */
223
        public function getConfig(?IUser $user = null): array {
224
                $info['identificationDocumentsFlow'] = $this->appConfig->getValueBool(Application::APP_ID, 'identification_documents', false);
×
225
                $info['hasSignatureFile'] = $this->hasSignatureFile($user);
×
226
                $info['phoneNumber'] = $this->getPhoneNumber($user);
×
227
                $info['isApprover'] = $this->validateHelper->userCanApproveValidationDocuments($user, false);
×
228
                $info['grid_view'] = $this->getUserConfigGridView($user);
×
229

230
                if ($user && $this->groupManager->isAdmin($user->getUID())) {
×
231
                        $info = array_filter(array_merge($info, [
×
232
                                'crl_filters' => $this->getUserConfigCrlFilters($user),
×
233
                                'crl_sort' => $this->getUserConfigCrlSort($user),
×
234
                        ]));
×
235
                }
236

237
                return $info;
×
238
        }
239

240

241

242
        private function updateIdentifyMethodToAccount(int $signRequestId, string $email, string $uid): void {
243
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequestId);
1✔
244
                foreach ($identifyMethods as $name => $methods) {
1✔
NEW
245
                        if ($name === IdentifyMethodService::IDENTIFY_EMAIL) {
×
NEW
246
                                foreach ($methods as $identifyMethod) {
×
NEW
247
                                        $entity = $identifyMethod->getEntity();
×
NEW
248
                                        if ($entity->getIdentifierValue() === $email) {
×
NEW
249
                                                $entity->setIdentifierKey(IdentifyMethodService::IDENTIFY_ACCOUNT);
×
NEW
250
                                                $entity->setIdentifierValue($uid);
×
NEW
251
                                                $this->identifyMethodMapper->update($entity);
×
252
                                        }
253
                                }
254
                        }
255
                }
256
        }
257

258
        private function getPhoneNumber(?IUser $user): string {
259
                if (!$user) {
×
260
                        return '';
×
261
                }
262
                $userAccount = $this->accountManager->getAccount($user);
×
263
                return $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue();
×
264
        }
265

266
        public function hasSignatureFile(?IUser $user = null): bool {
267
                if (!$user) {
4✔
268
                        return false;
×
269
                }
270
                try {
271
                        $this->pkcs12Handler->getPfxOfCurrentSigner($user->getUID());
4✔
272
                        return true;
×
273
                } catch (LibresignException) {
4✔
274
                        return false;
4✔
275
                }
276
        }
277

278
        private function getUserConfigGridView(?IUser $user = null): bool {
279
                if (!$user) {
×
280
                        return false;
×
281
                }
282

283
                return $this->config->getUserValue($user->getUID(), Application::APP_ID, 'grid_view', false) === '1';
×
284
        }
285

286
        private function getUserConfigCrlFilters(?IUser $user = null): array {
287
                if (!$user) {
×
288
                        return [];
×
289
                }
290

291
                $value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'crl_filters', '');
×
292
                if (empty($value)) {
×
293
                        return [];
×
294
                }
295

296
                $decoded = json_decode($value, true);
×
297
                return is_array($decoded) ? $decoded : [];
×
298
        }
299

300
        private function getUserConfigCrlSort(?IUser $user = null): array {
301
                if (!$user) {
×
302
                        return ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
×
303
                }
304

305
                $value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'crl_sort', '');
×
306
                if (empty($value)) {
×
307
                        return ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
×
308
                }
309

310
                $decoded = json_decode($value, true);
×
311
                return is_array($decoded) ? $decoded : ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
×
312
        }
313

314
        /**
315
         * Get PDF node by UUID
316
         *
317
         * @psalm-suppress MixedReturnStatement
318
         * @throws Throwable
319
         * @return \OCP\Files\File
320
         */
321
        public function getPdfByUuid(string $uuid): File {
322
                $fileData = $this->fileMapper->getByUuid($uuid);
2✔
323

324
                if (in_array($fileData->getStatus(), [FileEntity::STATUS_PARTIAL_SIGNED, FileEntity::STATUS_SIGNED])) {
2✔
325
                        $nodeId = $fileData->getSignedNodeId();
2✔
326
                } else {
327
                        $nodeId = $fileData->getNodeId();
×
328
                }
329
                $file = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
2✔
330
                if (!$file instanceof File) {
2✔
331
                        throw new DoesNotExistException('Not found');
×
332
                }
333
                return $file;
2✔
334
        }
335

336
        public function getFileByNodeId(int $nodeId): File {
337
                try {
338
                        return $this->folderService->getFileById($nodeId);
×
339
                } catch (NotFoundException) {
×
340
                        throw new DoesNotExistException('Not found');
×
341
                }
342
        }
343

344
        public function canRequestSign(?IUser $user = null): bool {
345
                if (!$user) {
8✔
346
                        return false;
1✔
347
                }
348
                $authorized = $this->appConfig->getValueArray(Application::APP_ID, 'groups_request_sign', ['admin']);
7✔
349
                if (empty($authorized)) {
7✔
350
                        return false;
1✔
351
                }
352
                $userGroups = $this->groupManager->getUserGroupIds($user);
6✔
353
                if (!array_intersect($userGroups, $authorized)) {
6✔
354
                        return false;
3✔
355
                }
356
                return true;
3✔
357
        }
358

359
        public function getSettings(?IUser $user = null): array {
360
                $return['canRequestSign'] = $this->canRequestSign($user);
4✔
361
                $return['hasSignatureFile'] = $this->hasSignatureFile($user);
4✔
362
                return $return;
4✔
363
        }
364

365
        public function addFilesToAccount(array $files, IUser $user): void {
366
                $this->validateAccountFiles($files, $user);
3✔
367
                foreach ($files as $fileData) {
2✔
368
                        $dataToSave = $fileData;
2✔
369
                        $dataToSave['userManager'] = $user;
2✔
370
                        $dataToSave['name'] = $fileData['name'] ?? $fileData['type'];
2✔
371
                        $file = $this->requestSignatureService->saveFile($dataToSave);
2✔
372

373
                        $this->accountFileService->addFile($file, $user, $fileData['type']);
2✔
374
                }
375
        }
376

377
        public function deleteFileFromAccount(int $nodeId, IUser $user): void {
378
                $this->validateHelper->validateAccountFileIsOwnedByUser($nodeId, $user->getUID());
×
379
                $accountFile = $this->accountFileMapper->getByUserIdAndNodeId($user->getUID(), $nodeId);
×
380
                $this->accountFileService->deleteFile($accountFile->getFileId(), $user->getUID());
×
381
        }
382

383
        public function saveVisibleElements(array $elements, string $sessionId, ?IUser $user): void {
384
                foreach ($elements as $element) {
×
385
                        $this->saveVisibleElement($element, $sessionId, $user);
×
386
                }
387
        }
388

389
        public function saveVisibleElement(array $data, string $sessionId, ?IUser $user): void {
390
                if (isset($data['elementId'])) {
×
391
                        $this->updateFileOfVisibleElement($data);
×
392
                        $this->updateDataOfVisibleElement($data);
×
393
                } elseif ($user instanceof IUser) {
×
394
                        $file = $this->saveFileOfVisibleElementUsingUser($data, $user);
×
395
                        $this->insertVisibleElement($data, $user, $file);
×
396
                } else {
397
                        $file = $this->saveFileOfVisibleElementUsingSession($data, $sessionId);
×
398
                }
399
        }
400

401
        private function updateFileOfVisibleElement(array $data): void {
402
                if (!isset($data['file'])) {
×
403
                        return;
×
404
                }
405
                $userElement = $this->userElementMapper->findOne(['id' => $data['elementId']]);
×
406
                $file = $this->folderService->getFileById($userElement->getFileId());
×
407
                $file->putContent($this->getFileRaw($data));
×
408
        }
409

410
        private function updateDataOfVisibleElement(array $data): void {
411
                if (!isset($data['starred'])) {
×
412
                        return;
×
413
                }
414
                $userElement = $this->userElementMapper->findOne(['id' => $data['elementId']]);
×
415
                $userElement->setStarred($data['starred'] ? 1 : 0);
×
416
                $this->userElementMapper->update($userElement);
×
417
        }
418

419
        private function saveFileOfVisibleElementUsingUser(array $data, IUser $user): File {
420
                $rootSignatureFolder = $this->folderService->getFolder();
×
421
                $folderName = $this->folderService->getFolderName($data, $user);
×
422
                $folderToFile = $rootSignatureFolder->newFolder($folderName);
×
423
                return $folderToFile->newFile(UUIDUtil::getUUID() . '.png', $this->getFileRaw($data));
×
424
        }
425

426
        private function saveFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
427
                if (!empty($data['nodeId'])) {
×
428
                        return $this->updateFileOfVisibleElementUsingSession($data, $sessionId);
×
429
                }
430
                return $this->createFileOfVisibleElementUsingSession($data, $sessionId);
×
431
        }
432

433
        private function updateFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
434
                $fileList = $this->signerElementsService->getElementsFromSession();
×
435
                $element = array_filter($fileList, fn (File $element) => $element->getId() === $data['nodeId']);
×
436
                $element = current($element);
×
437
                if (!$element instanceof File) {
×
438
                        throw new \Exception($this->l10n->t('File not found'));
×
439
                }
440
                $element->putContent($this->getFileRaw($data));
×
441
                return $element;
×
442
        }
443

444
        private function createFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
445
                $rootSignatureFolder = $this->folderService->getFolder();
×
446
                $folderName = $sessionId;
×
447
                $folderToFile = $rootSignatureFolder->newFolder($folderName);
×
448
                $filename = implode(
×
449
                        '_',
×
450
                        [
×
451
                                $data['type'],
×
452
                                $this->timeFactory->getDateTime()->getTimestamp(),
×
453
                        ]
×
454
                ) . '.png';
×
455
                return $folderToFile->newFile($filename, $this->getFileRaw($data));
×
456
        }
457

458
        private function insertVisibleElement(array $data, IUser $user, File $file): void {
459
                $userElement = new UserElement();
×
460
                $userElement->setType($data['type']);
×
461
                $userElement->setFileId($file->getId());
×
462
                $userElement->setUserId($user->getUID());
×
463
                $userElement->setStarred(isset($data['starred']) && $data['starred'] ? 1 : 0);
×
464
                $userElement->setCreatedAt($this->timeFactory->getDateTime());
×
465
                $this->userElementMapper->insert($userElement);
×
466
        }
467

468
        private function getFileRaw(array $data): string {
469
                if (!empty($data['file']['url'])) {
×
470
                        if (!filter_var($data['file']['url'], FILTER_VALIDATE_URL)) {
×
471
                                throw new \Exception($this->l10n->t('Invalid URL file'));
×
472
                        }
473
                        $response = $this->clientService->newClient()->get($data['file']['url']);
×
474
                        $contentType = $response->getHeader('Content-Type');
×
475
                        if ($contentType !== 'image/png') {
×
476
                                throw new \Exception($this->l10n->t('Visible element file must be png.'));
×
477
                        }
478
                        $content = (string)$response->getBody();
×
479
                        if (empty($content)) {
×
480
                                throw new \Exception($this->l10n->t('Empty file'));
×
481
                        }
482
                        $this->validateHelper->validateBase64($content, ValidateHelper::TYPE_VISIBLE_ELEMENT_USER);
×
483
                        return $content;
×
484
                }
485
                $this->validateHelper->validateBase64($data['file']['base64'], ValidateHelper::TYPE_VISIBLE_ELEMENT_USER);
×
486
                $withMime = explode(',', (string)$data['file']['base64']);
×
487
                if (count($withMime) === 2) {
×
488
                        $content = base64_decode($withMime[1]);
×
489
                } else {
490
                        $content = base64_decode((string)$data['file']['base64']);
×
491
                }
492
                if (!$content) {
×
493
                        return '';
×
494
                }
495
                return $content;
×
496
        }
497

498
        public function deleteSignatureElement(?IUser $user, string $sessionId, int $nodeId): void {
499
                if ($user instanceof IUser) {
×
500
                        $element = $this->userElementMapper->findOne([
×
501
                                'file_id' => $nodeId,
×
502
                                'user_id' => $user->getUID(),
×
503
                        ]);
×
504
                        $this->userElementMapper->delete($element);
×
505
                        try {
506
                                $file = $this->folderService->getFileById($element->getFileId());
×
507
                                $file->delete();
×
508
                        } catch (NotFoundException) {
×
509
                        }
510
                } else {
511
                        $rootSignatureFolder = $this->folderService->getFolder();
×
512
                        $folderName = $sessionId;
×
513
                        $rootSignatureFolder->delete($folderName);
×
514
                }
515
        }
516

517
        /**
518
         * @throws LibresignException at savePfx
519
         * @throws InvalidArgumentException
520
         */
521
        public function uploadPfx(array $file, IUser $user): void {
522
                if (
523
                        $file['error'] !== 0
×
524
                        || !is_uploaded_file($file['tmp_name'])
×
525
                        || Filesystem::isFileBlacklisted($file['tmp_name'])
×
526
                ) {
527
                        // TRANSLATORS Error when the uploaded certificate file is not valid
528
                        throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
×
529
                }
530
                if ($file['size'] > 10 * 1024) {
×
531
                        // TRANSLATORS Error when the certificate file is bigger than normal
532
                        throw new InvalidArgumentException($this->l10n->t('File is too big'));
×
533
                }
534
                $content = file_get_contents($file['tmp_name']);
×
535
                $mimetype = $this->mimeTypeDetector->detectString($content);
×
536
                if ($mimetype !== 'application/octet-stream') {
×
537
                        // TRANSLATORS Error when the mimetype of uploaded file is not valid
538
                        throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
×
539
                }
540
                $extension = strtolower(pathinfo((string)$file['name'], PATHINFO_EXTENSION));
×
541
                if ($extension !== 'pfx') {
×
542
                        // TRANSLATORS Error when the certificate file is not a pfx file
543
                        throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
×
544
                }
545
                unlink($file['tmp_name']);
×
546
                $this->pkcs12Handler->savePfx($user->getUID(), $content);
×
547
        }
548

549
        public function deletePfx(IUser $user): void {
550
                $this->pkcs12Handler->deletePfx($user->getUID());
×
551
        }
552

553
        /**
554
         * @throws LibresignException when have not a certificate file
555
         */
556
        public function updatePfxPassword(IUser $user, string $current, string $new): void {
557
                try {
558
                        $pfx = $this->pkcs12Handler->updatePassword($user->getUID(), $current, $new);
×
559
                } catch (InvalidPasswordException) {
×
560
                        throw new LibresignException($this->l10n->t('Invalid user or password'));
×
561
                }
562
        }
563

564
        /**
565
         * @throws LibresignException when have not a certificate file
566
         */
567
        public function readPfxData(IUser $user, string $password): array {
568
                try {
569
                        return $this->pkcs12Handler
×
570
                                ->setCertificate($this->pkcs12Handler->getPfxOfCurrentSigner($user->getUID()))
×
571
                                ->setPassword($password)
×
572
                                ->readCertificate();
×
573
                } catch (InvalidPasswordException) {
×
574
                        throw new LibresignException($this->l10n->t('Invalid user or password'));
×
575
                }
576
        }
577
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc