TelemetryPublisherFirestore.cs: Force re-authorization on failure

This commit is contained in:
Denis-Cosmin Nutiu 2020-11-24 19:03:02 +02:00
parent cbd12c5304
commit b3dddaacd2

View file

@ -32,7 +32,7 @@ namespace NucuCar.Telemetry.Publishers
protected HttpClient HttpClient;
private string _idToken;
private DateTime _nextExpiresTime;
private DateTime _authorizationExpiryTime;
// Variables used for authentication
private readonly string _webEmail;
@ -74,17 +74,6 @@ namespace NucuCar.Telemetry.Publishers
private async Task SetupAuthorization()
{
// If there are no credentials or partial credentials supplies there must be no authorization.
if (_webApiKey == null || _webEmail == null || _webPassword == null)
{
return;
}
// Check if the token is about to expire in the next 5 minutes.
if (DateTime.UtcNow.AddMinutes(5) < _nextExpiresTime)
{
return;
}
// https://cloud.google.com/identity-platform/docs/use-rest-api#section-sign-in-email-password
var requestUrl = $"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={_webApiKey}";
var data = new Dictionary<string, object>()
@ -102,7 +91,7 @@ namespace NucuCar.Telemetry.Publishers
_idToken = jsonContent.GetProperty("idToken").ToString();
// Setup next expire.
var expiresIn = double.Parse(jsonContent.GetProperty("expiresIn").ToString());
_nextExpiresTime = DateTime.UtcNow.AddSeconds(expiresIn);
_authorizationExpiryTime = DateTime.UtcNow.AddSeconds(expiresIn);
HttpClient.Authorization(_idToken);
}
else
@ -112,6 +101,22 @@ namespace NucuCar.Telemetry.Publishers
}
}
private async Task CheckAndSetupAuthorization()
{
// If there are no credentials or partial credentials supplies there must be no authorization.
if (_webApiKey == null || _webEmail == null || _webPassword == null)
{
return;
}
// Check if the token is about to expire in the next 5 minutes.
if (DateTime.UtcNow.AddMinutes(5) < _authorizationExpiryTime)
{
return;
}
await SetupAuthorization();
}
public override async Task PublishAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
@ -124,7 +129,7 @@ namespace NucuCar.Telemetry.Publishers
HttpResponseMessage responseMessage = null;
try
{
await SetupAuthorization();
await CheckAndSetupAuthorization();
responseMessage = await HttpClient.PostAsync("", data);
}
// ArgumentException occurs during json serialization errors.