80 lines
2.1 KiB
PHP
80 lines
2.1 KiB
PHP
<?php
|
|
// CSRFPIdentity.php
|
|
// Created: 2021-06-11
|
|
// Updated: 2022-02-02
|
|
|
|
namespace Index\Security;
|
|
|
|
/**
|
|
* Represents a CSRF prevention identity.
|
|
*/
|
|
class CSRFPIdentity {
|
|
private CSRFP $owner;
|
|
private string $identity;
|
|
|
|
/**
|
|
* Construct a new instance of CSRFPIdentity.
|
|
*
|
|
* @param CSRFP $owner Owner CSRFP instance.
|
|
* @param string $identity Identity string.
|
|
* @return CSRFPIdentity Instance representing the identity.
|
|
*/
|
|
public function __construct(CSRFP $owner, string $identity) {
|
|
$this->owner = $owner;
|
|
$this->identity = $identity;
|
|
}
|
|
|
|
/**
|
|
* Gets a reference to the owner CSRFP object.
|
|
*
|
|
* @return CSRFP Owner object.
|
|
*/
|
|
public function getOwner(): CSRFP {
|
|
return $this->owner;
|
|
}
|
|
|
|
/**
|
|
* Gets the string for this identity.
|
|
*/
|
|
public function getIdentity(): string {
|
|
return $this->identity;
|
|
}
|
|
|
|
/**
|
|
* Creates a new token using this identity.
|
|
*
|
|
* @return CSRFPToken Newly created token.
|
|
*/
|
|
public function createToken(): CSRFPToken {
|
|
$timestamp = $this->owner->time();
|
|
$tolerance = $this->owner->getTolerance();
|
|
$hash = $this->owner->createHash($this->identity, $timestamp, $tolerance);
|
|
return new CSRFPToken($timestamp, $tolerance, $hash);
|
|
}
|
|
|
|
/**
|
|
* Verifies a token using this identity.
|
|
*
|
|
* @param CSRFPToken $token Token to verify.
|
|
* @return bool true if the token is valid, false if not.
|
|
*/
|
|
public function verifyToken(CSRFPToken $token): bool {
|
|
$timestamp = $token->getTimestamp();
|
|
$tolerance = $token->getTolerance();
|
|
$tHash = $token->getHash();
|
|
|
|
// invalid for sure, defaults for decode failure
|
|
if($timestamp < 0 || $tolerance < 1 || empty($tHash))
|
|
return false;
|
|
|
|
$currentTime = $this->owner->time();
|
|
if($currentTime < $timestamp
|
|
|| $currentTime > ($timestamp + $tolerance))
|
|
return false;
|
|
|
|
$rHash = $this->owner->createHash($this->identity, $timestamp, $tolerance);
|
|
|
|
return hash_equals($rHash, $tHash);
|
|
}
|
|
}
|