Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
TokenService
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
3 / 3
4
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sendCodeByGateway
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 sendCodeByEmail
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4/**
5 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6 * SPDX-License-Identifier: AGPL-3.0-or-later
7 */
8
9namespace OCA\Libresign\Service\IdentifyMethod\SignatureMethod;
10
11use OCA\Libresign\Service\MailService;
12use OCA\Libresign\Service\TwofactorGatewayService;
13use OCP\AppFramework\OCS\OCSForbiddenException;
14use OCP\IL10N;
15use OCP\Security\IHasher;
16use OCP\Security\ISecureRandom;
17
18class TokenService {
19    public const TOKEN_LENGTH = 6;
20
21    public function __construct(
22        private ISecureRandom $secureRandom,
23        private IHasher $hasher,
24        private MailService $mail,
25        private IL10N $l10n,
26        private TwofactorGatewayService $twofactorGatewayService,
27    ) {
28    }
29
30    public function sendCodeByGateway(string $identifier, string $gatewayName): string {
31        $this->twofactorGatewayService->ensureAvailable($gatewayName);
32        if (!$this->twofactorGatewayService->isGatewayComplete($gatewayName)) {
33            // TRANSLATORS Error shown to the administrator when a two-factor gateway needed to send signing codes is not configured. %s is the gateway name.
34            throw new OCSForbiddenException($this->l10n->t('Gateway %s not configured on Two-Factor Gateway.', $gatewayName));
35        }
36
37        $code = $this->secureRandom->generate(self::TOKEN_LENGTH, ISecureRandom::CHAR_DIGITS);
38        $this->twofactorGatewayService->send(
39            $gatewayName,
40            $identifier,
41            // TRANSLATORS Text of the verification code message sent to the signer. %s is the one-time code.
42            $this->l10n->t('%s is your LibreSign verification code.', $code)
43        );
44        return $this->hasher->hash($code);
45    }
46
47    public function sendCodeByEmail(string $email, string $displayName): string {
48        $code = $this->secureRandom->generate(self::TOKEN_LENGTH, ISecureRandom::CHAR_DIGITS);
49        $this->mail->sendCodeToSign(
50            email: $email,
51            name: $displayName,
52            code: $code
53        );
54        return $this->hasher->hash($code);
55    }
56}