Files
PVM/public_html/gest-lib/login/classes/Login.class.php
2025-11-17 12:20:03 +01:00

613 lines
26 KiB
PHP

<?php
class Login {
public static function _moduleDatasource($filter) {
$Ret = new \Ret;
$retData = array(array("id" => "signupMode", "data" => Login\SignUp::get_mode()));
$Ret->set_data($retData);
return $Ret;
}
// <editor-fold desc="SETTERS" defaultstate="collapsed">
private static function set_sessionData($userData) {
if (!isset($_SESSION)) {
getSession();
}
if (LOGIN_JWT) {
$_SESSION["accessToken"] = $userData["accessToken"];
$_SESSION["refreshToken"] = $userData["refreshToken"];
$_SESSION["expiryDate"] = $userData["expiryDate"];
$_SESSION["expiresIn"] = $userData["expireIn"];
$_SESSION["deviceId"] = $userData["deviceId"];
} else {
$_SESSION["password"] = $userData["password"];
}
$_SESSION["username"] = $userData["user_name"];
$_SESSION["cod_mdep"] = $userData["cod_mdep"];
$_SESSION["user_code"] = $userData["user_code"];
$_SESSION["fullname"] = $userData["full_name"];
$_SESSION["cod_lang"] = isset($userData["cod_lang"]) ? $userData["cod_lang"] : "IT";
$_SESSION["profileDB"] = $GLOBALS["profileDB"];
$_SESSION["gruppo"] = $userData["key_group"];
$_SESSION["sqldriver"] = null;
$_SESSION["login"] = "OK";
}
// </editor-fold>
private static function fix_sessionUserPassword($md5User) {
if (!is_null(nullIfBlank($md5User))) {
$Query = new Query;
$Query->select("password")->from("wtb_users")
->where("dbo.MD5_encode(LOWER(wtb_users.user_name + wtb_users.password))", $md5User);
$Ret = $Query->toRet()->firstRowFirstValue()->execute();
if ($Ret->is_OK()) {
$password = $Ret->get_data();
if (!is_null($password)) {
$_SESSION["password"] = $password;
}
}
}
}
// <editor-fold desc="CHIAMATE SOTTO CLASSI" defaultstate="collapsed">
public static function request_resetPassword($data) {
return Login\UpdatePassword::send_changeLink($data);
}
public static function renew_password($data) {
return Login\UpdatePassword::update($data);
}
// </editor-fold>
private static $_userData = null;
private static function searchUserPassword($userName, $azienda = null) {
$arr_profileDb = array();
if (!is_null($azienda)) {
$arr_profileDb[] = $azienda;
}
$arr_profileDb = array_unique(array_merge($arr_profileDb, PVM::getListAziende()));
foreach ($arr_profileDb as $profileDb) {
$Query = new \Query;
$Query->select("password")->from("wtb_users")->where("user_name", $userName);
$Ret = $Query->profileDB($profileDb)->firstRowFirstValue()->toRet()->execute();
if ($Ret->is_OK() && !is_null($Ret->get_data())) {
return $Ret->get_data();
}
}
return null;
}
public static function authenticate($data) {
$userName = array_get($data, "username");
$password = array_get($data, "password");
$md5User = array_get($data, "md5_user");
$azienda = array_get($data, "azienda");
$deviceId = array_get($data, "deviceId");
$Ret = self::get_endpointHost();
if ($Ret->is_OK()) {
$endpoint = $Ret->get_string();
$accessWithOperatorPassword = false;
/*if (md5($password) === \Config::getOperatorMd5Password() && \PVM::isDebugEnv()) {
// IN SVILUPPO PERMETTE DI LOGGARSI DEFINENDO SOLO UTENTE E PASSWORD STANDARD
$passwordResult = self::searchUserPassword($userName, $azienda);
if (!is_null($passwordResult)) {
$password = $passwordResult;
$accessWithOperatorPassword = true;
}
}*/
$IMSApi = new IMSApi();
$IMSApi
->anonymousAuth()
->profileDB(is_null($azienda) ? "" : $azienda);
if (LOGIN_JWT) {
$IMSApi
->post("auth/login")
->body(array(
"username" => $userName,
"password" => $password,
"deviceId" => $deviceId,
"md5User" => $md5User
));
} else {
$IMSApi
->post("loginWeb")
->body(array(
"profileDb" => is_null($azienda) ? "" : $azienda,
"username" => $userName,
"password" => $password,
"md5User" => $md5User
));
}
if (!PVM::isDevClient()) {
$IMSApi->endpoint($endpoint);
}
$Ret = $IMSApi->send();
if ($Ret->is_OK()) {
self::destroy_session();
$retData = $Ret->get_data();
$Ret->set_data();
if (isset($retData[0]["dto"])) {
$user = $retData[0]["dto"];
if (LOGIN_JWT) {
$user["deviceId"] = $deviceId;
} else {
$user["password"] = $password;
}
if (!isset($user["username"])) {
$imsApi = new IMSApi();
$ret = $imsApi
->get("auth/me")
->profileDB(is_null($azienda) ? "" : $azienda)
->accessToken($user["accessToken"])
->send();
if ($ret->is_KO()) {
$ret->display();
}
$user = array_merge(
$user,
$ret->getDto()
);
}
self::$_userData = $user;
$GLOBALS["profileDB"] = is_null($azienda) ? $user["profile_db"] : $azienda;
if (true) {
self::fix_sessionUserPassword($md5User); // completamento $_SESSION["password"] per autenticazione con md5 da url
$Ret = self::checkTokenClient();
if ($Ret->is_OK()) {
if (!$accessWithOperatorPassword) {
$Ret = self::checkPasswordExpired($user);
}
if ($Ret->is_OK()) {
// self::set_profileDB_cached($userName . $password . $md5User, $user["profile_db"]);
self::set_sessionData($user);
// $Ret->set_data(array(
// "username" => $user["user_name"],
// "fullname" => $user["full_name"],
// "profileDb" => $user["profile_db"],
// "endPoint" => Rest::get_endPointRemote()
// ));
if (!is_null(nullIfBlank($md5User))) {
$idModuloRef = (isset($_GET["ref"])
&& User::hasModulo($_GET["ref"])) ? $_GET["ref"] : null;
$params = array_get($_GET, "params");
if (!is_null($idModuloRef)) {
header("Location: ./$idModuloRef.php" . (is_null($params) ? "" : "?$params"));
} else {
Controller::homeRedirect();
}
}
}
}
} else {
$Ret->set_error("File configurazione azienda {$user["profile_db"]} non trovato");
}
} else {
$Ret->set_error("Risposta servizio <i>loginWeb</i> non valida");
}
}
}
return $Ret;
}
private static function destroy_session() {
if (!isset($_SESSION)) {
getSession();
}
$keypair = null;
if (extension_loaded("sodium") && isset($_SESSION) && isset($_SESSION["keypair"])) {
$keypair = $_SESSION["keypair"];
}
$_SESSION = array();
@session_unset();
@session_destroy();
@session_start();
if (isset($keypair)) {
$_SESSION["keypair"] = $keypair;
}
}
private static function get_profileDB_cached($uid) {
$filePath = Cache::get_filepath(base64_encode($uid) . ".txt", null, true);
return file_exists($filePath) ? file_get_contents($filePath) : "";
}
private static function set_profileDB_cached($uid, $profileDb) {
$filePath = base64_encode($uid) . ".txt";
return Cache::write($filePath, $profileDb, null, true);
}
// <editor-fold desc="CONTROLLI E VALIDAZIONI " defaultstate="collapsed">
private static function get_tokenPasswordExpired($userData) {
return md5(strtolower($userData["user_name"] . $userData["password"]));
}
public static function set_newPasswordExpired($data) {
$azienda = $data["azienda"];
if (is_null($azienda)) {
$azienda = \Login::get_azienda();
}
if (!is_null($azienda)) {
$GLOBALS["profileDB"] = strtolower($azienda);
$token = $data["token"];
$newPassword = $data["new_password"];
$sql = "SELECT user_name FROM wtb_users WHERE dbo.MD5_encode(LOWER(User_name+password)) = '[token]'";
$Query = new Query($sql);
$Ret = $Query->setVar("token", $token)->anonymousAuth()->toRet()->firstRowFirstValue()->execute();
if ($Ret->is_OK()) {
$userName = $Ret->get_data();
if (!is_null($userName)) {
$Ret = User::updatePassword($userName, $newPassword, null, true, false, true);
} else {
$Ret->set_error("Richiesta non valida. Contattare l'assistenza");
}
} else {
$Ret->set_error("Richiesta non valida. Contattare l'assistenza");
}
} else {
$Ret->set_error("Azienda non trovata");
}
return $Ret;
}
private static function checkPasswordExpired($user) {
$Ret = new Ret;
$passwordExpireDate = Utility\Date::strtotime($user["password_endtime"], Format::strtotimeDMYHMS);
$lastAccessDate = nullIfBlank($user["Last_access_datetime"]);
if (!is_null($passwordExpireDate) && Utility\Date::getToday() > $passwordExpireDate) {
$Ret->set_warning()->set_data(
array("token" => self::get_tokenPasswordExpired($user), "azienda" => $user["profile_db"])
);
if (is_null($lastAccessDate)) {
$Ret->set_number(Login\Status::PasswordNeedChange)
->set_string("Gentile utente, le notifichiamo che è necessaria la creazione di una nuova password");
} else {
$Ret->set_number(Login\Status::PasswordExpired)
->set_string("Gentile utente, le notifichiamo che la sua password è scaduta");
}
}
return $Ret;
}
// </editor-fold>
// <editor-fold desc="TOKEN ATTIVAZIONE (valutare spostamento in classe apposita)" defaultstate="collapsed">
private static function getTokenHash($tokenId, $userName) {
$Ret = User::get_userData($userName);
if ($Ret->is_OK()) {
$user = $Ret->get_data();
return hash("md5", $tokenId . $user["user_name"] . $user["creation_datetime"]);
}
return null;
}
private static function checkTokenClient() {
$user = self::$_userData;
$Ret = new Ret;
if (!PVM::isDevMode()) { // ESCLUSIONE SE IN SVILUPPO E DA IP STATICI INTEGRY
if (!User::group_is(self::getGruppoValidatoriDefault(), User::AMMINISTRATORE_SISTEMA)) {
$GestSetup = new GestSetup;
$verificaTokenAttiva
= $GestSetup->section("LOGIN")->keySection("TOKEN_AUTHENTICATION")->defaultValue("N")->asBoolean()->get();
if ($verificaTokenAttiva) {
$userName = $user["user_name"];
$tokenId = self::getTokenClient();
$Ret = User\Token::get($tokenId);
if ($Ret->is_OK()) {
$token = $Ret->get_data();
if (is_null($token["flag_attivo"])) {
$Ret->set_warning()
->set_number(Login\Status::TokenLock)
->set_string("Richiesta di accesso gi&agrave; inoltrata.<br/>Ricever&agrave; un'email di conferma qualora la sua richiesta venga accettata.");
} else if ($token["flag_attivo"] == "N") {
$Ret->set_error("Gentile utente, la sua richiesta di accesso è stata respinta.<br/>Contattare l'amministratore per avviare le opportune verifiche.");
} else if ($token["flag_attivo"] == "S") {
User\Token::set_lastAccess($tokenId);
$Ret->set_OK();
} else {
$Ret->set_error("Stato richiesta non riconosciuto.<br/>Contattare l'amministratore per avviare le opportune verifiche.");
}
} else { // mai loggato
$Ret = self::getValidatori();
if ($Ret->is_OK()) {
$arr_validatori = $Ret->get_data();
if (count($arr_validatori) > 0) {
$userAgent = $_SERVER["HTTP_USER_AGENT"];
$ipRichiesta = $_SERVER["REMOTE_ADDR"];
$WtbUserTokens = new \EntityItem("wtb_user_tokens");
$WtbUserTokens->insert()
->set("tokenId", $tokenId)
->set("userName", $userName)
->set("flagAttivo", null)
->set("useragent", $userAgent)
->set("ipRequest", $ipRichiesta)
->setDatetime("dataCreazione", \Utility\Date::getNow());
$Ret = $WtbUserTokens->anonymousAuth()->send();
if ($Ret->is_OK()) {
$tokenHash = self::getTokenHash($tokenId, $userName);
$profileDB = $GLOBALS["profileDB"];
if (!is_null($tokenHash)) {
$UrlBuilder = new \RemoteModuleUrl();
$urlData = array("token_id" => $tokenId, "hash" => $tokenHash);
$url
= $UrlBuilder->module("login")->profileDB($profileDB)->data($urlData)->get_url();
$Mailer = new PVM\Mailer;
$mailText = "Gentile amministratore,<br/>
e' stata richiesta l'abilitazione di un token di accesso al portale web.<br/><br/>
Di seguito i dati del richiedente:<br/>";
$mailText .= "Nome utente: <b>" . strtoupper($userName) . "</b><br/>";
$mailText .= "IP richiedente: <b>" . $ipRichiesta . "</b><br/>";
$uaparsed = Utility::parse_useragent($userAgent);
$browser
= !is_null($uaparsed["browser"]["full_desc"]) ? $uaparsed["browser"]["full_desc"] : null;
$so
= !is_null($uaparsed["operating_system"]["full_desc"]) ? $uaparsed["operating_system"]["full_desc"] : null;
if (!is_null($uaparsed["device"]["full_desc"])) {
$mailText .= "Dispositivo: <b>" . $uaparsed["device"]["full_desc"]
. "</b><br/>";
}
if (!is_null($browser)) {
$mailText .= "Browser: <b>" . $browser . "</b><br/>";
}
if (!is_null($so)) {
$mailText .= "Sistema operativo: <b>" . $so . "</b><br/>";
}
if (is_null($browser) && is_null($so)) {
$mailText .= "Useragent: <b>" . $userAgent . "</b><br/>";
}
$mailText .= "<br/>Puoi abilitare l'accesso all'utente cliccando <a href='{$url}' target='_blank'>qui</a> o facendo copia e incolla del seguente link nel tuo browser: {$url}<br/><br/>";
foreach ($arr_validatori as $validatore) {
$Mailer->addTo($validatore["e_mail"], $validatore["full_name"]);
}
$Mailer->subject("Richiesta attivazione token per " . strtoupper($userName))
->message($mailText)
->azienda(\Azienda::getId());
$Ret = $Mailer->send();
if ($Ret->is_OK()) {
$Ret->set_warning()
->set_number(Login\Status::TokenLock)
->set_string("Gentile utente, il suo accesso è avvenuto da un dispositivo non riconosciuto, pertanto la sua richiesta di accesso necessita di essere convalidata da un amministratore.<br/>Riceverà un'email di conferma qualora essa venga accettata.");
} else {
$errorText = $Ret->get_error();
$Ret->set_warning()
->set_number(Login\Status::TokenLock)
->set_string("Gentile utente, il suo accesso è avvenuto da un dispositivo non riconosciuto, tuttavia si sono verificati problemi durante la notifica via email all'amministratore <i>({$errorText})</i><br/><u>Si prega di contattarlo per le opportune verifiche, nonché per processare la sua richiesta.</u>");
}
} else {
$Ret->set_error("Si è verificato un errore durante la richiesta di accesso (Hash-Token non valido).<br/><u>Contattare l'amministratore per avviare le opportune verifiche.</u>");
}
}
} else {
$Ret->set_error("Attenzione, validatori non configurati.<br/>Effettuare le opportune verifiche e riprovare.");
}
}
}
}
}
}
return $Ret->set_data(null);
}
private static function getGruppoValidatoriDefault() {
$GestSetup = new GestSetup;
$keyGroup = $GestSetup->keySection("KEYGROUP_VALIDATORI_DEFAULT")->get();
return if_null($keyGroup, User::RESPONSABILE_EDP);
}
public static function getValidatori() {
$idModuloToken = "token_board";
$usergroups = $users = array();
if (Azienda::hasModulo($idModuloToken)) {
$ModuloTokenBoard = new Modulo($idModuloToken);
$usergroups = $ModuloTokenBoard->getUsergroupsPolicy();
$users = $ModuloTokenBoard->getUsersPolicy();
}
$usergroups[] = self::getGruppoValidatoriDefault();
$usergroups = array_unique($usergroups);
$Query = new Query;
$Query->select("ISNULL(Full_name, User_name) AS full_name", "e_mail")
->from("wtb_users")
->where("ctrl_state", "S")
->where("dbo.f_isValidEmail(e_mail) = 1");
$where = "";
if (count($usergroups) > 0) {
$where = Query::processWhereParameters("key_group", $usergroups);
}
if (count($users) > 0) {
if (strlen($where) > 0) {
$where .= " OR ";
}
$where .= Query::processWhereParameters("user_name", $users);
}
$Query->where($where);
return $Query->toRet()->execute();
}
public static function enableToken($tokenId, $tokenHashCheck) { // qui passa quando l'amministratore clicca il link di abilitazione token
$Ret = User\Token::get($tokenId);
if ($Ret->is_OK()) {
$token = $Ret->get_data();
$tokenHash = self::getTokenHash($tokenId, $token["user_name"]);
if ($tokenHash == $tokenHashCheck) {
$flagAttivo = $token["flag_attivo"];
if (is_null($flagAttivo)) {
$Ret = User\Token::enable($tokenId);
if ($Ret->is_OK()) {
$Ret = User\Token::send_mail_activation($tokenId);
}
} else if ($flagAttivo == "N") {
$Ret->set_warning("Il token risulta esser stato disabilitato.<br/>&Egrave; possibile riabilitarlo dal pannello amministrativo.");
} else if ($flagAttivo == "S") {
$Ret->set_string("Il token risulta esser stato gi&agrave; abilitato.");
} else {
$Ret->set_error("Stato token non riconosciuto.<br/>Contattare lo sviluppatore per le opportune verifiche.");
}
} else {
$Ret->set_error("Verifica validit&agrave; richiesta fallita.");
}
}
return $Ret;
}
private static function getTokenClient($userName = null, $password = null) {
if (is_null($userName) || is_null($password)) {
$user = self::$_userData;
$userName = $user["user_name"];
$password = $user["password"];
}
$userName = strtolower($userName);
$password = strtolower($password);
$cookieName = $userName . "_" . md5($password);
if (isset($_COOKIE[$cookieName])) {
return $_COOKIE[$cookieName];
} else {
$token = hash("sha512", $userName . $password . rand(0, 10000));
setcookie($cookieName, $token, 2147483647);
return $token;
}
}
// </editor-fold>
public static function is_clientAndApplicationServer() {
$aziendaHost = PVM::getAziendaHost();
if (!is_null($aziendaHost)) {
$endPoint = Config::get_endPoint($aziendaHost);
if (!is_null($endPoint)) {
return PVM::get_clientIp() === parse_url($endPoint, PHP_URL_HOST);
}
}
return false;
}
// <editor-fold desc="ACQUISIZIONE PARAMETRI" defaultstate="collapsed">
private static function get_endpointHost() {
$Ret = new Ret;
$aziendaHost = PVM::getAziendaHost();
if (is_null($aziendaHost)) {
return $Ret->set_error("Azienda non riconosciuta da PVM::getAziendaHost");
}
$endPoint = Config::get_endPoint($aziendaHost);
if (is_null($endPoint)) {
return $Ret->set_error("Acquisizione endPoint aziendale fallita");
}
return $Ret->set_string($endPoint . "/" . IMSApi::get_serviceRootPath());
}
public static function get_azienda() {
global $_GET;
$azienda = null;
if (isset($_GET["azienda"])) {
$azienda = strtolower($_GET["azienda"]);
} else if (isset($GLOBALS["profileDB"])) {
$azienda = strtolower($GLOBALS["profileDB"]);
}
if (!file_exists("config_aziende/{$azienda}.config.json")) {
$azienda = null;
}
return if_null($azienda, PVM::getAziendaHost());
}
public static function get_aziendaMain($profileDB = null) {
if (is_null($profileDB)) {
$profileDB = self::get_azienda();
}
return Config::get_azienda($profileDB);
}
public static function get_backgroundsAzienda($profileDB) {
$arr_images = array();
if (!self::is_clientAndApplicationServer()) {
$profileDB = is_null($profileDB) ? self::get_azienda() : $profileDB;
$azienda = self::get_aziendaMain($profileDB);
$path_loginBg = str_replace(DIRECTORY_SEPARATOR, "/", AziendaUtils::getPathHome($azienda) . "login-bg"
. DIRECTORY_SEPARATOR);
if (\Utility\Str::ciEquals($azienda, "integry") && PVM::isDevClient()) {
$path_loginBg .= "funnies/";
}
if (file_exists($path_loginBg)) {
$arr_images = glob($path_loginBg . "*.{jpg,png}", GLOB_BRACE);
}
if (count($arr_images) == 0) {
$arr_images[]
= str_replace(DIRECTORY_SEPARATOR, "/", Controller::current_gestpath_images("teamwork-2600.jpg"));
}
}
return $arr_images;
}
// </editor-fold>
}