From f660007befa0ab53a340b8eca1a6d9e880f1c32d Mon Sep 17 00:00:00 2001
From: steel <mael.acier@ensiie.fr>
Date: Sat, 18 Jan 2025 00:05:02 +0100
Subject: [PATCH] update README and GitHub integration for AriseID Connect; add
 .gitignore for VSCode

---
 .gitignore |   1 +
 README.md  |   2 +
 github.php | 156 ++++++++++++++++++++++++++---------------------------
 3 files changed, 81 insertions(+), 78 deletions(-)
 create mode 100644 .gitignore

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..722d5e7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.vscode
diff --git a/README.md b/README.md
index 9eb44de..9c8a85f 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
 # Sample OAuth 2.0 Clients
 
+https://github.com/aaronpk/sample-oauth2-client
+
 Sample OAuth 2.0 clients using the GitHub and Google APIs
 
 Read more info in the book [OAuth 2.0 Simplified](https://oauth2simplified.com)
diff --git a/github.php b/github.php
index b248f8c..52a1270 100644
--- a/github.php
+++ b/github.php
@@ -1,73 +1,66 @@
 <?php
-error_reporting(E_ALL);
-ini_set('display_errors', '1');
-if(!defined('STDOUT')) define('STDOUT', fopen('php://stdout', 'wb'));
 
-// Fill these out with the values you got from Github
-$githubClientID = '6a028017-3100-44c6-a837-9752c3b9b8c4';
-$githubClientSecret = 'kazgNEQ26MstoIELYeFLftkTK_';
+// Remplir ces champs avec les valeurs obtenues sur AriseID Connect
+$clientId = 'f97b146f-121a-4400-a79c-7c2ecbbd87f8';
+$clientSecret = 'y6hsryRm6P~QSen~Xs0UtvkEcK';
 
-// This is the URL we'll send the user to first to get their authorization
-$authorizeURL = 'https://oidc.iiens.net/oauth2/auth';
+$oauthURLBase = 'http://oidc.127.0.0.1.nip.io:4444';
+// L'URL à laquelle on enverra d'abord l'utilisateur pour obtenir son autorisation
+$authorizeURL = "{$oauthURLBase}/oauth2/auth";
+// Le point d'accès à partir duquel notre serveur demandera un jeton d'accès
+$tokenURL = "{$oauthURLBase}/oauth2/token";
 
-// This is the endpoint our server will request an access token from
-$tokenURL = 'https://oidc.iiens.net/oauth2/token';
+// L'URL racine à utiliser pour effectuer des demandes d'API authentifiées
+$apiURLBase = 'http://api.127.0.0.1.nip.io:5000';
 
-// This is the Github base URL we can use to make authenticated API requests
-$apiURLBase = 'https://api.iiens.net/';
+// L'URL de ce script, utilisé comme URL de redirection
+$baseURL = 'http://php.127.0.0.1.nip.io:8000';
 
-// The URL for this script, used as the redirect URL
-// $baseURL = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
-$baseURL = 'http://localhost:8000/';
-
-// Start a session so we have a place to store things between redirects
+// On lance une session afin d'avoir un endroit où stocker les données entre les redirections
 session_start();
 
-echo '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css" >';
-
-// Start the login process by sending the user
-// to Github's authorization page
-if(isset($_GET['action']) && $_GET['action'] == 'login') {
+// Commence le processus de connexion en envoyant l'utilisateur
+// à la page d'autorisation d'AriseID Connect
+if (isset($_GET['action']) && $_GET['action'] == 'login') {
   unset($_SESSION['access_token']);
 
-  // Generate a random hash and store in the session
+  // Génère un hash aléatoire et le stocke dans la session
   $_SESSION['state'] = bin2hex(random_bytes(16));
 
-  $params = array(
+  $params = [
     'response_type' => 'code',
-    'client_id' => $githubClientID,
+    'client_id' => $clientId,
     'redirect_uri' => $baseURL,
     'scope' => 'profile',
     'state' => $_SESSION['state']
-  );
+  ];
 
-  // Redirect the user to Github's authorization page
-  header('Location: '.$authorizeURL.'?'.http_build_query($params));
+  // Redirige l'utilisateur vers la page d'autorisation d'AriseID Connect
+  header('Location: ' . $authorizeURL . '?' . http_build_query($params));
   die();
 }
 
-if(isset($_GET['action']) && $_GET['action'] == 'logout') {
+if (isset($_GET['action']) && $_GET['action'] == 'logout') {
   unset($_SESSION['access_token']);
-  header('Location: '.$baseURL);
+  header("Location: $baseURL");
   die();
 }
 
-// When Github redirects the user back here,
-// there will be a "code" and "state" parameter in the query string
-if(isset($_GET['code'])) {
-  // Verify the state matches our stored state
-  if(!isset($_GET['state'])
-    || $_SESSION['state'] != $_GET['state']) {
+// Quand AriseID Connect redirige l'utilisateur ici, il y aura
+// un paramètre "code" et "state" dans la chaîne de requête
+if (isset($_GET['code'])) {
+  // Certifie que l'état correspond à l'état stocké
+  if (!isset($_GET['state']) || $_SESSION['state'] != $_GET['state']) {
 
-    header('Location: ' . $baseURL . '?error=invalid_state');
+    header("Location: $baseURL?error=invalid_state");
     die();
   }
 
-  // Exchange the auth code for an access token
+  // Échange le code d'authentification contre un jeton d'accès
   $query_data = array(
     'grant_type' => 'authorization_code',
-    'client_id' => $githubClientID,
-    'client_secret' => $githubClientSecret,
+    'client_id' => $clientId,
+    'client_secret' => $clientSecret,
     'redirect_uri' => $baseURL,
     'code' => $_GET['code']
   );
@@ -81,54 +74,23 @@ if(isset($_GET['code'])) {
 
   $_SESSION['access_token'] = $token['access_token'];
 
-  header('Location: ' . $baseURL);
-  die();
-}
-
-var_dump($_SESSION['access_token']);
-
-if(isset($_GET['action']) && $_GET['action'] == 'profile') {
-  if(!empty($_SESSION['access_token'])) {
-    $query = '{"query":"query { profile { id name givenName familyName nickname birthdate email schoolLogin promotion groups { role group { name } } } }"}';
-    $profile = apiRequest($query);
-    echo '<pre>';
-    json_encode($profile);
-    echo '</pre>';
-  } else {
-    echo '<h3>Not logged in</h3>';
-    echo '<p><a href="?action=login">Log In</a></p>';
-  }
-}
-
-// If there is an access token in the session
-// the user is already logged in
-if(!isset($_GET['action'])) {
-  if(!empty($_SESSION['access_token'])) {
-    echo '<h3>Logged In</h3>';
-    echo '<p><a href="?action=profile">View Profile</a></p>';
-    echo '<p><a href="?action=logout">Log Out</a></p>';
-  } else {
-    echo '<h3>Not logged in</h3>';
-    echo '<p><a href="?action=login">Log In</a></p>';
-  }
+  header("Location: $baseURL");
   die();
 }
 
-
-// This helper function will make API requests to GitHub, setting
-// the appropriate headers GitHub expects, and decoding the JSON response
-function apiRequest($query) {
+function graphql_request($query)
+{
   global $apiURLBase;
-  $endpoint = $apiURLBase . 'graphql/v0';
+  $endpoint = "$apiURLBase/graphql/v0";
 
-  $headers = array();
+  $headers = [];
   $headers[] = 'Content-Type: application/json';
-  $headers[] = 'Authorization: Bearer '. $_SESSION['access_token'];
+  $headers[] = 'Authorization: Bearer ' . $_SESSION['access_token'];
 
   $ch = curl_init();
 
   curl_setopt($ch, CURLOPT_URL, $endpoint);
-  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
+  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
@@ -141,3 +103,41 @@ function apiRequest($query) {
 
   return json_decode($response, true);
 }
+
+$profile_query = '{"query":"{ profile { id name civilName givenName middleName forenames familyName nickname preferredUsername preferredNickname gender birthdate profile picture { url } website zoneinfo locale updatedAt promotion year groups { role group { name } } } }"}';
+
+?>
+<html lang="fr">
+
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1">
+  <meta name="color-scheme" content="light dark">
+  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.classless.min.css">
+  <title>OAuth2 Demo</title>
+</head>
+
+<body>
+  <main>
+    <?php if (empty($_SESSION['access_token'])): ?>
+      <h3>Non connecté</h3>
+      <a href="?action=login"><button>Se connecter</button></a>
+    <?php else: ?>
+      <!-- S'il y a un jeton d'accès dans la session l'utilisateur est connecté -->
+      <?php if (isset($_GET['action']) && $_GET['action'] == 'profile'): ?>
+        <p><a href=".">Retour</a></p>
+        <pre>
+          <code>
+<?php echo json_encode(graphql_request($profile_query), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); ?>
+          </code>
+        </pre>
+      <?php endif; ?>
+
+      <?php if (!isset($_GET['action'])): ?>
+        <h3>Connecté</h3>
+        <p><a href="?action=profile">Voir le profil</a></p>
+        <a href="?action=logout"><button>Se déconnecter</button></a>
+      <?php endif; ?>
+    <?php endif; ?>
+  </main>
+</body>
\ No newline at end of file
-- 
GitLab