Ok fino a step di attesa recall auth...

This commit is contained in:
Samuele E. Locatelli
2019-03-28 14:32:16 +01:00
parent acd38a8be4
commit 49ebd79769
4 changed files with 131 additions and 101 deletions
+99 -46
View File
@@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
@@ -49,6 +50,10 @@ namespace MConnectSDK
/// </summary>
protected DateTime lastRedSrvCheck;
/// <summary>
/// Intervallo di default x recall successive
/// </summary>
protected int waitRecall = 1000;
/// <summary>
/// URL x chaimata auth QR-code
/// </summary>
protected string qrAuthBaseUrl = @"https://smart.maestroconnect.com/deviceauth/{0}";
@@ -130,8 +135,11 @@ namespace MConnectSDK
}
set
{
string serVal = JsonConvert.SerializeObject(value);
ML.setRSV(ML.redHash("TokenResponse"), serVal, value.expires_in / 1000);
if (value != null)
{
string serVal = JsonConvert.SerializeObject(value);
ML.setRSV(ML.redHash("TokenResponse"), serVal, value.expires_in);
}
}
}
/// <summary>
@@ -414,8 +422,8 @@ namespace MConnectSDK
{
int user_code = 0;
int device_code = 0;
int refrInt = 100;
int expIn = 10000;
int refrInt = 5;
int expIn = 60;
if (redServAlive)
{
Random r = new Random();
@@ -434,7 +442,18 @@ namespace MConnectSDK
}
else
{
/// TBD !!!FARE!!! le vere chiamate di testing remoto...
// parametri chiamata
Uri callUri = new Uri(BaseUrl + "/oauth2/token");
var payload = "{\"client_id\": \"test\"}";
HttpContent callCont = new StringContent(payload, Encoding.UTF8, "application/json");
// effettuo call effettiva
var taskRes = Task.Run(() => Utils.PostURI(callUri, callCont));
taskRes.Wait();
// decodifico risposta come tokResp...
var resp = JsonConvert.DeserializeObject<tokenResponse>(taskRes.Result);
waitRecall = 1000 * resp.interval;
tokResp = resp;
}
}
/// <summary>
@@ -480,9 +499,43 @@ namespace MConnectSDK
* - chiamo /verification, con client_id + device_code
* - salvo e verifico retVal
*-----------------------------------------*/
// SOLOS E ho un device code...
if (tokResp != null && tokResp.device_code != "")
{
// parametri chiamata
Uri callUri = new Uri(BaseUrl + "/oauth2/verification");
var payload = "{\"client_id\": \"test\", \"device_code\": \"" + tokResp.device_code + "\"}";
HttpContent callCont = new StringContent(payload, Encoding.UTF8, "application/json");
// effettuo call effettiva
var taskRes = Task.Run(() => Utils.PostURI(callUri, callCont));
taskRes.Wait();
// leggo la rispsota in var temporanea...
var resp = JsonConvert.DeserializeObject<tokenResponse>(taskRes.Result);
// verifico se esista un errore come risposta...
if (resp != null)
{
if (resp.error == "") // aggiorno...
{
//// decodifico risposta come tokResp...
//tokResp = resp;
verifResp = JsonConvert.DeserializeObject<verificationSuccessResponse>(taskRes.Result);
}
else
{
if (resp.error == "slow_down")
{
Thread.Sleep(waitRecall);
}
else if (resp.error == "authorization_pending")
{
Thread.Sleep(waitRecall);
}
}
}
}
}
}
}
@@ -539,8 +592,9 @@ namespace MConnectSDK
{
redisConn = baseConf,
redisConnAdmin = baseConf + ",allowAdmin=true",
// hard coded x ora
testMode = true,
// hard coded x ora
//testMode = true,
testMode = false,
module = _module,
defaultDb = currDb
};
@@ -632,10 +686,6 @@ namespace MConnectSDK
// init output
ActivationPayload answ = new ActivationPayload();
StringBuilder sb = new StringBuilder();
#if false
// init altro
reqStatus = preCheckStatus();
#endif
var _currReq = reqStatus;
// verifico autorizzazione... se non c'è TENTO auth...
if (!reqStatus.IsHmiEnrolled)
@@ -1259,41 +1309,44 @@ namespace MConnectSDK
{
await Task.Run(() =>
{
authData = tryEnroll();
// recupero nuova reqStatus...
_currReq = reqStatusUpd;
// verifico SE sia stato registrato...
if (_currReq.IsHmiEnrolled || authData.IsEnrolled)
// SOLOS E precedentemente autorizzato...
if (_currReq.IsAuth)
{
sb.AppendLine("");
sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | ENROLL DONE", DateTime.Now));
authData.Message += sb.ToString();
processRequest = false;
_currReq.IsAuth = true;
_currReq.IsHmiEnrolled = true;
authData = tryEnroll();
// recupero nuova reqStatus...
_currReq = reqStatusUpd;
// verifico SE sia stato registrato...
if (_currReq.IsHmiEnrolled || authData.IsEnrolled)
{
sb.AppendLine("");
sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | ENROLL DONE", DateTime.Now));
authData.Message += sb.ToString();
processRequest = false;
_currReq.IsAuth = true;
_currReq.IsHmiEnrolled = true;
}
// verifico se richiesta cancellazione... CHIUDO!
if (token.IsCancellationRequested)
{
// riporto richiesta cancellazione... ed esco
authData = new ActivationPayload();
processRequest = false;
}
// aggiorno il payload...
_currReq.Payload = authData;
reqStatus = _currReq;
// riporto progress...
if (progress != null)
{
progress.Report(_currReq);
}
}
// verifico se richiesta cancellazione... CHIUDO!
if (token.IsCancellationRequested)
{
// riporto richiesta cancellazione... ed esco
authData = new ActivationPayload();
processRequest = false;
}
// aggiorno il payload...
_currReq.Payload = authData;
reqStatus = _currReq;
// riporto progress...
if (progress != null)
{
progress.Report(_currReq);
}
// mi fermo...
// attendo...
Thread.Sleep(500);
});
}
+30 -53
View File
@@ -81,63 +81,36 @@ namespace MConnectSDK
/// <param name="pageURL"></param>
public static async Task<string> DownloadPageAsync(string pageURL)
{
string result = "";
string answ = "";
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(pageURL))
using (HttpContent content = response.Content)
{
// ... lettura contenuto...
result = await content.ReadAsStringAsync();
}
return result;
}
#if false
/// <summary>
/// Effettua chaimata URL e restituisce risultato
/// </summary>
/// <param name="URL"></param>
/// <returns></returns>
public static string callUrl(string URL)
{
string answ = "";
// controllo se ho un VETO all'invio...
if (dtVetoSend < DateTime.Now)
{
var client = new WebClientWT();
//var client = new WebClient();
client.Headers.Add("user-agent", CRS("appName"));
try
{
answ = client.DownloadString(URL);
}
catch (Exception exc)
{
// imposto un veto per pauseSendMSec
int pauseSendMSec = CRI("pauseSendMSec");
// aggiungo NOISE... +/- 33%
Random rnd = new Random();
int noise = rnd.Next(1, pauseSendMSec / 3);
pauseSendMSec += noise - (pauseSendMSec / 6);
// imposto veto
dtVetoSend = DateTime.Now.AddMilliseconds(pauseSendMSec);
// log ogni
Logger lg = LogManager.GetCurrentClassLogger();
lg.Info("Errore in callURL: impostato attesa di {0} ms prima della prossima chiamata", pauseSendMSec);
logReduxFactor--;
if (logReduxFactor <= 0)
{
lg.Error("Eccezione in esecuzione callURL: {0}{1}{2}", URL, Environment.NewLine, exc);
logReduxFactor = 10;
}
}
// restituisco valore!
answ = await content.ReadAsStringAsync();
}
return answ;
}
#endif
}
/// <summary>
/// Chiamata POST asyncrona
/// </summary>
/// <param name="reqUri">URI della chiamata</param>
/// <param name="callCont">contenuto della chiamata</param>
/// <returns></returns>
public static async Task<string> PostURI(Uri reqUri, HttpContent callCont)
{
var response = string.Empty;
using (var client = new HttpClient())
{
HttpResponseMessage result = await client.PostAsync(reqUri, callCont);
//if (result.IsSuccessStatusCode)
//{
response = await result.Content.ReadAsStringAsync();
//}
}
return response;
}
}
@@ -187,13 +160,17 @@ namespace MConnectSDK
/// </summary>
public string verification_uri;
/// <summary>
/// Intervallo di refresh della chiamata proposto (msec)
/// Intervallo di refresh della chiamata proposto (sec)
/// </summary>
public int interval = 1000;
public int interval = 5;
/// <summary>
/// Expire di validità della risposta (msec)
/// Expire di validità della risposta (sec)
/// </summary>
public int expires_in = 60000;
public int expires_in = 60;
/// <summary>
/// Eventuale errore in risposta token
/// </summary>
public string error = "";
}
/// <summary>
+1 -1
View File
@@ -422,7 +422,7 @@ namespace TestClient
var currImage = pictBox.Image;
//if (userData.Username != "")
if (userResult.Result.Error.Reason == Reason.AllOk)
if (userResult.Result.Error.Reason == Reason.AllOk)
{
List<UserData> userList = ((UserPayload)userResult.Result.Payload).UserList;
// controllo se ho risultato...)
+1 -1
View File
@@ -1,7 +1,7 @@
#File di conf per MConnectClientSDK
conf:
Client_ID: "test"
MachineID: "MCID-0009-1234-5678"
MachineID: "MCID000123456789"
PingTarget: "stg.api.maestroconnect.scmgroup.com"
AliveTarget: "https://stg.api.maestroconnect.scmgroup.com/health"
BaseUrl: "https://stg.api.maestroconnect.scmgroup.com/api"