From 3946e9546604e531b0f3eb7849dd6d2dea247d9c Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Tue, 23 Jan 2024 16:58:26 +0300 Subject: add basic oidc support --- classes/Config.php | 8 +++++++ login.php | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/classes/Config.php b/classes/Config.php index b445973..3fc8358 100644 --- a/classes/Config.php +++ b/classes/Config.php @@ -15,6 +15,10 @@ class Config { const DICT_SERVER = "DICT_SERVER"; const SESSION_LIFETIME = "SESSION_LIFETIME"; const SESSION_NAME = "SESSION_NAME"; + const OIDC_NAME = "OIDC_NAME"; + const OIDC_URL = "OIDC_URL"; + const OIDC_CLIENT_ID = "OIDC_CLIENT_ID"; + const OIDC_CLIENT_SECRET = "OIDC_CLIENT_SECRET"; private const _DEFAULTS = [ Config::DB_TYPE => [ "sqlite", Config::T_STRING ], @@ -24,6 +28,10 @@ class Config { Config::DICT_SERVER => [ "", Config::T_STRING ], Config::SESSION_LIFETIME => [ 86400*30, Config::T_INT ], Config::SESSION_NAME => [ "epube_sid", Config::T_STRING ], + Config::OIDC_NAME => [ "OIDC", Config::T_STRING ], + Config::OIDC_URL => [ "", Config::T_STRING ], + Config::OIDC_CLIENT_ID => [ "", Config::T_STRING ], + Config::OIDC_CLIENT_SECRET => [ "", Config::T_STRING ], ]; private static ?Config $instance = null; diff --git a/login.php b/login.php index 37bed4b..a8df8ac 100644 --- a/login.php +++ b/login.php @@ -1,10 +1,11 @@ setRedirectURL(Config::make_self_url() . "/login.php"); + $oidc->addScope(['openid', 'profile', 'email']); + $oidc->authenticate(); + + exit; + } else if ($_REQUEST['code'] ?? false) { + + $oidc = new OpenIDConnectClient(Config::get(Config::OIDC_URL), + Config::get(Config::OIDC_CLIENT_ID), + Config::get(Config::OIDC_CLIENT_SECRET)); + + try { + $oidc->setRedirectURL(Config::make_self_url() . "/login.php"); + $oidc->addScope(['openid', 'profile', 'email']); + $oidc->authenticate(); + + $username = trim(mb_strtolower($oidc->requestUserInfo("preferred_username"))); + + if ($username) { + $user = ORM::for_table('epube_users') + ->where('user', $username) + ->find_one(); + + if ($user) { + if (session_status() != PHP_SESSION_ACTIVE) + session_start(); + + session_regenerate_id(true); + + $_SESSION["owner"] = $username; + $_SESSION["pass_hash"] = sha1($user->pass); + $_SESSION["csrf_token"] = bin2hex(random_bytes(16)); + + header("Location: index.php"); + exit; + } + } + + } catch (Exception $e) { + $login_notice = 'OIDC Error: ' . $e->getMessage(); + } + + logout_user(); } else { logout_user(); } @@ -54,6 +103,11 @@