$userName, 'password' => $password]); foreach ($rows as $row) { if (fnmatch($row['remote'], $remoteAddress)) { return new User($row['id'], $row['username']); } } return null; } public function __construct(int $id, string $userName, ?string $auth = null) { $this->id = $id; $this->userName = $userName; if (null === $auth) { do { $this->auth = sha1(random_int(PHP_INT_MIN, PHP_INT_MAX)); // /dev/urandom $result = $this->insert('sessions', [ 'auth' => $this->auth, 'user_id' => $this->id, 'username' => $this->userName, ]); } while (!$result); } else { $this->auth = $auth; } } public static function cleanUp(): void { $timestamp = date('Y-m-d H:i:s', time() - 900); self::delete('tokens', [['modified_at', '<', $timestamp]]); self::delete('sessions', [['modified_at', '<', $timestamp]]); } public function getAuth(): string { return $this->auth; } public static function getCallback(string $token): ?string { return self::selectSingleValue('tokens', 'callback', ['token' => $token]); } public function getLoginData(string $token): ?array { $ret = $this->select('logins', ['codice_fiscale', 'nome', 'cognome'], ['token' => $token]); return empty($ret) ? null : $ret[0]; } public function getId(): int { return $this->id; } public function getToken(string $callback): string { do { $token = sha1(random_int(PHP_INT_MIN, PHP_INT_MAX)); // /dev/urandom $result = $this->insert('tokens', [ 'token' => $token, 'auth' => $this->auth, 'callback' => $callback, ]); } while (!$result); $this->touchAuth($this->auth); return $token; } public function getUserName(): string { return $this->userName; } public static function setLoginData(string $token, string $codiceFiscale, string $nome, string $cognome): bool { return self::insert('logins', [ 'token' => $token, 'codice_fiscale' => $codiceFiscale, 'nome' => $nome, 'cognome' => $cognome, ]); } public static function verifyAuth(string $auth): ?User { $row = self::selectOne('sessions', ['user_id', 'username', 'auth'], ['auth' => $auth]); if (null === $row) { return null; } self::touchAuth($row['auth']); return new User($row['user_id'], $row['username'], $row['auth']); } public function verifyToken(string $token): bool { $row = $this->select('tokens', ['token'], ['auth' => $this->auth, 'token' => $token]); return count($row) > 0; } private static function getSiteKey(): string { return Config::getValue('site', 'key'); } private static function hashPassword(string $password): string { $siteKey = self::getSiteKey(); return hash('sha256', $siteKey . $password); } /** * Ha il solo effetto di aggiornare il campo "modified_at" della sessione */ private static function touchAuth(string $auth): bool { return self::update('sessions', [], ['auth' => $auth]); } }