From b3dddaacd220fff4f75fc8787a7dafe142aaf314 Mon Sep 17 00:00:00 2001 From: Denis Nutiu Date: Tue, 24 Nov 2020 19:03:02 +0200 Subject: [PATCH] TelemetryPublisherFirestore.cs: Force re-authorization on failure --- .../Publishers/TelemetryPublisherFirestore.cs | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs b/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs index f37551b..03b13cb 100644 --- a/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs +++ b/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs @@ -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() @@ -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 @@ -111,6 +100,22 @@ namespace NucuCar.Telemetry.Publishers Logger?.LogDebug($"{response?.Content}"); } } + + 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) { @@ -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.