From 3354d45762bbe0db33e3d26d8997e6f6624f24d7 Mon Sep 17 00:00:00 2001 From: winter Sparkles Date: Sun, 9 Aug 2026 02:26:33 +0100 Subject: implement sessions and also log in/out session data is stored in sqlite, not using php sessions --- .gitignore | 2 + Psso/AuthInterface/UserExists.php | 6 +++ Psso/AuthProvider/ConfigFile.php | 9 +++- Psso/Challenge/Username.php | 12 ++++- Psso/Context.php | 8 +++ Psso/Identity.php | 12 +++++ Psso/Session.php | 101 ++++++++++++++++++++++++++++++++++++++ config.ini | 15 +++++- locale/en.ini | 4 ++ routes/index.php | 12 +++++ routes/login.php | 83 +++++++++++++++++++++++++++++++ routes/logout.php | 24 +++++++++ routes/test-challenges.php | 67 ------------------------- webroot/index.php | 2 + 14 files changed, 284 insertions(+), 73 deletions(-) create mode 100644 .gitignore create mode 100644 Psso/AuthInterface/UserExists.php create mode 100644 Psso/Identity.php create mode 100644 Psso/Session.php create mode 100644 routes/login.php create mode 100644 routes/logout.php delete mode 100644 routes/test-challenges.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6d430cb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# database files +data/ \ No newline at end of file diff --git a/Psso/AuthInterface/UserExists.php b/Psso/AuthInterface/UserExists.php new file mode 100644 index 0000000..a75d5c6 --- /dev/null +++ b/Psso/AuthInterface/UserExists.php @@ -0,0 +1,6 @@ +config['users']["$username.password-hash"] ?? null; + $hash = $this->config['users'][$username]['password-hash'] ?? null; if (!isset($hash)) { return false; } return password_verify($password, $hash); } + + public function userExists(string $username): bool { + return isset($this->config['users'][$username]); + } } diff --git a/Psso/Challenge/Username.php b/Psso/Challenge/Username.php index 43de085..c8fa762 100644 --- a/Psso/Challenge/Username.php +++ b/Psso/Challenge/Username.php @@ -1,6 +1,6 @@ userExists($inputData['user']); + if (!$success) $message = 'challenge.message.wrong-username'; + } + return new ChallengeResult( + self::class, $success, $inputData['user'], $message + ); } } diff --git a/Psso/Context.php b/Psso/Context.php index 4a2cd82..5af2102 100644 --- a/Psso/Context.php +++ b/Psso/Context.php @@ -10,4 +10,12 @@ class Context { public function addResult(ChallengeResult $result): void { $this->results[] = $result; } + + public function setTag(string $tag): void { + if (!$this->hasTag($tag)) $this->tags[] = $tag; + } + + public function hasTag(string $tag): bool { + return in_array($tag, $this->tags); + } } diff --git a/Psso/Identity.php b/Psso/Identity.php new file mode 100644 index 0000000..68272d4 --- /dev/null +++ b/Psso/Identity.php @@ -0,0 +1,12 @@ +user = $user; + $this->groups = $groups; + } +} diff --git a/Psso/Session.php b/Psso/Session.php new file mode 100644 index 0000000..35a6228 --- /dev/null +++ b/Psso/Session.php @@ -0,0 +1,101 @@ + true]; + $this->db = new \PDO(...$args); + $this->setup(); + } + + public static function get(): self { + if (!isset(self::$instance)) { + self::$instance = new self(); + } + self::$instance->setCookie(); + return self::$instance; + } + + protected function setup(): void { + $this->db->exec( + <<<'END' + create table if not exists session ( + token text primary key not null, + identity text not null default 'N;', + challenges text not null default 'N;' + ); + END + ); + } + + protected function domain(): string { + return explode('.', $_SERVER['HTTP_HOST'], 2)[1]; + } + + protected function setCookie(): void { + if (isset($_COOKIE['PSSO_session'])) return; + header( + 'Set-Cookie: PSSO_session=' . $this->currentToken() + . '; Domain=' . $this->domain() + . '; HttpOnly' + . '; Max-Age=' . static::$config['auth']['lifetime'] + . '; Path=/' + . '; SameSite=Lax' + . '; Secure' + ); + } + + protected function currentToken(): string { + return $this->token = $this->token ?? + $_COOKIE['PSSO_session'] ?? + base64_encode(random_bytes(129)); + } + + protected function setColumn(string $column, mixed $data): void { + $stmt = $this->db->prepare( + "insert into session(token, $column) values (?, ?) " + . "on conflict do update set $column=excluded.$column" + ); + $stmt->execute([$this->currentToken(), serialize($data)]); + } + + public function getColumn(string $column): mixed { + $stmt = $this->db->prepare("select $column from session where token=?"); + $stmt->execute([$this->currentToken()]); + return unserialize($stmt->fetchColumn(0)); + } + + public function setIdentity(mixed $identity): void { + $this->setColumn('identity', $identity); + } + + public function getIdentity(): mixed { + return $this->getColumn('identity'); + } + + public function setChallenges(mixed $challenges): void { + $this->setColumn('challenges', $challenges); + } + + public function getChallenges(): mixed { + return $this->getColumn('challenges'); + } +} diff --git a/config.ini b/config.ini index f5a083c..633a88c 100644 --- a/config.ini +++ b/config.ini @@ -8,6 +8,13 @@ name = Pleasant SSO ;; primary domain where your login page will be primary-domain = auth.example.com +;; all domains that need to be visited to set cookies appropriately +;; note that for now, it's assumed that the domain one level higher than these +;; is the "registrable domain" where the cookies are set to +;; e.g. for 'auth.example.com', the cookie will get Domain=example.com +cookie-domains[] = auth.example.com +cookie-domains[] = auth.example.net + ;; location where the source code of the version of the software running on your ;; server can be found. so if you make any significant changes to the source ;; code you'd better put them up online somewhere and change this accordingly!! @@ -28,13 +35,17 @@ header-prefix = X-Login ;; ConfigFile -> look in this file, see below provider = ConfigFile +;; how long (in seconds) until a session expires and you have to log in again +;; 1 year = 31557600, 1 month = 2629800, 1 week = 604800, 1 day = 86400 +lifetime = 604800 + ;; this next section allows you to define users very simple here in the config ;; file, in case you don't want to use an external auth provider (set above) ;; but if you are using an external provider it's okay to remove all of this [users] -;; .password-hash -> allow password login for user +;; password-hash -> allow password login for user ;; password hash should be generated by php function 'password_hash' -winter.password-hash = "$2y$12$V3dwpbHF5fTx46g9xMflvODNGmr0apltiaDONUSE2skRrslgcRxSS" +winter[password-hash] = "$2y$12$V3dwpbHF5fTx46g9xMflvODNGmr0apltiaDONUSE2skRrslgcRxSS" ;; more options to be added in future! diff --git a/locale/en.ini b/locale/en.ini index 7809906..295ffcc 100644 --- a/locale/en.ini +++ b/locale/en.ini @@ -6,10 +6,14 @@ error.wrong-method.long = "Your request method (%s) is not valid for this path." error.uncaught = "Uncaught exception" ui.powered-by = "Powered by Pleasant SSO" ui.source-code = "Source code" +logout.title = "Log out" +logout.warning = "Are you sure you want to log out?" +logout.confirm = "Yes, I'm sure" login.title = "Log in" challenge.input.username = "Username" challenge.input.password = "Password" challenge.input.otp = "One-time passcode" +challenge.message.wrong-username = "Username does not exist" challenge.message.wrong-password = "Incorrect username or password" challenge.message.wrong-otp = "Invalid OTP code" challenge.continue = "Continue" \ No newline at end of file diff --git a/routes/index.php b/routes/index.php index 685ab92..f884be5 100644 --- a/routes/index.php +++ b/routes/index.php @@ -1,8 +1,20 @@ doc->addChild('content'); $content->addChild('p', 'Welcome to Pleasant SSO!'); + $identity = $session->getIdentity(); + $content->addChild('pre', 'Your identity: ' . print_r($identity, true)); + if ($identity === null) { + $link = $content->addChild('a', L('login.title')); + $link->addAttribute('href', '/login'); + } else { + $link = $content->addChild('a', L('logout.title')); + $link->addAttribute('href', '/logout'); + } $resp->send(); } diff --git a/routes/login.php b/routes/login.php new file mode 100644 index 0000000..2f73271 --- /dev/null +++ b/routes/login.php @@ -0,0 +1,83 @@ +setChallenges(null); + $session->setIdentity( + new Psso\Identity($context->user, $context->groups) + ); + header('Location: /'); //temporary crap for testing + return; + } + if (count($challengeTypes) == 0) { + throw new RuntimeException('no more challenges available!! auth fail'); + } + + // create challenges as indicated by the auth flow + $challenges = []; + foreach ($challengeTypes as $type) { + $c = $type::create($context); + $challenges[$c->serial] = $c; + } + + // send challenges to user + $resp = new Psso\XMLResponse; + $resp->doc->addAttribute('title', L('login.title')); + if (isset($message)) { + $resp->doc->addChild('challenge-message', L($message)); + } + foreach ($challenges as $challenge) { + $challenge->addAsHtml($resp->doc); + } + $resp->send(); + + // and store the challenges (actual instances!) for next request + $session->setChallenges($challenges); +} + +function GET() { + $session = Psso\Session::get(); + if ($session->getIdentity() !== null) { + // already logged in + header('Location: /'); // change this to return continue page + } + + $context = new Psso\Context; + presentChallenges($session, $context); +} + +function POST(array $config) { + $session = Psso\Session::get(); + + // we are receiving results of a previous challenge... load it in + $challenges = $session->getChallenges(); + $answeredChallenge = $challenges[$_POST['challenge']]; + + // match up the given input responses to their original Inputs + $inputData = []; + foreach ($_POST as $name => $value) { + if ($name == 'challenge') continue; + $serial = explode('__', $name, 2)[1]; + $input = $answeredChallenge->findInput($serial); + $inputData[$input->id] = $value; + } + + // check provided inputs against the challenge, are they correct? + $providerClass = 'Psso\\AuthProvider\\' . $config['auth']['provider']; + $provider = new $providerClass($config); + $result = $answeredChallenge->validate($provider, $inputData); + + // append the new result to the context so the auth flow can see it + $context = $answeredChallenge->context; + $context->addResult($result); + + // also set the user in context if we're able to + if ($result->successful && isset($result->user) && !isset($context->user)) { + $context->user = $result->user; + } + presentChallenges($session, $context, $result->message); +} diff --git a/routes/logout.php b/routes/logout.php new file mode 100644 index 0000000..21b2179 --- /dev/null +++ b/routes/logout.php @@ -0,0 +1,24 @@ +getIdentity() === null) { + // not actually logged in anyway + header('Location: /'); + return; + } + + $resp = new Psso\XMLResponse; + $resp->doc->addAttribute('title', L('logout.title')); + $form = $resp->doc->addChild('form'); + $form->addChild('p', L('logout.warning')); + $form->addAttribute('method', 'post'); + $form->addChild('button', L('logout.confirm')); + $resp->send(); +} + +function POST() { + $session = Psso\Session::get(); + $session->setIdentity(null); + header('Location: /'); +} diff --git a/routes/test-challenges.php b/routes/test-challenges.php deleted file mode 100644 index 32aad7e..0000000 --- a/routes/test-challenges.php +++ /dev/null @@ -1,67 +0,0 @@ -serial] = $c; - } - - $resp = new Psso\XMLResponse; - $resp->doc->addAttribute('title', L('login.title')); - if (isset($message)) { - $resp->doc->addChild('challenge-message', L($message)); - } - foreach ($challenges as $challenge) { - $challenge->addAsHtml($resp->doc); - } - $resp->send(); - // instead of just saving this to a file, it needs to be associated with the - // user's session somehow - file_put_contents('challenges-data', serialize($challenges)); -} - -function GET() { - $context = new Psso\Context; - presentChallenges($context); -} - -function POST(array $config) { - // we are receiving results of a previous challenge... load it in - $challenges = unserialize(file_get_contents('challenges-data')); - $answeredChallenge = $challenges[$_POST['challenge']]; - // match up the given input responses to their original Inputs - $inputData = []; - foreach ($_POST as $name => $value) { - if ($name == 'challenge') continue; - $serial = explode('__', $name, 2)[1]; - $input = $answeredChallenge->findInput($serial); - $inputData[$input->id] = $value; - } - - $providerClass = 'Psso\\AuthProvider\\' . $config['auth']['provider']; - $provider = new $providerClass($config); - $result = $answeredChallenge->validate($provider, $inputData); - - $context = $answeredChallenge->context; - $context->addResult($result); - - if ($result->successful) { - if (isset($result->user) && !isset($context->user)) { - $context->user = $result->user; - } - } - presentChallenges($context, $result->message); -} diff --git a/webroot/index.php b/webroot/index.php index dd8a6d9..eda73c2 100644 --- a/webroot/index.php +++ b/webroot/index.php @@ -18,6 +18,8 @@ $path = explode('?', $path, 2)[0]; $config = parse_ini_file(__DIR__ . '/../config.ini', true, INI_SCANNER_TYPED); +Psso\Session::setDsn($config, 'sqlite:' . __DIR__ . '/../data/sessions.sqlite'); + require_once __DIR__ . '/../localisation.php'; Psso\XMLResponse::addStylesheet('../templates/index.xsl'); -- cgit v1.3