session_lifetime_seconds = 60 * 60 * 24 * 3; } /** * Generate a random token * @param int $length */ private function gen_token(int $length): string { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $random = ''; for ($i = 0; $i < $length; $i++) { $index = rand(0, strlen($characters) - 1); $random .= $characters[$index]; } return $random; } /** * Saves a user into the session specified by their auth key * @param Session $session - the session user data */ public function save_session(Session $session): void { $path = "/tmp/{$session->token}"; $data = json_encode($session->to_array()); file_put_contents($path, $data, LOCK_EX); } /** * Loads the auth session associated with a specific key * @param string $token - the session $key */ private function load_session(string $token): ?Session { try { $path = "/tmp/$token"; if (!file_exists($path)) { return NULL; } $content = file_get_contents($path); $json = json_decode($content, TRUE); $session = new Session(); if ($session->from_array($json)) return NULL; return $session; } catch (Exception $e) { return NULL; } } /** * Creates a new session for a user */ public function create_session(User $user): Session { $session = new Session(); $session->token = $this->gen_token(128); $session->created = time(); $session->user = $user; $session->reset_expiry(); $this->save_session($session); return $session; } /** * Gets the current authed session */ public function get_session(): ?Session { $cookie_name = getenv("COOKIE_NAME"); if(!isset($_COOKIE[$cookie_name])) { return NULL; } $token = $_COOKIE[$cookie_name]; return $this->load_session($token); } }