49 lines
1.4 KiB
PHP
49 lines
1.4 KiB
PHP
|
<?php
|
||
|
namespace Misuzu\Auth;
|
||
|
|
||
|
use Index\XString;
|
||
|
use Index\Data\DbStatementCache;
|
||
|
use Index\Data\IDbConnection;
|
||
|
use Misuzu\Users\User;
|
||
|
|
||
|
class TwoFactorAuthSessions {
|
||
|
private DbStatementCache $cache;
|
||
|
|
||
|
public function __construct(IDbConnection $dbConn) {
|
||
|
$this->cache = new DbStatementCache($dbConn);
|
||
|
}
|
||
|
|
||
|
private static function generateToken(): string {
|
||
|
return XString::random(32);
|
||
|
}
|
||
|
|
||
|
public function createToken(User|string $userInfo): string {
|
||
|
if($userInfo instanceof User)
|
||
|
$userInfo = (string)$userInfo->getId();
|
||
|
|
||
|
$token = self::generateToken();
|
||
|
|
||
|
$stmt = $this->cache->get('INSERT INTO msz_auth_tfa (user_id, tfa_token) VALUES (?, ?)');
|
||
|
$stmt->addParameter(1, $userInfo);
|
||
|
$stmt->addParameter(2, $token);
|
||
|
$stmt->execute();
|
||
|
|
||
|
return $token;
|
||
|
}
|
||
|
|
||
|
public function getTokenUserId(string $token): string {
|
||
|
$stmt = $this->cache->get('SELECT user_id FROM msz_auth_tfa WHERE tfa_token = ? AND tfa_created > NOW() - INTERVAL 15 MINUTE');
|
||
|
$stmt->addParameter(1, $token);
|
||
|
$stmt->execute();
|
||
|
$result = $stmt->getResult();
|
||
|
|
||
|
return $result->next() ? $result->getString(0) : '';
|
||
|
}
|
||
|
|
||
|
public function deleteToken(string $token): void {
|
||
|
$stmt = $this->cache->get('DELETE FROM msz_auth_tfa WHERE tfa_token = ?');
|
||
|
$stmt->addParameter(1, $token);
|
||
|
$stmt->execute();
|
||
|
}
|
||
|
}
|