Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration OIDC #621

Merged
merged 4 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions agent/mmc/plugins/base/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1149,6 +1149,7 @@ def addUser(
"shadowAccount",
"top",
"person",
"lmcUserObject"
],
"uid": uid,
"gecos": gecos,
Expand Down
9 changes: 9 additions & 0 deletions services/mmc/authproviders.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Example config for using Google OIDC
# clientId and clientSecret are obtained after enabling OAuth 2.0 in your Google account
# lmcACL is the default ACL defined on a user using this OIDC provider
#[Google]
#logoUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c1/Google_%22G%22_logo.svg"
#urlProvider = "https://accounts.google.com"
#clientId = ""
#clientSecret = ""
#lmcACL = ":base#main#default/"
23 changes: 23 additions & 0 deletions web/graph/login/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -239,5 +239,28 @@ select {
}

/*ADD*/
.provider-btn {
background-color: #fafafa;
color: rgb(0, 0, 0);
padding: 10px 15px;
border: none;
border-radius: 5px;
font-size: 14px;
font-weight: bold;
cursor: pointer;
display: flex;
align-items: center;
margin: 5px;
}

.provider-btn:hover {
background-color: #e0e0e0;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.provider-btn img {
height: 20px;
margin-right: 10px;
}

.controls{margin: auto;}
7 changes: 6 additions & 1 deletion web/includes/createSession.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
$lang = $_POST["lang"];
if (isset($_GET["lang"]))
$lang = $_GET["lang"];
if (isset($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
}

$lang = (isset($lang) && $lang != "") ? $lang : "en_US";

$_SESSION['lang'] = $lang;
setcookie('lang', $lang, time() + 3600 * 24 * 30);
Expand All @@ -28,4 +33,4 @@

/* Make the comnpany logo effect */
$_SESSION["doeffect"] = True;
?>
?>
38 changes: 38 additions & 0 deletions web/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,44 @@ function changeServerLang() {
</div>
</form>

<!-- PROVIDER -->
<form action="providers.php" method="post" name="loginFormProvider" id="loginFormProvider">
<div class="control-group">
<br><hr>
<h3 style="text-align: center;">PROVIDERS</h3>
<?php
function fetchProvidersConfig() {
$iniPath = "/etc/mmc/authproviders.ini";
if (is_readable($iniPath)) {
return parse_ini_file($iniPath, true);
} else {
echo "Erreur : Impossible de lire le fichier de configuration des providers. Vérifiez l'installation.";
exit();
}
}

$providersConfig = fetchProvidersConfig();

foreach ($providersConfig as $provider => $config) {
$logoUrl = $config['logoUrl'];
echo '<button onclick="confirmLogin(\'' . $provider . '\')" class="login-btn provider-btn">';
echo '<img src="' . $logoUrl . '" alt="' . $provider . ' Logo"> Se connecter avec ' . $provider;
echo '</button>';
}
?>
<input type="hidden" id="selectedProvider" name="selectedProvider" />
<input type="hidden" id="selectedLang" name="lang" value="<?= $_SESSION['lang'] ?>" />
</div>
</form>
<script>
function confirmLogin(provider) {
document.getElementById('selectedProvider').value = provider;
document.getElementById('loginFormProvider').submit();
document.getElementById('selectedLang').submit();
}
</script>
<!-- ./PROVIDER -->

</div> <!-- login -->
</div> <!-- content -->
</div> <!-- interface -->
Expand Down
203 changes: 203 additions & 0 deletions web/providers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
<?php
require('phpseclib3/autoload.php');
require_once "oidc/OpenID-Connect-PHP-master/src/OpenIDConnectClient.php";

// part for error management before generation of the session following the return of authentication with the provider
require("includes/PageGenerator.php");
session_name("PULSESESSION");
session_start();

use Jumbojett\OpenIDConnectClient;

function parseIniSection($filePath, $section) {
if (!is_readable($filePath)) {
return [];
}

$sectionData = [];
$insideSection = false;

$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (preg_match('/^\s*[;#]/', $line)) {
continue;
}
if (preg_match('/^\s*\[(.+?)\]\s*$/', $line, $matches)) {
if ($matches[1] === $section) {
$insideSection = true;
} else {
if ($insideSection) break;
}
continue;
}

if ($insideSection && preg_match('/^\s*(\S+)\s*=\s*(.*?)\s*$/', $line, $matches)) {
$sectionData[$matches[1]] = $matches[2];
}
}

return $sectionData;
}

function fetchBaseIni($section, $key) {
$localPath = "/etc/mmc/plugins/base.ini.local";
$iniPath = "/etc/mmc/plugins/base.ini";

$localData = parseIniSection($localPath, $section);
if (array_key_exists($key, $localData)) {
return $localData[$key];
}

$iniData = parseIniSection($iniPath, $section);
return $iniData[$key] ?? null;
}

function fetchProvidersConfig(){
$config = parse_ini_file("/etc/mmc/authproviders.ini", true);
$localConfig = parse_ini_file("/etc/mmc/authproviders.ini.local", true);
$config = array_replace_recursive($config, $localConfig);

return $config;
}

function generateStr($length = 50) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

// language management
if (isset($_POST['selectedLang'])) {
$lang = $_POST['selectedLang'];
setcookie('userLang', $lang, time() + 86400, '/');
}

$providersConfig = fetchProvidersConfig();

if ($providersConfig && (isset($_POST['selectedProvider']) || isset($_GET['code']))) {
$provider = $_POST['selectedProvider'] ?? 'google';
$providerKey = ucfirst(strtolower($provider));

if (array_key_exists($providerKey, $providersConfig)) {
$clientUrl = $providersConfig[$providerKey]['urlProvider'];
$clientId = $providersConfig[$providerKey]['clientId'];
$clientSecret = $providersConfig[$providerKey]['clientSecret'];

// Check if the Provider URL is configured
if (empty($clientUrl) || $clientUrl == "https://url_de_mon_provider") {
new NotifyWidgetFailure("Supplier $providerKey selected is not properly configured.Please check the supplier URL in the configuration settings.");
header("Location: /mmc/index.php");
exit;
}

$oidc = new OpenIDConnectClient($clientUrl, $clientId, $clientSecret);
$oidc->setRedirectURL('https://localhost/mmc/providers.php');
$oidc->addScope(['email']);

if (!isset($_GET['code'])) {
$oidc->authenticate();
} else {
try {
$oidc->authenticate();
$token = $oidc->getAccessToken();
$userInfo = $oidc->requestUserInfo();

require_once("includes/utils.inc.php");
require("includes/config.inc.php");
require("modules/base/includes/users.inc.php");
require("modules/base/includes/edit.inc.php");
require("modules/base/includes/groups.inc.php");
require_once("includes/modules.inc.php");

global $conf;
$error = "";
$login = "";

/* Session creation */
$ip = preg_replace('@\.@', '', $_SERVER["REMOTE_ADDR"]);
$sessionid = md5(time() . $ip . mt_rand());

session_id($sessionid);
session_name("PULSESESSION");
session_start();

$_SESSION["ip_addr"] = $_SERVER["REMOTE_ADDR"];
$_SESSION["XMLRPC_agent"] = parse_url($conf["server_01"]["url"]);
$_SESSION["agent"] = "server_01";
$_SESSION["XMLRPC_server_description"] = $conf["server_01"]["description"];
$_SESSION['lang'] = $_COOKIE['userLang'];

$login = "root";
$pass = fetchBaseIni("ldap", "password");

include("includes/createSession.inc.php");

// Users list
$res = get_users_detailed($error, '', 0, 20);

$newUser = $providerKey . "/" . $userInfo->email;
$newPassUser = generateStr(50);
$aclString = $providersConfig[$providerKey]['lmcACL'];

$found = false;
foreach ($res[1] as $user) {
if ($user['uid']->scalar === $newUser) {
$found = true;
break;
}
}

if (!$found) {
$add = add_user(
$newUser, // uid
prepare_string($newPassUser), // password
"given_name", // firstN
"family_name", // lastN
null, // homeDir (None)
true, // createHomeDir
false, // ownHomeDir
null // primaryGroup (None)
);

if($add['code'] == 0) {
$setlmcACL = setAcl($newUser, $aclString);
$login = $newUser;
$pass = $newPassUser;
include("includes/createSession.inc.php");
/* Redirect to main page */
header("Location: main.php");
exit;
} else {
new NotifyWidgetFailure("Impossible to set up acls for the user $newUser", "Erreur acl");
header("Location: /mmc/index.php");
exit;
}
} else {
$newPassUser = generateStr(50); // New password
// Here we edit the user password
$ret = callPluginFunction("changeUserPasswd",
array(array($newUser, prepare_string($newPassUser)))
);

if (auth_user($newUser, $newPassUser, true)) {
$login = $newUser;
$pass = $newPassUser;
include("includes/createSession.inc.php");
/* Redirect to main page */
header("Location: main.php");
exit;
} else {
new NotifyWidgetFailure("Your account doesn't have access rights to Medulla. Contact the administrator of your entity to provide this access.", "Erreur d'authentification");
header("Location: /mmc/index.php");
exit;
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
} else {
new NotifyWidgetFailure("The selected supplier is not supported or its configuration is missing.Please check the configuration settings for this supplier.");
header("Location: /mmc/index.php");
exit;
}
}
?>