cookie_name = $cookie_name; $this->base_url = $base_url; $this->time_limit = $time_limit; $this->password = $encrypted_password; $this->filename = $login_file; $this->manager = $filemanager; } protected $selector; protected $token; public function loadCookie() { if (isset($_COOKIE[$this->cookie_name])) { list($s, $t) = \explode(':', $_COOKIE[$this->cookie_name]); $this->selector = $s; $this->token = $t; } } public function saveCookie() { $now = Carbon::now(); $exp = $now->addSeconds($this->time_limit); \setcookie($this->cookie_name, implode(':', [$this->selector, $this->token]), $exp->timestamp, $this->base_url); } public function removeCookie() { \setcookie($this->cookie_name, '', Carbon::now()->timestamp, '/'); } protected function generateToken() { $this->selector = bin2hex(\random_bytes(12)); $this->token = bin2hex(\random_bytes(20)); } protected $data; public function getData() { if ($this->data === null) { $this->data = (object) [ 'ip' => 0, 'token' => '', 'time' => 0 ]; if ($this->manager->folder('data')->exists($this->filename)) { $this->data = $this->manager->folder('data')->load($this->filename); $this->data->time = Carbon::parse($this->data->time); } } } protected $ip; public function getIp(Request $request) { if ($this->ip === null) { $this->ip = $request->getHeader('host')[0]; } return $this->ip; } protected $is_logged_in; public function checkAuth(Request $request): bool { if ($this->is_logged_in === null) { $this->loadCookie(); if ($this->selector === null) { $this->is_logged_in = false; return false; } $this->getIp($request); $this->getData(); if ($this->data->ip != $this->ip) { $this->is_logged_in = false; return false; } if ($this->data->token != implode(':', [$this->selector, $this->token])) { $this->is_logged_in = false; return false; } $now = Carbon::now(); if ($this->data->time->copy()->addSeconds($this->time_limit)->diffInSeconds($now->copy()) < 0) { $this->is_logged_in = false; } $this->is_logged_in = true; } return $this->is_logged_in; } public function login(Request $request): bool { $post = $request->getParsedBody(); if (!password_verify($post['clave'], $this->password)) { return false; } $this->generateToken(); $this->getIp($request); $time = Carbon::now(); $data = [ 'ip' => $this->ip, 'token' => implode(':', [$this->selector, $this->token]), 'time' => $time->format('Y-m-d H:i') ]; $this->manager->folder('data')->save($this->filename, $data); $this->saveCookie(); $this->is_logged_in = true; return true; } public function logout(): bool { $this->removeCookie(); $data = [ 'ip' => 0, 'token' => ':', 'time' => 0 ]; $this->manager->folder('data')->save($this->filename, $data); $this->is_logged_in = false; return true; } }