From f380402a17ada90588f2d73f164a8957b668f2f9 Mon Sep 17 00:00:00 2001
From: Guillaume Vagner <guillaume.vagner@supelec.fr>
Date: Sun, 24 Feb 2019 14:15:55 +0100
Subject: [PATCH] auto reload of token

---
 requests.js | 46 +++++++++++++++++++++++++++++++---------------
 schedule.js |  2 +-
 telegram.js | 11 +++++------
 3 files changed, 37 insertions(+), 22 deletions(-)

diff --git a/requests.js b/requests.js
index 18ba9dd..ad5e031 100644
--- a/requests.js
+++ b/requests.js
@@ -1,3 +1,5 @@
+// REQUESTS.JS : Envoi de requête HTTP vers l'OAuth de VR et vers LinkCS 
+
 // Modules extérieurs
 const rp = require('request-promise');
 
@@ -7,22 +9,27 @@ var { modifyChan, getChanByState } = require('./connection-db');
 // Configurations
 const config = require('./config');
 
-// Fonction d'envoi d'une requête au GraphQL de LinkCS 
-async function sendRequest(req, token) {
-    // ici faire le refresh token
-    const options = {
-        headers: { 'Authorization': `Bearer ${token}` },
-        json: true
-    }
-    const url = 'https://gateway.linkcs.fr/v1/graphql';
 
-    return rp(`${url}?query=${req}`, options)
+
+
+// Fonction d'envoi d'une requête au GraphQL de LinkCS 
+async function sendRequest(req, chan) {
+    // A chaque requête vérifie si le token est encore valable, sinon va en récupérer un nouveau
+    return getNewTokenIfNecessary(chan).then(chan => {
+        const options = {
+            headers: { 'Authorization': `Bearer ${chan.token}` },
+            json: true
+        }
+        const url = 'https://gateway.linkcs.fr/v1/graphql';
+    
+        return rp(`${url}?query=${req}`, options)    
+    })
 }
 
 // Récupération de tous les personnes et leurs assos ayant leur anniversaire
-function getBirthdays(token) {
+function getBirthdays(chan) {
     const req = 'query getUsersBirthday {users: usersBirthday {    ...userData}}fragment userData on User {firstName  lastName  roles {sector {composition {association {id}}}}}'
-    return sendRequest(req, token).then(body => {
+    return sendRequest(req, chan).then(body => {
         const users = [];
         body.data.users.forEach(user => {
             use = {};
@@ -38,18 +45,18 @@ function getBirthdays(token) {
 }
 
 // Récupération de la recherche de groupe
-function searchGroups(token, term) {
+function searchGroups(chan, term) {
     const req = `query {searchAssociations(term: "${term}") {id name code}}`
-    return sendRequest(req, token).then(body => {
+    return sendRequest(req, chan).then(body => {
         if (!body.data) return;
         return body.data.searchAssociations;
     }).catch(err => { console.error(err) })
 }
 
 // Récupération du nom de l'asso ayant l'ID donnée
-function getGroupById(token, id) {
+function getGroupById(chan, id) {
     const req = `query {association(id: ${id}) {name}}`
-    return sendRequest(req, token).then(body => {
+    return sendRequest(req, chan).then(body => {
         if (!body.data) return;
         return body.data.association.name;
     }).catch(err => { console.error(err) })
@@ -111,4 +118,13 @@ function getNewToken(chan) {
     })
 };
 
+// Récupère un nouveau token que si besoin
+function getNewTokenIfNecessary(chan) {
+    if (chan.expiration*1000 < Date.now()) {
+        return getNewToken(chan)
+    } else {
+        return Promise.resolve(chan)
+    }
+}
+
 module.exports = { getBirthdays, sendRequest, searchGroups, getGroupById, getFirstToken, getNewToken };
\ No newline at end of file
diff --git a/schedule.js b/schedule.js
index 998cf29..964bd43 100644
--- a/schedule.js
+++ b/schedule.js
@@ -17,7 +17,7 @@ function addSchedule(chan, time, bot) {
         schedules[chan.chatId] = schedule.scheduleJob({ hour: hour, minute: minute }, function () {
             return getNewToken(chan).then(chan => {
                 return Promise.all([
-                    getBirthdays(chan.token),
+                    getBirthdays(chan),
                     getGroups(chan.chatId)
                 ])
             }).then(([users, groups]) => {
diff --git a/telegram.js b/telegram.js
index 9503c51..5e93a94 100644
--- a/telegram.js
+++ b/telegram.js
@@ -45,7 +45,6 @@ bot.onText(/\/reset/, msg => {
     })
 })
 
-
 // Si rien n'a été fait avant, propose un lien de connexion à l'OAuth2 de VR
 bot.onText(/\/connect/, (msg, _) => {
     const chatId = msg.chat.id;
@@ -98,7 +97,7 @@ bot.onText(/\/allbirthdays/, msg => {
     const chatId = msg.chat.id;
     // recherche du token du chan actuel
     getChanByChatId(chatId).then(chan => {
-        return getBirthdays(chan.token)
+        return getBirthdays(chan)
     }).then(users => {
         var msg = '**Joyeux anniversaire** à :\n'
         users.forEach(user => {
@@ -114,7 +113,7 @@ bot.onText(/\/birthdays/, msg => {
     // recherche du token du chan actuel
     getChanByChatId(chatId).then(chan => {
         return Promise.all([
-            getBirthdays(chan.token),
+            getBirthdays(chan),
             getGroups(chatId),
         ])
     }).then(([users, groups]) => {
@@ -134,7 +133,7 @@ bot.onText(/\/search (.+)/, (msg, match) => {
     const chatId = msg.chat.id;
     const research = match[1];
     getChanByChatId(chatId).then(chan => {
-        return searchGroups(chan.token, research)
+        return searchGroups(chan, research)
     }).then(groups => {
         if (groups.length == 0) return bot.sendMessage(chatId, 'Pas de groupe à ce nom...');
         var resp = 'Voici les différentes associations. Faites /add XXXX pour ajouter les anniversaires de ses membres. ';
@@ -154,7 +153,7 @@ bot.onText(/\/add (.+)/, (msg, match) => {
     getChanByChatId(chatId).then(chan => {
         const id = parseInt(match[1].split(' ')[0]);
         return Promise.all([
-            getGroupById(chan.token, id),
+            getGroupById(chan, id),
             getGroups(chatId),
             id
         ]);
@@ -175,7 +174,7 @@ bot.onText(/\/del (.+)/, (msg, match) => {
     getChanByChatId(chatId).then(chan => {
         const id = parseInt(match[1].split(' ')[0]);
         return Promise.all([
-            getGroupById(chan.token, id),
+            getGroupById(chan, id),
             getGroups(chatId),
             id
         ]);
-- 
GitLab