Commit 2977b484 authored by Eric Seigne's avatar Eric Seigne
Browse files

avancees sur la gestion multicomptes

parent d23efe31
......@@ -2,7 +2,7 @@
* (c) Éric Seigne <eric.seigne@cap-rel.fr> - 2019-2020 - GNU AGPLv3
* full source code in src/ subfolder, this file is minifyed
*/
var globalAppVersion="1.8.2";var globalDevMode=true;var globalMyCamera;var globalpictureSource;var globaldestinationType;var globalNetworkResponse=Date.now();var globalCurrentPage="";var globalCurrentTitle="";var globalTenMinuts=60*10*1000;var globalCompatibleWithAPIVersion=4;var globalDoliScanDomain="";var globalLastInsertId="";var globalSyncInProgress=false;var globalPictureFileName="";var globalPicturesAvailable=[];var globalSyncObject=[];var dataLDF="";var dataIK="";var globalMyNavigator=undefined;var globalResumable=undefined;var globalProgressBar=undefined;var globalTypeFrais="";var globalVehiculeEd=undefined;var globalSrvKeys=['email','api_token','firstname','name','adresse','cp','ville','pays','send_copy_to','compta_email','compta_ik','compta_peage','compta_hotel','compta_train','compta_carburant','compta_taxi','compta_restauration','compta_divers','compta_compteperso','compta_tvadeductible','official_app_version','official_app_message','mode_simple','compta_tva_tx1','compta_tva_tx2','compta_tva_tx3','compta_tva_tx4'];function errorHandlerCustomFile(title,message){myDebug('errorHandlerCustomFile : '+title+' -- message follow:');myDebug(message);}
var globalAppVersion="1.8.2";var globalDevMode=false;var globalMyCamera;var globalpictureSource;var globaldestinationType;var globalNetworkResponse=Date.now();var globalCurrentPage="";var globalCurrentTitle="";var globalTenMinuts=60*10*1000;var globalCompatibleWithAPIVersion=4;var globalDoliScanDomain="";var globalLastInsertId="";var globalSyncInProgress=false;var globalPictureFileName="";var globalPicturesAvailable=[];var globalSyncObject=[];var dataLDF="";var dataIK="";var globalMyNavigator=undefined;var globalResumable=undefined;var globalProgressBar=undefined;var globalTypeFrais="";var globalVehiculeEd=undefined;var loginAPIKeyErrorInProgress=false;var globalSrvKeys=['email','api_token','firstname','name','adresse','cp','ville','pays','send_copy_to','compta_email','compta_ik','compta_peage','compta_hotel','compta_train','compta_carburant','compta_taxi','compta_restauration','compta_divers','compta_compteperso','compta_tvadeductible','official_app_version','official_app_message','mode_simple','compta_tva_tx1','compta_tva_tx2','compta_tva_tx3','compta_tva_tx4'];function errorHandlerCustomFile(title,message){myDebug('errorHandlerCustomFile : '+title+' -- message follow:');myDebug(message);}
function loadCustomCSS(){if((typeof cordova=='undefined')||(cordova===null)||(cordova=="")){return;}
if((typeof cordova.file=='undefined')||(cordova.file===null)||(cordova.file=="")){return;}
if((typeof cordova.file.cacheDirectory=='undefined')||(cordova.file.cacheDirectory===null)||(cordova.file.cacheDirectory=="")){return;}
......@@ -105,6 +105,9 @@ html+="</ul>";html+="<ons-button modifier='material large' onclick='createIK(\""
$(formField).append(html);}
function onErrorAgendaIK(msg){hideWait();ons.notification.alert("Erreur d'accès à l'agenda"+JSON.stringify(msg),{title:"Erreur"});}
function createIK(titre,ladate,message,arrivee,depart){myDebug("createIK : "+titre);dataIK={label:titre+" "+message,ladate:ladate,arrivee:arrivee,depart:depart,};myDebug("createIK : avant le Goto : "+JSON.stringify(dataIK));gotoPage("frais-ik.html",true);}
function makeOneAccount(id,title,mail){let html="";html="<ons-row>\n";html+=" <ons-col>\n";html+=" <ons-card>\n";html+=" <ons-row>\n";html+=" <ons-col>\n";html+=" <ons-icon icon=\"fa-user-tie\" size=\"50px\"></ons-icon>\n";html+=" </ons-col>\n";html+=" <ons-col>\n";html+=" <div class=\"title\">\n";html+=" "+title+"\n";html+=" </div>\n";html+=" </ons-col>\n";html+=" </ons-row>\n";html+=" <ons-row>\n";html+=" <ons-col style=\"text-align: center;\">\n";html+=" <ons-button modifier=\"material large\" onclick=\"loginAPIKeyErrorInProgress=false;loginWithAPIToken("+id+");\" class=\"menubutton\">\n";html+=" <ons-icon icon=\"md-sign-in\"></ons-icon>\n";html+=" <span class=\"menulabel translate\">AUTH</span>\n";html+=" </ons-button>\n";html+=" </ons-col>\n";html+=" </ons-row>\n";html+=" </ons-card>\n";html+=" </ons-col>\n";html+="</ons-row>\n";return html;}
function feedMyAccounts(){let formField='#feedMyAccounts';let html="";$(formField).empty();let accounts=JSON.parse(localGetData("accounts"));if(accounts!==null){for(let f=0;f<accounts.length;f++){lemail=accounts[f]['email'];html+=makeOneAccount(f,lemail,lemail);}}
$(formField).append(html);}
function sendForm(leformName){myDebug("sendForm "+leformName);showWait();$.ajaxSetup({timeout:10000,headers:{'X-CSRF-TOKEN':localGetData("api_token")}});if(document.getElementById('ladate')){myDebug("on a ladate : "+document.getElementById('ladate').value);localStoreData("ladate",document.getElementById('ladate').value);}
var moyenPaiement=null;var els=document.getElementsByName('moyenPaiement');for(var i=0;i<els.length;i++){if(els[i].checked){moyenPaiement=els[i].value;myDebug("on a moyenPaiement : "+moyenPaiement);localStoreData("moyenPaiement",moyenPaiement);break;}}
var leform=document.getElementById(leformName);myDebug("formdata tout neuf");var formdata=new FormData(leform);myDebug(formdata);formdata.append('_token',localGetData("api_token"));if(document.getElementById('updateID').value==0){myDebug("on est pas en update");var hasImage=document.getElementById('smallImage');if(hasImage!==null&&!globalDevMode){var file=document.getElementById('smallImage').getAttribute("src");if(file!=""){myDebug("sendForm fileImage : "+file);let typeFraisObj=document.getElementById(leformName).typeFrais;myDebug("sendForm typeFraisObj: "+typeFraisObj.value);globalTypeFrais="autre";if(typeFraisObj!==null){globalTypeFrais=typeFraisObj.value;}
......@@ -142,9 +145,9 @@ else{$('#'+field).attr('style',"");}}
else{myDebug("le champ suivant n'existe pas : "+field);}}
if(probleme!=""){ons.notification.alert("Certaines informations sont manquantes:<ul> "+probleme+"</ul>",{title:"Attention"}).then(function(){return false;});}
else{myDebug("genericCheckForm return true");return true;}}
function initialiseForm(){myDebug('initialiseForm ... ');if(document.getElementById('feedPaiements')){myDebug('feedPaiements ...');$('#feedPaiements').load('parts/paiement.html',function(){myDebug('feedPaiements load ...');$('#feedPaiements').trigger("create");if(dataLDF!=""){if(dataLDF['moyenPaiement']){myDebug("Choix du moyen de paiement : ");$('#moyenPaiement-'+dataLDF['moyenPaiement']).click();myDebug("On a cliqué sur "+dataLDF['moyenPaiement']);}}
function initialiseForm(){myDebug('initialiseForm ... ');if(document.getElementById('feedPaiements')){myDebug('feedPaiements ...');$('#feedPaiements').load('parts/paiement.html',function(){myDebug('feedPaiements load ...');$('#feedPaiements').trigger("create");$('#feedPaiements').find('.translate').each(function(i,obj){if($(obj).html()){let t=trans($(obj).html());$(obj).html(t.trim());}});if(dataLDF!=""){if(dataLDF['moyenPaiement']){myDebug("Choix du moyen de paiement : ");$('#moyenPaiement-'+dataLDF['moyenPaiement']).click();myDebug("On a cliqué sur "+dataLDF['moyenPaiement']);}}
else{if(localGetData('moyenPaiement')){$('#moyenPaiement-'+localGetData('moyenPaiement')).click();myDebug("On a prévalidé le moyenPaiement-"+localGetData('moyenPaiement'));}
else{myDebug('feedPaiements aucun moyen de paiement prévalidé ...');}}});myDebug('initialiseForm end ');}
else{myDebug('feedPaiements aucun moyen de paiement prévalidé ...');}}});myDebug('feedPaiements end ');}
if(document.getElementById('ladate')){let today=new Date();$('#ladate').val(today.toDateInputValue());}
if(document.getElementById('feedVehiculesPerso')){if($('#feedVehiculesPerso').is(':empty')){$("#feedVehiculesPerso").append(feedVehicules("vehicules"));}}
if(document.getElementById('feedVehiculesPro')){if($('#feedVehiculesPro').is(':empty')){$("#feedVehiculesPro").append(feedVehicules("vehiculesPro"));}}
......@@ -155,7 +158,8 @@ if(document.getElementById('feedTVA4')){if($('#feedTVA4').is(':empty')){let v=lo
if(document.getElementById('ladateStart')){var date=new Date();let jour=new Date(date.getFullYear(),date.getMonth()-1,1);$('#ladateStart').val(jour.toDateInputValue());}
if(document.getElementById('ladateEnd')){var date=new Date();let jour=new Date(date.getFullYear(),date.getMonth()+1,0);$('#ladateEnd').val(jour.toDateInputValue());}
if(device!==undefined){if(device.platform=="iOS"){$('input[type="number"]').attr('pattern','[0-9]*');$('input[type="number"]').attr('decimal','true');$('input[type="number"]').prop('type','text');}}
else{myDebug("device is undef !");}}
else{myDebug("device is undef !");}
myDebug('initialiseForm end ');}
function newResumable(ajaxURL,result,filename){myDebug("creation de l'objet globalResumable pour "+filename+" a envoyer vers "+ajaxURL);if(typeof globalProgressBar!='undefined'){globalResumable.cancel();}
if(typeof filename===undefined||filename==""){if(globalIndexedDB!==null&&databaseEngine=='IndexedDB'){myDebug("globalLastInsertId : "+globalLastInsertId);if(globalLastInsertId>0){localDeleteLDFtoSync(globalLastInsertId);globalLastInsertId="";}}
gotoPage('messageDone.html',false);return;}
......@@ -178,15 +182,15 @@ function trans(str){return translateStrings(str);}
function onLangFileLoaded(text){if(text===null||typeof text==="undefined"){}
else{var data=JSON.parse(text);translateStrings=i18n.create({values:data});translateUI();}}
function CreateAccount(){window.open("https://doliscan.fr/webRegister","_system");return false;}
function loginWithAPIToken(accountID=null){let lemail="";if(accountID!==null){let accounts=JSON.parse(localGetData("accounts"));if(accounts!==null){lemail=accounts[accountID]['email'];api_token=accounts[accountID]['apikey'];let api_server=accounts[accountID]['server'];localStoreData("email",lemail);localStoreData("api_token",api_token);localStoreData("api_server",api_server);}
else{alert("auto user switch NULL");}}
if(localGetData("api_token")===null){myDebug("loginWithAPIToken : aucun token, return");myDebug("carouselLogin call 0");carouselLogin();return;}
function loginWithAPIToken(accountID=null){myDebug("loginWithAPIToken : "+accountID);let lemail="";if(accountID!==null){let accounts=JSON.parse(localGetData("accounts"));if(accounts!==null){lemail=accounts[accountID]['email'];api_token=accounts[accountID]['apikey'];let api_server=accounts[accountID]['server'];localStoreData("email",lemail);localStoreData("api_token",api_token);localStoreData("api_server",api_server);}
else{myDebug("auto user switch NULL");}}
if(localGetData("api_token")===null){myDebug("loginWithAPIToken : aucun token, return");myDebug("carouselLogin call 0");loginAPIKeyErrorInProgress=true;carouselLogin();return;}
lemail=localGetData("email");api_token=localGetData("api_token");myDebug("loginWithAPIToken : token existant on essaye de se connecter sur "+localGetData("api_server"));myDebug("loginWithAPIToken : avec "+api_token);myDebug("loginWithAPIToken : avec "+lemail);showWait();if(ajaxRequestJSON)
ajaxRequestJSON.abort();var ajaxRequestJSON=$.ajax({url:localGetData("api_server")+"/api/ping",timeout:5000,type:"POST",dataType:"json",data:{email:lemail,},headers:{Authorization:'Bearer '+api_token},success:function(result,textStatus,request){globalNetworkResponse=Date.now();hideWait();myDebug("loginWithAPIToken : OK ("+textStatus+"/"+request.status+")");if(typeof result!='undefined'){myDebug("loginWithAPIToken : result ok");myDebug(result.data);if(typeof result.data!='undefined'&&typeof result.data.api_token!='undefined'){myDebug("loginWithAPIToken : result.data ok, on compare "+globalCompatibleWithAPIVersion+" et "+result.data.api_version);if(result.data.api_version==globalCompatibleWithAPIVersion){updateLocalUserFromServer(result,updateLocalUserFromServerSuccess);}
else{if(typeof result.data.api_version_message!='undefined'){myDebug("result.data.api_token undefined : "+result);$("#messagePopupMessage").replaceWith(result.data.api_version_message);$("#messagePopup").show();}}
localStoreData("api_token",api_token);gotoPage('menu.html','false');}
else{myDebug("loginWithAPIToken : ERR -> result.data undefined");localStoreData("api_token",null);myDebug("carouselLogin call 3");carouselLogin();}}
else{myDebug("loginWithAPIToken : ERR -> result undefined");localStoreData("api_token",null);myDebug("carouselLogin call 4");carouselLogin();}},error:function(result){hideWait();let msg="";if(result.status===0){msg='Not connect. Verify Network.';}else if(result.status==404){msg='Requested page not found. [404]';}else if(result.status==500){msg='Internal Server Error [500].';}else{msg='Uncaught Error.\n'+result.responseText;}
else{myDebug("loginWithAPIToken : ERR -> result undefined");localStoreData("api_token",null);myDebug("carouselLogin call 4");carouselLogin();}},error:function(result){hideWait();let msg="";if(result.status===0){msg='Not connect. Verify Network.';}else if(result.status==401){msg='API Key error, not authenticated, maybe too old. [401]';myDebug("On passe loginAPIKeyErrorInProgress a true");loginAPIKeyErrorInProgress=true;nullKeyAccount("accounts",lemail);}else if(result.status==404){msg='Requested page not found. [404]';}else if(result.status==500){msg='Internal Server Error [500].';}else{msg='Uncaught Error.\n'+result.responseText;}
myDebug("loginWithAPIToken : ERR -> end session : "+msg);myDebug("loginWithAPIToken : ERR -> end session : "+result.status);localStoreData("api_token",null);myDebug("carouselLogin call 2");carouselLogin();}});}
function passwordJson(){$("#messagePopupMessage").replaceWith("");let lemail=document.getElementById('emailForget').value;showWait();if(ajaxRequestPasswordJSON)
ajaxRequestPasswordJSON.abort();var ajaxRequestPasswordJSON=$.ajax({type:"POST",url:localGetData("api_server")+"/api/password/forgot",timeout:15000,data:{email:lemail,},success:function(result){hideWait();globalNetworkResponse=Date.now();ons.notification.alert(result.message,{title:"Information"}).then(function(){myDebug("carouselLogin call 9");carouselLogin();});},error:function(result){hideWait();if(typeof result.responseJSON.message!='undefined'){ons.notification.alert(result.responseJSON.message,{title:"Erreur"});}
......@@ -206,8 +210,9 @@ if(result.status=="503"){ons.notification.alert("Serveur indisponible, veuillez
else{$("#erreurLogin").show();}
myDebug("loginJson error : ERR -> end session : "+msg);myDebug("loginJson error : ERR -> end session : "+result.status);localStoreData("api_token",null);myDebug("carouselLogin call 10");carouselLogin();}});}
function switchServer(formId,nom,adresse){$(formId).empty();$(formId).append('Serveur: <b>'+nom+"</b>");localStoreData("api_server",adresse);localStoreData("name_server",nom);}
function carouselLogin(){myDebug("carouselLogin...");let defaultCarouselIndex=0;if(localGetData("email")!==null){$('input[name="email"]').val(localGetData("email"));}
if(localGetData("accounts")!==null){defaultCarouselIndex=2;}
function carouselLogin(){myDebug("carouselLogin... loginAPIKeyErrorInProgress="+loginAPIKeyErrorInProgress);let defaultCarouselIndex=0;if(localGetData("accounts")!==null){defaultCarouselIndex=2;}
if(loginAPIKeyErrorInProgress==true){defaultCarouselIndex=0;}
if(localGetData("email")!==null){$('input[name="email"]').val(localGetData("email"));}
try{carousel=document.querySelector('ons-carousel');if(typeof carousel=='object'){myDebug("carouselLogin... on est sur l'index "+carousel.getActiveIndex());if(carousel.getActiveIndex()!=defaultCarouselIndex){myDebug("carouselLogin... set Active Index : "+defaultCarouselIndex);carousel.setActiveIndex(defaultCarouselIndex);}
myDebug("carouselLogin... on est maintenant sur l'index "+carousel.getActiveIndex());}
else{myDebug("carouselLogin not ready...");}}catch(e){myDebug("carouselLogin not ready catched ... ",e)}}
......@@ -235,6 +240,8 @@ if(localGetData("api_server")==null){hideWait();$("#erreurLogin").show();}},erro
function rmAccount(storageKey,id){let accounts=JSON.parse(localGetData(storageKey));accounts.splice(id,1);if(accounts.length>0)
localStoreData(storageKey,JSON.stringify(accounts));else
localStoreData(storageKey,null);}
function nullKeyAccount(storageKey,email){return new Promise((resolve,reject)=>{let update=0;let accounts=JSON.parse(localGetData(storageKey));if(accounts!==null){for(let f=0;f<accounts.length;f++){if(accounts[f]['email']==email){accounts[f]['apikey']=null;}}}
resolve(localStoreData(storageKey,JSON.stringify(accounts)));});}
function addAccount(storageKey,email,apikey,server){myDebug("addAccount : "+email);return new Promise((resolve,reject)=>{let update=0;let accounts=JSON.parse(localGetData(storageKey));if(accounts===null){accounts=[];}
else{for(let f=0;f<accounts.length;f++){if(accounts[f]['email']==email){accounts[f]['apikey']=apikey;accounts[f]['server']=server;update=1;myDebug("addAccount : update");}}}
if(update==0){let accountNew={"email":email,"apikey":apikey,"server":server};myDebug("addAccount : insert : "+accountNew);accounts.push(accountNew);}
......@@ -268,7 +275,7 @@ function onPhotoDataSuccess(imageData){myDebug("onPhotoDataSuccess :"+imageURI);
function onPhotoURISuccess(imageURI){var imageCDV;myDebug("onPhotoURISuccess :"+imageURI);if(imageURI.startsWith("file://")){imageCDV=imageURI.substr(7);}
else{imageCDV=imageURI;}
if(device!==undefined){if(device.platform=="iOS"){plugins.crop(function success(data){dataCDV=window.WkWebView.convertFilePath(data);globalPictureFileName=data;myDebug('iOS retour du crop : '+data+" -> convert to CDV : "+dataCDV);let smallImage=document.getElementById('smallImage');smallImage.style.display='block';smallImage.src=dataCDV;let photoFacturette=document.getElementById('photoFacturette');photoFacturette.value="2";},function fail(){},imageURI,{quality:80,targetWidth:-1,targetHeight:-1});}
else{ImageCropper.cropImage(imageURI,function(data){myDebug('Android retour du crop : '+data+" ou "+imageURI+"?");globalPictureFileName=imageURI;let smallImage=document.getElementById('smallImage');smallImage.style.display='block';smallImage.src=data;let photoFacturette=document.getElementById('photoFacturette');photoFacturette.value="2";},function(err){myDebug("Crop Error: "+err);});}}
else{ImageCropper.cropImage(imageURI,function(data){myDebug('Android retour du crop : '+data+" ou "+imageURI+"?");globalPictureFileName=data;let smallImage=document.getElementById('smallImage');smallImage.style.display='block';smallImage.src=data;let photoFacturette=document.getElementById('photoFacturette');photoFacturette.value="2";},function(err){myDebug("Crop Error: "+err);});}}
else{myDebug("device is undef !");}}
function capturePhoto(){if(device!==undefined){if(device.platform=="iOS"){capturePhotoIOS();}
else{capturePhotoAndroid();}}
......
......@@ -7,7 +7,7 @@ var globalAppVersion = "1.8.2"; // mis à jour automatiquement à partir
// **********************************************************************
var globalDevMode = true; // on est en mode dev ou prod ? par defaut oui pour la page d'index
var globalDevMode = false; // on est en mode dev ou prod ? par defaut oui pour la page d'index
// note en mode dev la photo de la facturette n'est pas obligatoire
var globalMyCamera; // l'appareil photo
var globalpictureSource; // picture source
......@@ -30,6 +30,7 @@ var globalResumable = undefined;
var globalProgressBar = undefined;
var globalTypeFrais = "";
var globalVehiculeEd = undefined; //vehicule a modifier
var loginAPIKeyErrorInProgress = false; //passe a true dans le cas particulier d'une tentative de login avec une clé d'api qui ne marche pas
//liste des donnees que le serveur peut eventuellement échanger avec nous (factorisation de code)
var globalSrvKeys = ['email', 'api_token', 'firstname', 'name', 'adresse', 'cp', 'ville', 'pays', 'send_copy_to', 'compta_email',
'compta_ik', 'compta_peage', 'compta_hotel', 'compta_train', 'compta_carburant', 'compta_taxi', 'compta_restauration', 'compta_divers',
......
......@@ -382,3 +382,48 @@ function createIK(titre, ladate, message, arrivee, depart) {
myDebug("createIK : avant le Goto : " + JSON.stringify(dataIK));
gotoPage("frais-ik.html", true);
}
function makeOneAccount(id, title, mail) {
let html = "";
html = "<ons-row>\n";
html += " <ons-col>\n";
html += " <ons-card>\n";
html += " <ons-row>\n";
html += " <ons-col>\n";
html += " <ons-icon icon=\"fa-user-tie\" size=\"50px\"></ons-icon>\n";
html += " </ons-col>\n";
html += " <ons-col>\n";
html += " <div class=\"title\">\n";
html += " " + title + "\n";
html += " </div>\n";
html += " </ons-col>\n";
html += " </ons-row>\n";
html += " <ons-row>\n";
html += " <ons-col style=\"text-align: center;\">\n";
html += " <ons-button modifier=\"material large\" onclick=\"loginAPIKeyErrorInProgress=false;loginWithAPIToken(" + id + ");\" class=\"menubutton\">\n";
html += " <ons-icon icon=\"md-sign-in\"></ons-icon>\n";
html += " <span class=\"menulabel translate\">AUTH</span>\n";
html += " </ons-button>\n";
html += " </ons-col>\n";
html += " </ons-row>\n";
html += " </ons-card>\n";
html += " </ons-col>\n";
html += "</ons-row>\n";
return html;
}
function feedMyAccounts() {
let formField = '#feedMyAccounts';
let html = "";
$(formField).empty();
let accounts = JSON.parse(localGetData("accounts"));
if (accounts !== null) {
for (let f = 0; f < accounts.length; f++) {
lemail = accounts[f]['email'];
html += makeOneAccount(f, lemail, lemail);
}
}
$(formField).append(html);
}
......@@ -416,6 +416,18 @@ function initialiseForm() {
$('#feedPaiements').load('parts/paiement.html', function () {
myDebug('feedPaiements load ...');
$('#feedPaiements').trigger("create");
//Cas particulier pour la traduction
$('#feedPaiements').find('.translate').each(function (i, obj) {
// console.debug("PAY traduction de " + $(obj).html());
// alert("on traduit [" + i + "] et " + $(obj).html());
if ($(obj).html()) {
let t = trans($(obj).html());
$(obj).html(t.trim());
}
});
//Si on est en mode modification de frais dataLDF n'est pas vide...
if (dataLDF != "") {
if (dataLDF['moyenPaiement']) {
......@@ -436,7 +448,7 @@ function initialiseForm() {
}
}
});
myDebug('initialiseForm end ');
myDebug('feedPaiements end ');
}
//Si on a un objet "ladate" on essaye de lui attribuer par défaut la date du jour
......@@ -521,7 +533,7 @@ function initialiseForm() {
else {
myDebug("device is undef !");
}
myDebug('initialiseForm end ');
}
function newResumable(ajaxURL, result, filename) {
......
......@@ -5,6 +5,7 @@ function CreateAccount() {
//si accountID est non nul alors on essaye d'utiliser ce compte sauvegardé
function loginWithAPIToken(accountID = null) {
myDebug("loginWithAPIToken : " + accountID);
let lemail = "";
if (accountID !== null) {
let accounts = JSON.parse(localGetData("accounts"));
......@@ -17,13 +18,14 @@ function loginWithAPIToken(accountID = null) {
localStoreData("api_server", api_server);
}
else {
alert("auto user switch NULL");
myDebug("auto user switch NULL");
}
}
if (localGetData("api_token") === null) {
myDebug("loginWithAPIToken : aucun token, return");
myDebug("carouselLogin call 0");
loginAPIKeyErrorInProgress = true;
carouselLogin();
return;
}
......@@ -33,6 +35,7 @@ function loginWithAPIToken(accountID = null) {
myDebug("loginWithAPIToken : avec " + api_token);
myDebug("loginWithAPIToken : avec " + lemail);
/*
processData: false,
cache: false,
......@@ -101,6 +104,11 @@ function loginWithAPIToken(accountID = null) {
let msg = "";
if (result.status === 0) {
msg = 'Not connect. Verify Network.';
} else if (result.status == 401) {
msg = 'API Key error, not authenticated, maybe too old. [401]';
myDebug("On passe loginAPIKeyErrorInProgress a true");
loginAPIKeyErrorInProgress = true;
nullKeyAccount("accounts", lemail);
} else if (result.status == 404) {
msg = 'Requested page not found. [404]';
} else if (result.status == 500) {
......@@ -337,16 +345,20 @@ function switchServer(formId, nom, adresse) {
//Passe sur la page de Login
function carouselLogin() {
myDebug("carouselLogin...");
myDebug("carouselLogin... loginAPIKeyErrorInProgress=" + loginAPIKeyErrorInProgress);
let defaultCarouselIndex = 0;
if (localGetData("accounts") !== null) {
defaultCarouselIndex = 2;
}
if (loginAPIKeyErrorInProgress == true) {
defaultCarouselIndex = 0;
}
if (localGetData("email") !== null) {
// $("#autoLoginText").append("Compte " + localGetData("email") + " sur " + localGetData("name_server"));
$('input[name="email"]').val(localGetData("email"));
}
if (localGetData("accounts") !== null) {
defaultCarouselIndex = 2;
}
//let carousel = document.getElementById('carousel');
try {
......
......@@ -197,6 +197,23 @@ function rmAccount(storageKey, id) {
// myDebug("rmaccount liste apres" + accounts);
}
//Passe à null la clé d'api de l'utilisateur
function nullKeyAccount(storageKey,email) {
return new Promise((resolve, reject) => {
let update = 0;
//On cherche une place de libre (max 4 on a dit)
let accounts = JSON.parse(localGetData(storageKey));
if (accounts !== null) {
for (let f = 0; f < accounts.length; f++) {
if (accounts[f]['email'] == email) {
accounts[f]['apikey'] = null;
}
}
}
resolve(localStoreData(storageKey, JSON.stringify(accounts)));
});
}
//Ajoute un compte utilisateur
function addAccount(storageKey, email, apikey, server) {
myDebug("addAccount : " + email);
......
......@@ -135,66 +135,15 @@
<div class="container">
<h3 class="translate">MyAccounts</h3>
<form id="leformAccounts">
<div id='feedUserSwitch'></div>
<div id='feedMyAccounts'></div>
</form>
</div>
<ons-row>
<ons-col>
<ons-card>
<ons-row>
<ons-col>
<ons-icon icon="fa-user-tie" size="50px"></ons-icon>
</ons-col>
<ons-col>
<div class="title">
DEMO
</div>
</ons-col>
</ons-row>
<ons-row>
<ons-col style="text-align: center;">
<ons-button modifier="material large" onclick="loginWithAPIToken(0);" class="menubutton">
<ons-icon icon="md-sign-in"></ons-icon>
<span class="menulabel translate">AUTH</span>
</ons-button>
</ons-col>
</ons-row>
</ons-card>
</ons-col>
</ons-row>
<ons-row>
<ons-col>
<ons-card>
<ons-row>
<ons-col>
<ons-icon icon="fa-user-tie" size="50px"></ons-icon>
</ons-col>
<ons-col>
<div class="title">
CAP-REL
</div>
</ons-col>
</ons-row>
<ons-row>
<ons-col style="text-align: center;">
<ons-button modifier="material large" onclick="loginWithAPIToken(1);" class="menubutton">
<ons-icon icon="md-sign-in"></ons-icon>
<span class="menulabel translate">AUTH</span>
</ons-button>
</ons-col>
</ons-row>
</ons-card>
</ons-col>
</ons-row>
</ons-carousel-item>
</ons-carousel>
<script>
ons.getScriptPage().onInit = function () {
feedMyAccounts();
this.onShow = function () {
myDebug("2° lancement de carousel ...");
carouselLogin();
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment