Browse Source

cleans up and documents ot_connect

Olivier Massot 5 years ago
parent
commit
8c8e6c5a75

+ 0 - 1
ot_connect/.gitignore

@@ -1 +0,0 @@
-/vendor/

+ 18 - 7
ot_connect/Classes/Service/OtAuthenticationService.php

@@ -1,17 +1,20 @@
 <?php
 namespace Opentalent\OtConnect\Service;
 
+use DateTime;
 use GuzzleHttp\Client;
 use GuzzleHttp\Cookie\CookieJar;
 use GuzzleHttp\Cookie\SetCookie;
+use GuzzleHttp\Exception\GuzzleException;
 use GuzzleHttp\Exception\RequestException;
+use TYPO3\CMS\Core\Crypto\Random;
 use TYPO3\CMS\Core\Database\ConnectionPool;
 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
 use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;
 
 /**
- * Service "OpenID Authentication" for the "openid" extension.
+ * Authentication service based on the Opentalent API.
  * See the README for more
  */
 class OtAuthenticationService extends AbstractAuthenticationService
@@ -36,7 +39,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
     ];
 
     /**
-     * The min delay to wait before the getUser method may regenerate the user's data in DB (seconds)
+     * The time in seconds during which the user's data in DB won't be re-updated after the last successful update
      * Set it to 0 to disable the delay
      */
     CONST USER_UPDATE_DELAY = 300;
@@ -152,9 +155,10 @@ class OtAuthenticationService extends AbstractAuthenticationService
     }
 
     /**
-     * Return the name of the user currently authenticated on the API side, or null if no user is logged in
+     * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
      *
      * @return string|null
+     * @throws GuzzleException
      */
     protected function getAuthenticatedUsername() {
 
@@ -175,7 +179,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
     }
 
     /**
-     * Update the guzzle cookie jar with the current ones
+     * Update the guzzle cookie jar with the current session's ones
      */
     private function fillCookieJar() {
 
@@ -198,6 +202,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
      * @param string $username
      * @param string $password
      * @return bool     Returns true if the api accepted the login request
+     * @throws GuzzleException
      */
     protected function logUser($username, $password) {
 
@@ -258,11 +263,11 @@ class OtAuthenticationService extends AbstractAuthenticationService
         $q = $connection->select(['tx_otconnect_generationDate'], 'fe_users', ['username' => $username]);
         $strGenDate = $q->fetch(3)[0];
 
-        $genDate = \DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
+        $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
         if ($genDate == null) {
             return true;
         }
-        $now = new \DateTime();
+        $now = new DateTime();
         $diff = $now->getTimestamp() - $genDate->getTimestamp();
 
         return ($diff > self::USER_UPDATE_DELAY);
@@ -289,7 +294,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
         $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('fe_users');
 
         // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
-        $randomStr = (new \TYPO3\CMS\Core\Crypto\Random)->generateRandomHexString(10);
+        $randomStr = (new Random)->generateRandomHexString(10);
 
         // Front-end user
         $fe_row = [
@@ -360,6 +365,8 @@ class OtAuthenticationService extends AbstractAuthenticationService
             $response = $this->client->request('GET', self::GET_USER_DATA_URI, ['cookies' => $this->jar]);
         } catch (RequestException $e) {
             return [];
+        } catch (GuzzleException $e) {
+            return [];
         }
         return json_decode($response->getBody(), true);
     }
@@ -371,6 +378,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
      *
      * @param array $user Data of user.
      * @return int        Code that shows if user is really authenticated.
+     * @throws GuzzleException
      */
     public function authUser(array $user)
     {
@@ -423,6 +431,8 @@ class OtAuthenticationService extends AbstractAuthenticationService
 
         } catch (RequestException $e) {
             return false;
+        } catch (GuzzleException $e) {
+            return false;
         }
     }
 
@@ -430,6 +440,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
      * Unset a cookie by reducing its expiration date
      *
      * @param string $name
+     * @return bool
      */
     protected function unset_cookie(string $name) {
         $res = setcookie($name, '', time() - 1, '/', self::COOKIE_DOMAIN);

+ 0 - 101
ot_connect/Configuration/ExtensionBuilder/settings.yaml

@@ -1,101 +0,0 @@
-#
-# Extension Builder settings for extension ot_connect
-# generated 2020-04-22T11:02:00Z
-#
-# See http://www.yaml.org/spec/1.2/spec.html
-#
-
----
-
-###########    Overwrite settings  ###########
-#
-# These settings only apply, if the roundtrip feature of the extension builder
-# is enabled in the extension manager
-#
-# Usage:
-# nesting reflects the file structure
-# a setting applies to a file or recursive to all files and subfolders
-#
-# merge:
-#   means for classes: All properties ,methods and method bodies
-#   of the existing class will be modified according to the new settings
-#   but not overwritten
-#
-#   for locallang xlf files: Existing keys and labels are always
-#   preserved (renaming a property or DomainObject will result in new keys and new labels)
-#
-#   for other files: You will find a Split token at the end of the file
-#   see: \EBT\ExtensionBuilder\Service\RoundTrip::SPLIT_TOKEN
-#
-#   After this token you can write whatever you want and it will be appended
-#   everytime the code is generated
-#
-# keep:
-#   files are never overwritten
-#   These settings may break the functionality of the extension builder!
-#   Handle with care!
-#
-#
-
-############  extension settings  ##############
-
-overwriteSettings:
-  Classes:
-    Controller: merge
-    Domain:
-      Model: merge
-      Repository: merge
-
-  Configuration:
-    #TCA merge not possible - use overrides directory
-    #TypoScript: keep
-
-  Resources:
-    Private:
-      #Language: merge
-      #Templates: keep
-
-  user_extension.svg: keep
-
-#  ext_localconf.php: merge
-
-#  ext_tables.php: merge
-
-#  ext_tables.sql: merge
-
-## use static date attribute in xliff files ##
-#staticDateInXliffFiles: 2020-04-22T11:02:00Z
-
-## skip docComment (license header) ##
-#skipDocComment
-
-## list of error codes for warnings that should be ignored ##
-#ignoreWarnings:
-  #503
-
-######### settings for classBuilder #############################
-#
-# here you may define default parent classes for your classes
-# these settings only apply for new generated classes
-# you may also just change the parent class in the generated class file.
-# It will be kept on next code generation, if the overwrite settings
-# are configured to merge it
-#
-#################################################################
-
-classBuilder:
-
-  Controller:
-    parentClass: \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
-
-  Model:
-    AbstractEntity:
-      parentClass: \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
-
-    AbstractValueObject:
-      parentClass: \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject
-
-  Repository:
-    parentClass: \TYPO3\CMS\Extbase\Persistence\Repository
-
-  setDefaultValuesForClassProperties: true

+ 0 - 39
ot_connect/ExtensionBuilder.json

@@ -1,39 +0,0 @@
-{
-    "modules": [],
-    "properties": {
-        "backendModules": [],
-        "description": "Authentification Opentalent pour Typo3 ",
-        "emConf": {
-            "category": "services",
-            "custom_category": "",
-            "dependsOn": "typo3 => 8.7.0-8.7.99\n",
-            "disableLocalization": false,
-            "disableVersioning": false,
-            "skipGenerateDocumentationTemplate": true,
-            "sourceLanguage": "en",
-            "state": "alpha",
-            "targetVersion": "8.7.0-8.7.99",
-            "version": "0.1.0"
-        },
-        "extensionKey": "ot_connect",
-        "name": "OtConnect",
-        "originalExtensionKey": "",
-        "originalVendorName": "",
-        "persons": [
-            {
-                "company": "Opentalent",
-                "email": "olivier.massot@2iopenservice.fr",
-                "name": "Olivier Massot",
-                "role": "Developer"
-            }
-        ],
-        "plugins": [],
-        "vendorName": "Opentalent"
-    },
-    "wires": [],
-    "log": {
-        "last_modified": "2020-04-22 11:02",
-        "extension_builder_version": "8.10.4",
-        "be_user": " (1)"
-    }
-}

+ 12 - 12
ot_connect/Readme.md

@@ -6,7 +6,7 @@ Extension d'authentification typo3.
 |---|---|
 | Extension key | ot_connect |
 | Vendor | Opentalent |
-| Nom | OtConnect |
+| Nom | OtConnect |
 
 Le rôle de cette extension est de fournir une authentification et une session unique pour les utilisateurs Opentalent, 
 qu'ils se rendent sur l'application Opentalent, sur le frontend du site de leur(s) structure(s), ou sur le backend TYPO3 
@@ -35,17 +35,17 @@ Un service d'authentification doit hériter de la classe `TYPO3\CMS\Sv\AbstractA
 De plus, le service doit être enregistré dans `ext_localconf.php` via la méthode `\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService`.
 A cette étape, on peut lui donner des rôles (authentification backend et/ou frontend, par exemple).
 
-> **IMPORTANT**: quelle que soit la méthode d'authentif, les users backend et frontend 
->doivent avoir leurs enregistrements dans la base TYPO3 (tables `fe_users` et `be_users`)
+> **IMPORTANT** : quelle que soit la méthode d'authentification, les users backend et frontend 
+>doivent avoir leurs enregistrements dans la base TYPO3 (tables `fe_users` et `be_users`)
 
 ### Requêtes d'authentification
 
-Typo3 reconnait une requête d'authentification de la manière suivante:
+Typo3 reconnait une requête d'authentification de la manière suivante :
 
 * La requête a un paramètre `logintype` dont la valeur est `login`: c'est une requête d'authentification Frontend
 * La requête a un paramètre `login_status` dont la valeur est `login`: c'est une requête d'authentification Backend
 
-Voilà les formulaires minimaux pour poster une demande d'authentification:
+Voilà les formulaires minimaux pour poster une demande d'authentification :
 
     <-- FrontEnd -->
     <form action="" method="POST" enctype="multipart/form-data" >
@@ -68,7 +68,7 @@ Voilà les formulaires minimaux pour poster une demande d'authentification:
 ### Base de données
 
 Les utilisateurs **Backend** doivent avoir une ligne correspondante dans la table `be_users` de la base TYPO3.
-Ils doivent avoir a minima les champs suivants renseignés : 
+Ils doivent avoir a minima les champs suivants renseignés : 
 
 * `username`
 * `password`: si le mot de passe n'est pas utilisé pour authentifier l'utilisateur, 
@@ -76,12 +76,12 @@ par exemple parce qu'une API l'a déjà authentifié en amont, mettre une random
 * `usergroup`: le user doit appartenir à un groupe existant (cf. `be_groups`), sauf s'il est admin (champs `admin` = 1)
 
 Les utilisateurs **Frontend** doivent avoir une ligne correspondante dans la table `fe_users` de la base TYPO3.
-Ils doivent avoir a minima les champs suivants renseignés : 
+Ils doivent avoir a minima les champs suivants renseignés : 
 
 * `username`
-* `password`: si le mot de passe n'est pas utilisé pour authentifier l'utilisateur, 
+* `password` : si le mot de passe n'est pas utilisé pour authentifier l'utilisateur, 
 par exemple parce qu'une API l'a déjà authentifié en amont, mettre une random string
-* `usergroup`: le user doit appartenir à un groupe existant (cf. `be_groups`)
+* `usergroup` : le user doit appartenir à un groupe existant (cf. `be_groups`)
 
 ### Plus d'infos
 
@@ -90,9 +90,9 @@ par exemple parce qu'une API l'a déjà authentifié en amont, mettre une random
 
 ## Fonctionnement de l'extension OtConnect
 
-Un service `OtAuthenticationService` est créé et enregistré avec les caractéritiques suivantes:
+Un service `OtAuthenticationService` est créé et enregistré avec les caractéristiques suivantes :
  
-* `'subtype' => 'getUserFE,authUserFE,getUserBE,authUserBE'`: le service peut récupérer les infos des users 
+* `'subtype' => 'getUserFE,authUserFE,getUserBE,authUserBE'` : le service peut récupérer les infos des users 
 et les authentifier, à la fois pour le Frontend (FE) et pour le Backend (BE)
 * `'priority' => 80`: la priorité est fixée à 80, ce qui place le service en amont des services Typo3.
 
@@ -101,7 +101,7 @@ Enfin, la variable de configuration `FE_fetchUserIfNoSession` force l'appel à l
 
 Voilà les différents scénarios pour un utilisateur nommé Bob. 
 
-> Les cas suivants sont donnés pour le Frontend, mais ils sont identiques pour le Backend à deux différences près:
+> Les cas suivants sont donnés pour le Frontend, mais ils sont identiques pour le Backend à deux différences près :
 > * Le user doit saisir son login / mdp (pas d'auto-log)
 > * Seuls les utilisateurs ayant la propriété `admin_access` à true ont accès au Backend.
 

+ 2 - 2
ot_connect/composer.json

@@ -9,7 +9,7 @@
         }
     ],
     "require": {
-        "typo3/cms-core": "^8.7.1"
+        "typo3/cms-core": "^8.7.1 || ^10.4"
     },
     "autoload": {
         "psr-4": {
@@ -25,4 +25,4 @@
         "ot_connect": "self.version",
         "typo3-ter/ot-connect": "self.version"
     }
-}
+}

+ 0 - 2
ot_connect/ext_emconf.php

@@ -3,8 +3,6 @@
 /***************************************************************
  * Extension Manager/Repository config file for ext: "ot_connect"
  *
- * Auto generated by Extension Builder 2020-04-22
- *
  * Manual updates:
  * Only the data in the array - anything else is removed by next write.
  * "version" and "dependencies" must not be touched!

+ 0 - 16
ot_connect/ext_tables.php

@@ -1,16 +0,0 @@
-<?php
-defined('TYPO3_MODE') || die('Access denied.');
-
-if (TYPO3_MODE === 'BE') {
-
-//    // Add field to setup module
-//    $GLOBALS['TYPO3_USER_SETTINGS']['columns']['tx_otconnect_otconnect'] = [
-//        'type' => 'user',
-//        'table' => 'be_users',
-//        'label' => 'LLL:EXT:ot_connect/Resources/Private/Language/locallang_db.xlf:_MOD_user_setup.tx_openid_openid',
-//        'csh' => 'tx_otconnect_otconnect',
-//        'userFunc' => \Opentalent\OtConnect\OtConnectModuleSetup::class . '->renderAuthentication',
-//        'access' => \Opentalent\OtConnect\OtConnectModuleSetup::class
-//    ];
-//    \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addFieldsToUserSettings('tx_otconnect_otconnect', 'after:password2');
-}

+ 2 - 0
ot_connect/ext_tables.sql

@@ -1,3 +1,5 @@
+# ext_tables.sql contient les directives permettant d ajouter des tables et champs à la DB
+
 #
 # Table structure for table 'be_users'
 #

+ 1 - 1
ot_templating/ext_tables.sql

@@ -1,4 +1,4 @@
-# ext_localconf.sql contient les directives permettant d ajouter des tables et champs à la DB
+# ext_tables.sql contient les directives permettant d ajouter des tables et champs à la DB
 
 #
 # Table structure for table 'pages'