| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
namespace JFB_Modules\Webhook\Db\Models; |
| 5 |
|
| 6 |
// If this file is called directly, abort. |
| 7 |
if ( ! defined( 'WPINC' ) ) { |
| 8 |
die; |
| 9 |
} |
| 10 |
|
| 11 |
use Jet_Form_Builder\Db_Queries\Base_Db_Model; |
| 12 |
use Jet_Form_Builder\Db_Queries\Exceptions\Sql_Exception; |
| 13 |
use Jet_Form_Builder\Exceptions\Action_Exception; |
| 14 |
use JFB_Modules\Security; |
| 15 |
|
| 16 |
class Tokens_Model extends Base_Db_Model { |
| 17 |
|
| 18 |
protected $gmt = 1; |
| 19 |
|
| 20 |
public static function table_name(): string { |
| 21 |
return 'tokens'; |
| 22 |
} |
| 23 |
|
| 24 |
public static function schema(): array { |
| 25 |
return array( |
| 26 |
'id' => 'bigint(20) NOT NULL AUTO_INCREMENT', |
| 27 |
// slug of action (it has nothing to do with the actions used in the form.) |
| 28 |
'action' => 'varchar(100)', |
| 29 |
'hash' => 'text', |
| 30 |
// How many times was performed |
| 31 |
'exec_count' => 'int(11) NOT NULL DEFAULT 0', |
| 32 |
// How many times can be done |
| 33 |
'limit_exec' => 'int(11) NOT NULL DEFAULT 1', |
| 34 |
'expire_at' => 'TIMESTAMP NULL', |
| 35 |
self::CREATED_AT => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP', |
| 36 |
self::UPDATED_AT => 'TIMESTAMP', |
| 37 |
); |
| 38 |
} |
| 39 |
|
| 40 |
public static function schema_keys(): array { |
| 41 |
return array( |
| 42 |
'id' => 'primary key', |
| 43 |
'expire_at' => 'index', |
| 44 |
); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Prevent check capability to delete rows |
| 49 |
*/ |
| 50 |
public function before_delete() { |
| 51 |
// silence is golden |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* @param string $action |
| 56 |
* @param int|string $lifespan |
| 57 |
* |
| 58 |
* @return array<int, string> |
| 59 |
* @throws Sql_Exception |
| 60 |
*/ |
| 61 |
public static function create_token( string $action, $lifespan = 0 ): array { |
| 62 |
$timezone = new \DateTimeZone( 'UTC' ); |
| 63 |
|
| 64 |
try { |
| 65 |
$current = new \DateTimeImmutable( 'now', $timezone ); |
| 66 |
} catch ( \Exception $exception ) { |
| 67 |
return array( 0, '' ); |
| 68 |
} |
| 69 |
|
| 70 |
$lifespan_min = $lifespan && is_numeric( $lifespan ) |
| 71 |
? absint( $lifespan * 60 ) // return number of minutes |
| 72 |
: 0; // always be available |
| 73 |
|
| 74 |
$token = Security\Csrf\Csrf_Tools::generate(); |
| 75 |
|
| 76 |
$row = array( |
| 77 |
'action' => $action, |
| 78 |
'hash' => Security\Module::get_hasher()->HashPassword( $token ), |
| 79 |
); |
| 80 |
|
| 81 |
if ( $lifespan_min ) { |
| 82 |
$row['expire_at'] = $current->modify( |
| 83 |
sprintf( '+%d min', $lifespan_min ) |
| 84 |
)->format( |
| 85 |
Base_Db_Model::DATETIME_FORMAT |
| 86 |
); |
| 87 |
} |
| 88 |
|
| 89 |
$id = ( new static() )->insert( $row ); |
| 90 |
|
| 91 |
return array( $id, $token ); |
| 92 |
} |
| 93 |
} |
| 94 |
|