ldap = new LDAPHelper(); $this->auth = new AuthHelper(); $this->domain = getenv("HTTP_HOST"); } /** * Displays a page to the user * @param string $file * @param array $data */ private function send_page( string $file, array $data = array() ): void { extract($data); $webroot = $GLOBALS['webroot']; require($webroot . '/views/header.php'); require($webroot . "/views/$file.php"); require($webroot . '/views/footer.php'); } /** * Displays a message to the user (message page) * @param string $title * @param string $msg * @param int $code */ private function send_message( string $title, string $msg ): void { $this->send_page('message', array( 'title' => $title, 'msg' => $msg )); } /** * Gets the HTTP request information */ private function get_req(): array { return array( 'path' => $_SERVER['REQUEST_URI'], 'method' => $_SERVER['REQUEST_METHOD'], ); } /** * @param array $fields */ private function get_post_info( string ...$fields ): ?array { $values = array(); try { $temp = NULL; parse_str(file_get_contents('php://input'), $temp); foreach ($temp as $key => $value) { $_POST[$key] = $value; } } catch (Exception $_e) {} foreach ($fields as $key) { if (!isset($_POST[$key])) return NULL; $values[$key] = $_POST[$key]; } return $values; } private function handle_login(): void { $info = $this->get_post_info('username', 'password'); if ($info == NULL) { http_response_code(400); $this->send_message('Bad Requet', 'Credentials were not supplied'); return; } $user = $this->ldap->search($info['username']); if ($user == NULL || !count($user)) { http_response_code(400); $this->send_message('Bad Requst', 'User does not exist'); return; } $user = $user[0]; if ($this->ldap->bind( $user->dn, $info['password'] )) { http_response_code(400); $this->send_message('Bad Requst', 'Invalid Credentials'); return; } $session = $this->auth->create_session($user); http_response_code(200); $session->write_headers(); $this->send_message('Success', 'Authenticated. You can now go back to your content'); } /** * Handles the HTTP request * @param array $req */ private function handle_req(array $req): void { if ($req['method'] == 'POST') { $this->handle_login(); return; } $session = $this->auth->get_session(); if ($session == NULL) { // user is NOT authenticated if ($req['path'] == '/login') { // user is requesting login page http_response_code(200); $this->send_page('login', array( 'title' => 'Login' )); } else { // user is trying to forward auth // redirect them to login http_response_code(303); header("Location: http://{$this->domain}/login"); } } else { // user is authenticated $session->reset_expiry(); $session->write_headers(); $this->auth->save_session($session); } } public function handle(): void { $req = $this->get_req(); $this->handle_req($req); } }