Elgg  Version 5.1
HmacFactory.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Security;
4 
6 
10 class HmacFactory {
11 
12  use TimeUsing;
13 
17  protected $site_secret;
18 
22  protected $crypto;
23 
30  public function __construct(SiteSecret $secret, Crypto $crypto) {
31  $this->site_secret = $secret;
32  $this->crypto = $crypto;
33  }
34 
44  public function getHmac($data, $algo = 'sha256', $key = '') {
45  if (!$key) {
46  $key = $this->site_secret->get(true);
47  }
48 
49  return new Hmac($key, [$this->crypto, 'areEqual'], $data, $algo);
50  }
51 
61  public function generateInviteCode(string $username): string {
62  $time = $this->getCurrentTime()->getTimestamp();
63  $token = $this->getHmac([$time, $username])->getToken();
64 
65  return "{$time}.{$token}";
66  }
67 
78  public function validateInviteCode(string $username, string $code): bool {
79  // validate the format of the token created by self::generateInviteCode()
80  $matches = [];
81  if (!preg_match('~^(\d+)\.([a-zA-Z0-9\-_]+)$~', $code, $matches)) {
82  return false;
83  }
84 
85  $time = (int) $matches[1];
86  $mac = $matches[2];
87 
88  return $this->getHmac([$time, $username])->matchesToken($mac);
89  }
90 }
Manages a site-specific secret key, encoded as a 32 byte string "secret".
Definition: SiteSecret.php:24
Cryptographic services.
Definition: Crypto.php:12
generateInviteCode(string $username)
Generates a unique invite code for a user.
Definition: HmacFactory.php:61
if(!$annotation instanceof ElggAnnotation) $time
Definition: time.php:20
$username
Definition: delete.php:23
trait TimeUsing
Adds methods for setting the current time (for testing)
Definition: TimeUsing.php:10
validateInviteCode(string $username, string $code)
Validate a user&#39;s invite code.
Definition: HmacFactory.php:78
getCurrentTime($modifier= '')
Get the (cloned) time.
Definition: TimeUsing.php:25
if(!$entity instanceof\ElggUser) $data
Definition: attributes.php:13
getHmac($data, $algo= 'sha256', $key= '')
Get an HMAC token builder/validator object.
Definition: HmacFactory.php:44
Component for creating HMAC tokens.
Definition: Hmac.php:10
$token
if($container instanceof ElggGroup &&$container->guid!=elgg_get_page_owner_guid()) $key
Definition: summary.php:44
__construct(SiteSecret $secret, Crypto $crypto)
Constructor.
Definition: HmacFactory.php:30
Provides a factory for HMAC objects.
Definition: HmacFactory.php:10