-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOAuth2OTP.php
More file actions
503 lines (436 loc) · 12.1 KB
/
OAuth2OTP.php
File metadata and controls
503 lines (436 loc) · 12.1 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
<?php namespace Models\OAuth2;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\libs\Utils\PunnyCodeHelper;
use App\Models\Utils\BaseEntity;
use Doctrine\ORM\Mapping AS ORM;
use DateTime;
use DateInterval;
use DateTimeZone;
use Illuminate\Support\Facades\Log;
use models\exceptions\ValidationException;
use OAuth2\OAuth2Protocol;
use OAuth2\Requests\OAuth2AccessTokenRequestPasswordless;
use Utils\IPHelper;
use Utils\Model\Identifier;
use Laminas\Math\Rand;
/**
* @ORM\Entity(repositoryClass="App\Repositories\DoctrineOAuth2OTPRepository")
* @ORM\Table(name="oauth2_otp")
* Class OTP
* @package Models\OAuth2
*/
class OAuth2OTP extends BaseEntity implements Identifier
{
/**
* @ORM\Column(name="value", type="string")
* @var string
*/
private $value;
/**
* @ORM\Column(name="length", type="integer")
* @var int
*/
private $length;
/**
* @ORM\Column(name="`connection`", type="string")
* @var string
*/
private $connection;
/**
* @ORM\Column(name="send", type="string")
* @var string
*/
private $send;
/**
* @ORM\Column(name="scope", type="string")
* @var string
*/
private $scope;
/**
* @ORM\Column(name="email", type="string")
* @var string
*/
private $email;
/**
* @ORM\Column(name="phone_number", type="string")
* @var string
*/
private $phone_number;
/**
* @ORM\Column(name="nonce", type="string")
* @var string
*/
private $nonce;
/**
* @ORM\Column(name="lifetime", type="integer")
* @var int
*/
private $lifetime;
/**
* @ORM\Column(name="redirect_url", type="string")
* @var string
*/
private $redirect_url;
/**
* @var \DateTime
* @ORM\Column(name="redeemed_at", type="datetime")
*/
private $redeemed_at;
/**
* @var string
* @ORM\Column(name="redeemed_from_ip", type="string")
*/
private $redeemed_from_ip;
/**
* @ORM\Column(name="redeemed_attempts", type="integer")
* @var int
*/
private $redeemed_attempts;
/**
* @ORM\ManyToOne(targetEntity="Models\OAuth2\Client", inversedBy="otp_grants", cascade={"persist"})
* @ORM\JoinColumn(name="oauth2_client_id", referencedColumnName="id", nullable=true)
* @var Client
*/
private $client;
/**
* OAuth2OTP constructor.
* @param int $length
* @param int $lifetime
*/
public function __construct(int $length, int $lifetime = 0 )
{
parent::__construct();
$this->length = $length;
$this->lifetime = $lifetime;
$this->redeemed_at = null;
$this->redeemed_attempts = 0;
}
/**
* @return string
*/
public function getValue(): string
{
return $this->value;
}
/**
* @return string
*/
public function getConnection(): string
{
return $this->connection;
}
/**
* @param string $connection
*/
public function setConnection(string $connection): void
{
$this->connection = $connection;
}
/**
* @return string
*/
public function getSend(): string
{
return $this->send;
}
/**
* @param string $send
*/
public function setSend(string $send): void
{
$this->send = $send;
}
/**
* @return string
*/
public function getScope(): ?string
{
return $this->scope;
}
/**
* @param string $scope
*/
public function setScope(?string $scope): void
{
$this->scope = !empty($scope) ? trim($scope):null;
}
/**
* @return string
*/
public function getEmail(): ?string
{
return PunnyCodeHelper::decodeEmail($this->email);
}
/**
* @param string $email
*/
public function setEmail(?string $email): void
{
$this->email = PunnyCodeHelper::encodeEmail($email);
}
/**
* @return string
*/
public function getPhoneNumber(): ?string
{
return $this->phone_number;
}
/**
* @param string $phone_number
*/
public function setPhoneNumber(?string $phone_number): void
{
$this->phone_number = !empty($phone_number) ? trim($phone_number):null;
}
/**
* @return string
*/
public function getNonce(): ?string
{
return $this->nonce;
}
/**
* @param string $nonce
*/
public function setNonce(?string $nonce): void
{
$this->nonce = !empty($nonce) ? trim($nonce): null;
}
/**
* @return string
*/
public function getRedirectUrl(): ?string
{
return $this->redirect_url;
}
/**
* @param string $redirect_url
*/
public function setRedirectUrl(?string $redirect_url): void
{
$this->redirect_url = !empty($redirect_url) ? trim($redirect_url) :null;
}
/**
* @return \DateTime|null
*/
public function getRedeemedAt(): ?\DateTime
{
return $this->redeemed_at;
}
public function isRedeemed():bool{
// inline OTP are always alive
if ($this->connection === OAuth2Protocol::OAuth2PasswordlessConnectionInline) {
return false;
}
return !is_null($this->redeemed_at);
}
/**
* @throws ValidationException
*/
public function redeem(): void
{
// inline OTP are always alive
if ($this->connection === OAuth2Protocol::OAuth2PasswordlessConnectionInline) {
return;
}
if (!is_null($this->redeemed_at))
throw new ValidationException("OTP is already redeemed.");
$this->redeemed_at = new \DateTime('now', new \DateTimeZone('UTC'));
$this->redeemed_from_ip = IPHelper::getUserIp();
Log::debug(sprintf("OAuth2OTP::redeem from ip %s", $this->redeemed_from_ip));
}
/**
* @return Client
*/
public function getClient(): Client
{
return $this->client;
}
public function hasClient():bool{
return !is_null($this->client);
}
/**
* @param Client $client
*/
public function setClient(Client $client): void
{
$this->client = $client;
}
/**
* @return int
*/
public function getLifetime(): int
{
return $this->lifetime;
}
/**
* @param int $lifetime
*/
public function setLifetime(int $lifetime): void
{
$this->lifetime = $lifetime;
}
public function getRemainingLifetime()
{
//check is refresh token is stills alive... (ZERO is infinite lifetime)
if (intval($this->lifetime) == 0) {
return 0;
}
$created_at = clone $this->created_at;
$created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S'));
$now = new DateTime(gmdate("Y-m-d H:i:s", time()), new DateTimeZone("UTC"));
//check validity...
if ($now > $created_at) {
return -1;
}
$seconds = abs($created_at->getTimestamp() - $now->getTimestamp());;
return $seconds;
}
public function isAlive():bool
{
// inline OTP are always alive
if ($this->connection === OAuth2Protocol::OAuth2PasswordlessConnectionInline) {
return true;
}
return $this->getRemainingLifetime() >= 0;
}
public function clearClient():void{
$this->client = null;
}
/**
* @return int
*/
public function getLength(): int
{
return $this->length;
}
const MaxRedeemAttempts = 3;
public function logRedeemAttempt():void
{
if ($this->connection === OAuth2Protocol::OAuth2PasswordlessConnectionInline) {
Log::debug(sprintf("OAuth2OTP::logRedeemAttempt trying to mark redeem attempt for %s and inline connection", $this->value));
return;
}
Log::debug(sprintf("OAuth2OTP::logRedeemAttempt trying to mark redeem attempt for %s ", $this->value));
if ($this->redeemed_attempts < self::MaxRedeemAttempts) {
$this->redeemed_attempts = $this->redeemed_attempts + 1;
Log::debug(sprintf("OAuth2OTP::logRedeemAttempt redeemed_attempts %s", $this->redeemed_attempts));
}
}
public function isValid():bool
{
// inline OTP are always valid
if ($this->connection === OAuth2Protocol::OAuth2PasswordlessConnectionInline) {
return true;
}
return ($this->redeemed_attempts < self::MaxRedeemAttempts) && $this->isAlive();
}
public function getUserName():?string
{
return $this->connection == OAuth2Protocol::OAuth2PasswordlessEmail
|| $this->connection == OAuth2Protocol::OAuth2PasswordlessConnectionInline
? $this->getEmail() : $this->phone_number;
}
/**
* @param string $scope
* @return bool
*/
public function allowScope(string $scope):bool{
$s1 = explode(" ", $scope);
$s2 = explode(" ", $this->scope);
return count(array_diff($s1, $s2)) == 0;
}
public function setValue(string $value)
{
$this->value = strtoupper($value);
}
public function getType(): string
{
return "otp";
}
const VsChar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public function generateValue(): string
{
// calculate value
// entropy(SHANNON FANO Approx) len * log(count(VsChar))/log(2) = bits of entropy
$this->value = Rand::getString($this->length, self::VsChar);
return $this->value;
}
/**
* @param OAuth2AccessTokenRequestPasswordless $request
* @param int $length
* @return OAuth2OTP
*/
public static function fromRequest(OAuth2AccessTokenRequestPasswordless $request, int $length):OAuth2OTP{
$instance = new self($length);
$instance->connection = $request->getConnection();
$instance->setEmail($request->getEmail());
$instance->phone_number = $request->getPhoneNumber();
$instance->scope = $request->getScopes();
$instance->setValue($request->getOTP());
$instance->redirect_url = $request->getRedirectUrl();
return $instance;
}
/**
* @param string $user_name
* @param string $connection
* @param string|null $value
* @param string|null $scopes
* @return OAuth2OTP|null
*/
public static function fromParams(string $user_name, string $connection, ?string $value, string $scopes = null): ?OAuth2OTP
{
$instance = new self(strlen($value));
$instance->connection = $connection;
if ($connection == OAuth2Protocol::OAuth2PasswordlessConnectionEmail || $connection === OAuth2Protocol::OAuth2PasswordlessConnectionInline)
$instance->setEmail($user_name);
if ($connection == OAuth2Protocol::OAuth2PasswordlessConnectionSMS)
$instance->phone_number = $user_name;
$instance->setValue($value);
if (!empty($scopes))
$instance->setScope($scopes);
return $instance;
}
// non db fields
private $auth_time;
private $user_id;
/**
* @param int $auth_time
*/
public function setAuthTime(int $auth_time): void
{
$this->auth_time = $auth_time;
}
/**
* @param mixed $user_id
*/
public function setUserId($user_id): void
{
$this->user_id = $user_id;
}
/**
* @return mixed
*/
public function getAuthTime()
{
return $this->auth_time;
}
/**
* @return mixed
*/
public function getUserId()
{
return $this->user_id;
}
}