浏览代码

Start API

stany.ferer 1 年之前
父节点
当前提交
30fea0e56e

+ 3 - 0
conf.inc.php

@@ -58,6 +58,9 @@ define("DB_T_TYPE_USER", "type_user");
 define("DB_T_TYPE_DOCUMENT", "type_document");
 define("DB_T_TYPE_ACCESS", "type_access");
 
+define("API_AUTHENT", DOMAIN_API."authenticator/");
+define("API_LOGOUT", DOMAIN_API."logout/");
+
 define("HOME_TYPE_USER", array(
     1 =>    [ // Administrateur
                 "home" => "rh-liste-salaries",

+ 118 - 0
core/class/apiSessionAuthenticator.class.php

@@ -0,0 +1,118 @@
+<?php
+
+class apiSessionAuthenticator
+{
+    private static $cookieFile;
+
+    /**
+     * Initialiser les configurations pour l'authentification
+     */
+    public static function init($loginUrl, $apiBaseUrl, $email, $password)
+    {
+        // Fichier temporaire pour stocker les cookies de session
+        self::$cookieFile = tempnam(sys_get_temp_dir(), 'cookie');
+    }
+
+    public static function checkSession()
+    {
+        if (session::isConnect()) {
+            // L'utilisateur est connecté
+            return json_encode(['authenticated' => true, 'user' => session::getName()]);
+        } else {
+            // L'utilisateur n'est pas connecté
+            return json_encode(['authenticated' => false]);
+        }
+    }
+
+    /**
+     * Authentifier l'utilisateur et maintenir la session PHP via un cookie
+     */
+    public static function authenticate(array $_input) {
+        $ch = curl_init();
+    
+        $data = [
+            'email' => $_input["email"],
+            'password' => $_input["password"],
+        ];
+    
+        curl_setopt($ch, CURLOPT_URL, API_AUTHENT);
+        curl_setopt($ch, CURLOPT_POST, true);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+        // Activer le suivi des redirections
+        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+
+        // Désactiver la vérification SSL (à ne pas utiliser en production)
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+    
+        // Gérer les cookies pour maintenir la session
+        curl_setopt($ch, CURLOPT_COOKIEJAR, self::$cookieFile);
+        curl_setopt($ch, CURLOPT_COOKIEFILE, self::$cookieFile);
+    
+        // Exécuter la requête cURL
+        $response = curl_exec($ch);
+    
+        // Fermer la session cURL
+        curl_close($ch);
+
+        return $response;
+    }
+    
+
+    /**
+     * Faire une requête API authentifiée avec la session PHP active
+     */
+    public static function makeAuthenticatedRequest($endpoint, $method = 'GET', $data = [])
+    {
+        $ch = curl_init();
+
+        $url = DOMAIN_API . $endpoint;
+        curl_setopt($ch, CURLOPT_URL, $url . "/");
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+        // Utiliser les cookies pour maintenir la session
+        curl_setopt($ch, CURLOPT_COOKIEFILE, self::$cookieFile);
+
+        // Configuration des méthodes GET/POST/PUT/DELETE
+        if ($method === 'POST') {
+            curl_setopt($ch, CURLOPT_POST, true);
+            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
+        } elseif ($method === 'PUT') {
+            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
+            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
+        } elseif ($method === 'DELETE') {
+            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
+        }
+
+        $response = curl_exec($ch);
+        curl_close($ch);
+
+        if ($response === false) {
+            throw new Exception('Erreur lors de la requête API.');
+        }
+
+        return json_decode($response, true);
+    }
+
+    /**
+     * Déconnexion (facultatif)
+     */
+    public static function logout()
+    {
+        $ch = curl_init();
+
+        curl_setopt($ch, CURLOPT_URL, API_LOGOUT);
+        curl_setopt($ch, CURLOPT_POST, true);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_COOKIEFILE, self::$cookieFile);
+
+        $response = curl_exec($ch);
+        curl_close($ch);
+
+        // Supprimer le fichier cookie après déconnexion
+        unlink(self::$cookieFile);
+    }
+}

+ 67 - 32
core/class/user.class.php

@@ -82,46 +82,81 @@ class user {
         return (isset($return["googleAuthenticator"])) ? $return["googleAuthenticator"] : 0;
     }
 
+    public static function authenticator(array $_input)
+    {
+        db::query("SELECT id, email, password, prenom, nom, id_type, googleAuthenticator, googleAuthenticatorSecret, actif FROM " . DB_T_USER . " WHERE email = :email AND deleted = 0");
+        db::bind(':email', $_input["email"]);
+        $row = db::single();
+
+        if (isset($row["id"])) {
+            if ($row["actif"] == 0) {
+                return [
+                    "status" => "error",
+                    "type" => "actif"
+                ];
+            } elseif (isset($_input["password"]) and md5($_input["password"]) == $row["password"]) {
+                return [
+                    "status" => "success",
+                    "type" => "authent",
+                    "id" => $row["id"],
+                    "prenom" => $row["prenom"],
+                    "nom" => $row["nom"],
+                    "googleAuthenticator" => $row["googleAuthenticator"],
+                    "idType" => $row["id_type"],
+                    "email" => $row["email"],
+                    "actif" => $row["actif"]
+                ];
+            } else {
+                return [
+                    "status" => "error",
+                    "type" => "authent"
+                ];
+            }
+        } else {
+            return [
+                "status" => "error",
+                "type" => "unknown"
+            ];
+        }
+    }
+
     public static function connect(array $_input) {
-        $return = NULL;
-        if (isset($_input["email"]) AND isset($_input["password"])) {
-            db::query("SELECT id, email, password, prenom, nom, id_type, googleAuthenticator, googleAuthenticatorSecret, actif FROM " . DB_T_USER . " WHERE email = :email AND deleted = 0");
-            db::bind(':email', $_input["email"]);
-            $row = db::single();
-
-            if($row["googleAuthenticator"] == 1 AND DOMAIN_CONTROL != $_SERVER['SERVER_NAME']){
-                if(googleAuthenticator::verifyCode($row["googleAuthenticatorSecret"], $_input["authenticator"], 1) == FALSE){
-                    $row["id"] = NULL;
-                }
+
+        $api = apiSessionAuthenticator::authenticate($_input);
+        $connect = json_decode($api, true);
+
+        if ($connect["googleAuthenticator"] == 1 and DOMAIN_CONTROL != $_SERVER['SERVER_NAME']) {
+            if (googleAuthenticator::verifyCode($connect["googleAuthenticatorSecret"], $_input["authenticator"], 1) == FALSE) {
+                $row["id"] = NULL;
             }
+        }
 
-            if (isset($row["id"])) {
-                if ($row["actif"] == 0) {
+        if (isset($connect["id"])) {
+            if ($connect["status"] == "success") {
+                $_SESSION["user"] = array(
+                    "apiSession" => $connect["session_id"],
+                    "id" => $connect["id"],
+                    "prenom" => $connect["prenom"],
+                    "nom" => $connect["nom"],
+                    "googleAuthenticator" => $connect["googleAuthenticator"],
+                    "idType" => $connect["idType"],
+                    "email" => $connect["email"],
+                    "actif" => $connect["actif"]
+                );
+                self::updateLastConnect($connect["id"]);
+                return TRUE;
+            } else {
+                if ($connect["type"] == "actif") {
                     alert::recError("Votre compte est désactivé");
                     return FALSE;
-                } elseif (isset($_input["password"]) AND md5($_input["password"]) == $row["password"]) {
-                    $_SESSION["user"] = array(
-                        "id" => $row["id"],
-                        "prenom" => $row["prenom"],
-                        "nom" => $row["nom"],
-                        "googleAuthenticator" => $row["googleAuthenticator"],
-                        "idType" => $row["id_type"],
-                        "email" => $row["email"],
-                        "actif" => $row["actif"]
-                    );
-                    self::updateLastConnect($row["id"]);
-                    return TRUE;
-                } else {
+                } elseif ($connect["type"] == "authent") {
                     alert::recError("Erreur d'authentification");
-                    return FALSE; 
+                    return FALSE;
+                } elseif ($connect["type"] == "unknown") {
+                    alert::recError("Erreur d'authentification");
+                    return FALSE;
                 }
-            } else {
-                alert::recError("Erreur d'authentification");
-                return FALSE; 
             }
-        } else {
-            alert::recError("Erreur d'authentification");
-            return FALSE; 
         }
     }
     

+ 44 - 0
public-cms/api/authenticator/index.php

@@ -0,0 +1,44 @@
+<?php
+
+session_start(); 
+
+require_once "../../../env.inc.php"; 
+require_once DOCUMENT_ROOT."/access.inc.php";
+require_once DOCUMENT_ROOT."/conf.inc.php";
+require_once DIR_PHP_LAYOUTS . "header.php";
+
+if(core::ifPost("email") AND core::ifPost("password")){
+    $connect = user::authenticator(core::getPost());
+
+    if($connect["status"] == "success"){
+        historique::recRef("/api/authenticator/");
+        historique::add(array(
+            "idType" => historique::getIdRef("CONNEXION"),
+            "idUser" => $connect["id"],
+            "idPage" => historique::getIdRef("/api/authenticator/"),
+            "log" => $_SERVER['REMOTE_ADDR']
+        ));
+
+        // Réponse JSON en cas de succès
+        echo json_encode([
+            "status" => $connect["status"],
+            "message" => "Login successful",
+            "session_id" => session_id(),
+            "type" => $connect["type"],
+            "id" => $connect["id"],
+            "prenom" => $connect["prenom"],
+            "nom" => $connect["nom"],
+            "googleAuthenticator" => $connect["googleAuthenticator"],
+            "idType" => $connect["idType"],
+            "email" => $connect["email"]
+        ]);
+    }
+    else {
+        // Authentification échouée
+        http_response_code(401); // Code 401 Unauthorized
+        echo json_encode([
+            "status" => "error",
+            "message" => "Invalid email or password"
+        ]);
+    }
+}

+ 12 - 0
public-cms/api/checkSession/index.php

@@ -0,0 +1,12 @@
+<?php
+
+session_start(); 
+
+require_once "../../../env.inc.php"; 
+require_once DOCUMENT_ROOT."/access.inc.php";
+require_once DOCUMENT_ROOT."/conf.inc.php";
+require_once DIR_PHP_LAYOUTS . "header.php";
+
+if ($_SERVER['REQUEST_METHOD'] === 'GET') {
+    echo apiSessionAuthenticator::checkSession();
+}

+ 0 - 0
public-cms/api/index.html


+ 0 - 0
public-cms/css/index.html


+ 0 - 0
public-cms/img/index.html


+ 0 - 0
public-cms/libs/index.html


+ 32 - 0
public-events/test.php

@@ -5,3 +5,35 @@ $_SESSION["debug"] = 1;
 
 ini_set('display_errors', 1);
 error_reporting(E_ALL);
+
+function checkAuthenticationOnServerA()
+{
+    // URL de l'endpoint de vérification de session sur le serveur A
+    $url = 'https://local.cms.cse-invent.com/api/checkSession/';
+
+    // Initialiser cURL
+    $ch = curl_init($url);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    
+    // Optionnel : si vous devez envoyer les cookies pour vérifier la session
+    // curl_setopt($ch, CURLOPT_COOKIEFILE, '/path/to/cookie_file');
+
+    // Exécuter la requête
+    $response = curl_exec($ch);
+    curl_close($ch);
+
+    // Décoder la réponse JSON
+    $result = json_decode($response, true);
+
+    if ($result && isset($result['authenticated'])) {
+        if ($result['authenticated']) {
+            return "L'utilisateur est connecté.";
+        } else {
+            return "L'utilisateur n'est pas connecté.";
+        }
+    }
+
+    return "Erreur lors de la vérification de l'état de la session.";
+}
+
+checkAuthenticationOnServerA();