diff options
| author | winter Sparkles | 2026-08-09 02:26:33 +0100 |
|---|---|---|
| committer | winter Sparkles | 2026-08-09 02:26:33 +0100 |
| commit | 3354d45762bbe0db33e3d26d8997e6f6624f24d7 (patch) | |
| tree | 4bef4bf59488f443ed54ff6e30002268836ac259 | |
| parent | 4bb659e1f7bb5850db5695a536428a9b71e3ffe5 (diff) | |
implement sessions and also log in/out
session data is stored in sqlite, not using php sessions
| -rw-r--r-- | .gitignore | 2 | ||||
| -rw-r--r-- | Psso/AuthInterface/UserExists.php | 6 | ||||
| -rw-r--r-- | Psso/AuthProvider/ConfigFile.php | 9 | ||||
| -rw-r--r-- | Psso/Challenge/Username.php | 12 | ||||
| -rw-r--r-- | Psso/Context.php | 8 | ||||
| -rw-r--r-- | Psso/Identity.php | 12 | ||||
| -rw-r--r-- | Psso/Session.php | 101 | ||||
| -rw-r--r-- | config.ini | 15 | ||||
| -rw-r--r-- | locale/en.ini | 4 | ||||
| -rw-r--r-- | routes/index.php | 12 | ||||
| -rw-r--r-- | routes/login.php (renamed from routes/test-challenges.php) | 44 | ||||
| -rw-r--r-- | routes/logout.php | 24 | ||||
| -rw-r--r-- | webroot/index.php | 2 |
13 files changed, 231 insertions, 20 deletions
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 @@ +<?php +namespace Psso\AuthInterface; + +interface UserExists { + public function userExists(string $username): bool; +} diff --git a/Psso/AuthProvider/ConfigFile.php b/Psso/AuthProvider/ConfigFile.php index 0d855d0..688c193 100644 --- a/Psso/AuthProvider/ConfigFile.php +++ b/Psso/AuthProvider/ConfigFile.php @@ -2,15 +2,20 @@ namespace Psso\AuthProvider; use Psso\{AuthProvider, AuthInterface}; -class ConfigFile extends AuthProvider implements AuthInterface\Password { +class ConfigFile extends AuthProvider +implements AuthInterface\Password, AuthInterface\UserExists { public function validatePassword( string $username, #[\SensitiveParameter] string $password ): bool { - $hash = $this->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 @@ <?php namespace Psso\Challenge; -use Psso\{Challenge, AuthProvider, ChallengeResult, Input}; +use Psso\{Challenge, AuthProvider, AuthInterface, ChallengeResult, Input}; /** Just asks for a username and sets it in the context. Always succeeds. */ class Username extends Challenge { @@ -11,6 +11,14 @@ class Username extends Challenge { public function validate( AuthProvider $provider, array $inputData ): ChallengeResult { - return new ChallengeResult(self::class, true, $inputData['user'], null); + $success = true; + $message = null; + if ($provider instanceof AuthInterface\UserExists) { + $success = $provider->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 @@ +<?php +namespace Psso; + +class Identity { + public protected(set) string $user; + public protected(set) array $groups; + + public function __construct(string $user, array $groups = []) { + $this->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 @@ +<?php +namespace Psso; + +class Session { + protected static ?self $instance = null; + protected static ?array $pdoSetup = null; + protected static ?array $config = null; + + protected \PDO $db; + private ?string $token = null; + + public static function setDsn( + array $config, + string $dsn, + ?string $username = null, + #[\SensitiveParameter] ?string $password = null + ): void { + static::$config = $config; + static::$pdoSetup = [$dsn, $username, $password]; + } + + protected function __construct() { + $args = static::$pdoSetup; + $args[] = [\PDO::ATTR_PERSISTENT => 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'); + } +} @@ -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] -;; <user>.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 @@ <?php function GET() { + $session = Psso\Session::get(); + + // all of this markup is temporary and for testing only :3 $resp = new Psso\XMLResponse; $content = $resp->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/test-challenges.php b/routes/login.php index 32aad7e..2f73271 100644 --- a/routes/test-challenges.php +++ b/routes/login.php @@ -1,24 +1,30 @@ <?php function presentChallenges( - Psso\Context $context, ?string $message = null + Psso\Session $session, Psso\Context $context, ?string $message = null ) { $challengeTypes = Psso\AuthFlow::nextStep($context); if ($challengeTypes === true) { // auth finished! all good - header('Location: /login-success'); //temporary crap for testing + $session->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)) { @@ -28,20 +34,29 @@ function presentChallenges( $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)); + + // 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($context); + presentChallenges($session, $context); } function POST(array $config) { + $session = Psso\Session::get(); + // we are receiving results of a previous challenge... load it in - $challenges = unserialize(file_get_contents('challenges-data')); + $challenges = $session->getChallenges(); $answeredChallenge = $challenges[$_POST['challenge']]; + // match up the given input responses to their original Inputs $inputData = []; foreach ($_POST as $name => $value) { @@ -51,17 +66,18 @@ function POST(array $config) { $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); - - if ($result->successful) { - if (isset($result->user) && !isset($context->user)) { - $context->user = $result->user; - } + + // 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($context, $result->message); + 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 @@ +<?php + +function GET() { + $session = Psso\Session::get(); + if ($session->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/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'); |
