forked from flashii/eeprom
67 lines
1.9 KiB
PHP
67 lines
1.9 KiB
PHP
<?php
|
|
namespace EEPROM\Auth;
|
|
|
|
use EEPROM\Base64;
|
|
use EEPROM\Config;
|
|
use EEPROM\DB;
|
|
use PDO;
|
|
use PDOException;
|
|
|
|
class MisuzuAuth implements AuthInterface {
|
|
private static $database = null;
|
|
|
|
public function getDatabase(): PDO {
|
|
if(self::$database !== null)
|
|
return self::$database;
|
|
|
|
$configPath = Config::get('Misuzu', 'config', '');
|
|
|
|
if(!is_file($configPath))
|
|
throw new \Exception('Cannot find Misuzu configuration.');
|
|
|
|
$config = parse_ini_file($configPath, true)['Database'];
|
|
$dsn = ($config['driver'] ?? 'mysql') . ':';
|
|
|
|
foreach($config as $key => $value) {
|
|
if($key === 'driver' || $key === 'username' || $key === 'password')
|
|
continue;
|
|
if($key === 'database')
|
|
$key = 'dbname';
|
|
|
|
$dsn .= $key . '=' . $value . ';';
|
|
}
|
|
|
|
try {
|
|
self::$database = new PDO($dsn, $config['username'], $config['password'], DB::FLAGS);
|
|
} catch(PDOException $ex) {
|
|
throw new \Exception('Unable to connect to Misuzu database.');
|
|
}
|
|
|
|
return self::$database;
|
|
}
|
|
|
|
public function getName(): string { return 'Misuzu'; }
|
|
|
|
public function verifyToken(string $token): int {
|
|
$packed = Base64::decode($token, true);
|
|
$packed = str_pad($packed, 37, "\x00");
|
|
$unpacked = unpack('Cversion/Nuser/H64token', $packed);
|
|
|
|
if($unpacked['version'] !== 1)
|
|
return -1;
|
|
|
|
$getUserId = $this->getDatabase()->prepare('
|
|
SELECT `user_id`
|
|
FROM `msz_sessions`
|
|
WHERE `user_id` = :user
|
|
AND `session_key` = :token
|
|
AND `session_expires` > NOW()
|
|
');
|
|
$getUserId->bindValue('user', $unpacked['user']);
|
|
$getUserId->bindValue('token', $unpacked['token']);
|
|
$getUserId->execute();
|
|
|
|
return (int)$getUserId->fetchColumn();
|
|
}
|
|
}
|