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

avoutic / web-framework / 45418632783

24 Nov 2026 02:47PM UTC coverage: 69.305% (-4.3%) from 73.637%
45418632783

push

github

avoutic
Mark the config_values table as deprecated

2872 of 4144 relevant lines covered (69.31%)

2.89 hits per line

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

89.69
/src/Security/UserCodeService.php
1
<?php
2

3
/*
4
 * This file is part of WebFramework.
5
 *
6
 * (c) Avoutic <avoutic@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
namespace WebFramework\Security;
13

14
use Carbon\Carbon;
15
use Psr\Log\LoggerInterface;
16
use WebFramework\Entity\User;
17
use WebFramework\Entity\VerificationCode;
18
use WebFramework\Exception\CodeVerificationException;
19
use WebFramework\Exception\InvalidCodeException;
20
use WebFramework\Repository\UserRepository;
21
use WebFramework\Repository\VerificationCodeRepository;
22

23
/**
24
 * Handles generation and verification of user-specific codes.
25
 */
26
class UserCodeService
27
{
28
    /**
29
     * UserCodeService constructor.
30
     *
31
     * @param LoggerInterface            $logger                     The logger service
32
     * @param RandomProvider             $randomProvider             The random provider service
33
     * @param UserRepository             $userRepository             The user repository
34
     * @param VerificationCodeRepository $verificationCodeRepository The verification code repository
35
     * @param int                        $codeLength                 The length of verification codes
36
     * @param int                        $codeExpiryMinutes          The number of minutes until codes expire
37
     * @param int                        $maxAttempts                The maximum number of verification attempts
38
     */
39
    public function __construct(
×
40
        private LoggerInterface $logger,
41
        private RandomProvider $randomProvider,
42
        private UserRepository $userRepository,
43
        private VerificationCodeRepository $verificationCodeRepository,
44
        private int $codeLength,
45
        private int $codeExpiryMinutes,
46
        private int $maxAttempts,
47
    ) {}
×
48

49
    /**
50
     * Generate a verification code.
51
     */
52
    public function generateVerificationCode(): string
×
53
    {
54
        $alphabet = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
×
55
        $alphabetLength = strlen($alphabet);
×
56
        $randomBytes = $this->randomProvider->getRandom($this->codeLength);
×
57
        $code = '';
×
58

59
        for ($i = 0; $i < $this->codeLength; $i++)
×
60
        {
61
            $code .= $alphabet[ord($randomBytes[$i]) % $alphabetLength];
×
62
        }
63

64
        return $code;
×
65
    }
66

67
    /**
68
     * Get the action associated with a verification code.
69
     *
70
     * @param string $guid The GUID of the verification code
71
     *
72
     * @return null|string The action associated with the verification code, or null if not found
73
     */
74
    public function getActionByGuid(string $guid): ?string
2 ✔
75
    {
76
        $verificationCode = $this->verificationCodeRepository->getByGuid($guid);
2 ✔
77
        if ($verificationCode === null)
2 ✔
78
        {
79
            return null;
1 ✔
80
        }
81

82
        return $verificationCode->getAction();
1 ✔
83
    }
84

85
    /**
86
     * Get a verification code that is ready to be redeemed for an action, without consuming it.
87
     *
88
     * Redeemable means: the code exists, was entered correctly, has not expired, has not
89
     * been invalidated or processed, and belongs to the given action. The code is not
90
     * marked as processed. That is up to the caller, once it has acted on the code.
91
     *
92
     * @param string $guid   The GUID of the verification code
93
     * @param string $action The action the code must belong to
94
     *
95
     * @return VerificationCode The redeemable verification code
96
     *
97
     * @throws CodeVerificationException If the code is not redeemable for the action
98
     */
99
    public function getRedeemableCode(string $guid, string $action): VerificationCode
7 ✔
100
    {
101
        $verificationCode = $this->verificationCodeRepository->getByGuid($guid);
7 ✔
102

103
        if ($verificationCode === null)
7 ✔
104
        {
105
            throw new CodeVerificationException();
1 ✔
106
        }
107

108
        // Verify the code was actually verified (marked as correct) and hasn't expired
109
        if (!$verificationCode->isCorrect())
6 ✔
110
        {
111
            $this->logger->debug('Verification code not yet correct', ['guid' => $guid]);
1 ✔
112

113
            throw new CodeVerificationException();
1 ✔
114
        }
115

116
        if ($verificationCode->isExpired())
5 ✔
117
        {
118
            $this->logger->debug('Verification code expired', ['guid' => $guid]);
1 ✔
119

120
            throw new CodeVerificationException();
1 ✔
121
        }
122

123
        // Prevent replay attacks - check if code has already been invalidated or processed
124
        if ($verificationCode->isInvalidated() || $verificationCode->isProcessed())
4 ✔
125
        {
126
            $this->logger->warning('Verification code already invalidated or processed (replay attempt)', ['guid' => $guid]);
2 ✔
127

128
            throw new CodeVerificationException();
2 ✔
129
        }
130

131
        if ($verificationCode->getAction() !== $action)
2 ✔
132
        {
133
            $this->logger->error('Invalid action for verification code', [
1 ✔
134
                'guid' => $guid,
1 ✔
135
                'action' => $verificationCode->getAction(),
1 ✔
136
            ]);
1 ✔
137

138
            throw new CodeVerificationException();
1 ✔
139
        }
140

141
        return $verificationCode;
1 ✔
142
    }
143

144
    /**
145
     * Generate a verification code entry in the database.
146
     *
147
     * @param User         $user     The user to generate the code for
148
     * @param string       $action   The action associated with the code
149
     * @param array<mixed> $flowData Additional flow-specific data to store
150
     *
151
     * @return array{guid: string, code: string} The GUID and the plain code
152
     */
153
    public function generateVerificationCodeEntry(User $user, string $action, array $flowData = []): array
1 ✔
154
    {
155
        $code = $this->generateVerificationCode();
1 ✔
156
        $expiresAt = Carbon::now()->addMinutes($this->codeExpiryMinutes)->getTimestamp();
1 ✔
157

158
        $verificationCode = $this->verificationCodeRepository->create([
1 ✔
159
            'user_id' => $user->getId(),
1 ✔
160
            'code' => $code,
1 ✔
161
            'action' => $action,
1 ✔
162
            'max_attempts' => $this->maxAttempts,
1 ✔
163
            'expires_at' => $expiresAt,
1 ✔
164
            'flow_data' => json_encode($flowData),
1 ✔
165
        ]);
1 ✔
166

167
        $this->logger->debug('Generated verification code entry', [
1 ✔
168
            'guid' => $verificationCode->getGuid(),
1 ✔
169
            'user_id' => $user->getId(),
1 ✔
170
            'action' => $action,
1 ✔
171
        ]);
1 ✔
172

173
        return ['guid' => $verificationCode->getGuid(), 'code' => $code];
1 ✔
174
    }
175

176
    /**
177
     * Verify a code by GUID.
178
     *
179
     * @param string $guid   The GUID of the verification code entry
180
     * @param string $action The expected action
181
     * @param string $code   The code to verify
182
     *
183
     * @return array{user: User, flow_data: array<mixed>} The user and flow data
184
     *
185
     * @throws InvalidCodeException      If the code is invalid or max attempts exceeded
186
     * @throws CodeVerificationException If the verification code entry is invalid or expired
187
     */
188
    public function verifyCodeByGuid(string $guid, string $action, string $code): array
6 ✔
189
    {
190
        $this->logger->debug('Handling code verification by GUID', ['guid' => $guid, 'action' => $action]);
6 ✔
191

192
        $verificationCode = $this->verificationCodeRepository->getActiveByGuid($guid);
6 ✔
193

194
        if ($verificationCode === null)
6 ✔
195
        {
196
            $this->logger->debug('Verification code not found or inactive', ['guid' => $guid]);
1 ✔
197

198
            throw new CodeVerificationException();
1 ✔
199
        }
200

201
        if ($verificationCode->getAction() !== $action)
5 ✔
202
        {
203
            $this->logger->error('Invalid action for verification code', [
1 ✔
204
                'guid' => $guid,
1 ✔
205
                'expected_action' => $action,
1 ✔
206
                'actual_action' => $verificationCode->getAction(),
1 ✔
207
            ]);
1 ✔
208

209
            throw new CodeVerificationException();
1 ✔
210
        }
211

212
        // Increment attempts before checking code
213
        $verificationCode->incrementAttempts();
4 ✔
214
        $this->verificationCodeRepository->save($verificationCode);
4 ✔
215

216
        // Check if max attempts exceeded
217
        if (!$verificationCode->hasAttemptsRemaining())
4 ✔
218
        {
219
            $this->logger->warning('Max attempts exceeded for verification code', [
1 ✔
220
                'guid' => $guid,
1 ✔
221
                'attempts' => $verificationCode->getAttempts(),
1 ✔
222
            ]);
1 ✔
223

224
            throw new InvalidCodeException();
1 ✔
225
        }
226

227
        // Verify the code
228
        if ($verificationCode->getCode() !== $code)
3 ✔
229
        {
230
            $this->logger->debug('Invalid code provided', [
1 ✔
231
                'guid' => $guid,
1 ✔
232
                'attempts' => $verificationCode->getAttempts(),
1 ✔
233
            ]);
1 ✔
234

235
            throw new InvalidCodeException();
1 ✔
236
        }
237

238
        // Code is valid - mark as correct
239
        $verificationCode->markAsCorrect();
2 ✔
240
        $this->verificationCodeRepository->save($verificationCode);
2 ✔
241

242
        $user = $this->userRepository->find($verificationCode->getUserId());
2 ✔
243
        if ($user === null)
2 ✔
244
        {
245
            $this->logger->error('User not found for verification code', [
1 ✔
246
                'guid' => $guid,
1 ✔
247
                'user_id' => $verificationCode->getUserId(),
1 ✔
248
            ]);
1 ✔
249

250
            throw new CodeVerificationException();
1 ✔
251
        }
252

253
        $this->logger->info('Verification code verified successfully', [
1 ✔
254
            'guid' => $guid,
1 ✔
255
            'user_id' => $user->getId(),
1 ✔
256
            'action' => $action,
1 ✔
257
        ]);
1 ✔
258

259
        return [
1 ✔
260
            'user' => $user,
1 ✔
261
            'flow_data' => $verificationCode->getFlowData(),
1 ✔
262
        ];
1 ✔
263
    }
264
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc