openvk/VKAPI/Handlers/VKAPIRequestHandler.php

65 lines
1.7 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2020-08-12 14:36:18 +03:00
namespace openvk\VKAPI\Handlers;
2020-08-12 14:36:18 +03:00
use openvk\VKAPI\Exceptions\APIErrorException;
use openvk\Web\Models\Entities\IP;
2020-08-12 14:36:18 +03:00
use openvk\Web\Models\Entities\User;
use openvk\Web\Models\Repositories\IPs;
2020-08-12 14:36:18 +03:00
abstract class VKAPIRequestHandler
{
protected $user;
2022-12-17 02:03:02 +03:00
protected $platform;
public function __construct(?User $user = null, ?string $platform = null)
2020-08-12 14:36:18 +03:00
{
2022-12-17 02:03:02 +03:00
$this->user = $user;
$this->platform = $platform;
2020-08-12 14:36:18 +03:00
}
2020-08-12 14:36:18 +03:00
protected function fail(int $code, string $message): void
{
throw new APIErrorException($message, $code);
}
2020-08-12 14:36:18 +03:00
protected function getUser(): ?User
{
return $this->user;
}
2022-12-17 02:03:02 +03:00
protected function getPlatform(): ?string
{
return $this->platform ?? "";
2022-12-17 02:03:02 +03:00
}
2020-08-12 14:36:18 +03:00
protected function userAuthorized(): bool
{
return !is_null($this->getUser());
}
2020-08-12 14:36:18 +03:00
protected function requireUser(): void
{
if (!$this->userAuthorized()) {
2020-08-12 14:36:18 +03:00
$this->fail(5, "User authorization failed: no access_token passed.");
}
2020-08-12 14:36:18 +03:00
}
protected function willExecuteWriteAction(): void
{
$ip = (new IPs())->get(CONNECTING_IP);
$res = $ip->rateLimit();
if (!($res === IP::RL_RESET || $res === IP::RL_CANEXEC)) {
if ($res === IP::RL_BANNED && OPENVK_ROOT_CONF["openvk"]["preferences"]["security"]["rateLimits"]["autoban"]) {
$this->user->ban("User account has been suspended for breaking API terms of service", false);
$this->fail(18, "User account has been suspended due to repeated violation of API rate limits.");
}
$this->fail(29, "You have been rate limited.");
}
}
2020-08-12 14:36:18 +03:00
}