Skip to content

Commit

Permalink
added: GetSecuredApiKeyRemainingValidity
Browse files Browse the repository at this point in the history
[changelog]

New SearchClient method to get the remaining validity (seconds)
of a securedAPIKey
  • Loading branch information
Ant-hem committed Aug 15, 2019
1 parent 61235ac commit aa5d5f0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Algolia.Search/Clients/ISearchClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
using Algolia.Search.Models.Mcm;
using Algolia.Search.Models.Personalization;
using Algolia.Search.Models.Search;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
Expand Down Expand Up @@ -116,6 +117,12 @@ public interface ISearchClient
/// <returns></returns>
string GenerateSecuredApiKeys(string parentApiKey, SecuredApiKeyRestriction restriction);

/// <summary>
/// Gets how many seconds are left before the secured API key expires.
/// </summary>
/// <param name="securedAPIKey">The secured API Key</param>
TimeSpan GetSecuredApiKeyRemainingValidity(string securedAPIKey);

/// <summary>
/// Get the full list of API Keys.
/// </summary>
Expand Down
30 changes: 30 additions & 0 deletions src/Algolia.Search/Clients/SearchClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,11 @@
using Algolia.Search.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -199,6 +202,33 @@ public string GenerateSecuredApiKeys(string parentApiKey, SecuredApiKeyRestricti
return HmacShaHelper.Base64Encode($"{hash}{queryParams}");
}

/// <inheritdoc />
public TimeSpan GetSecuredApiKeyRemainingValidity(string securedAPIKey)
{
if (string.IsNullOrWhiteSpace(securedAPIKey))
{
throw new ArgumentNullException(nameof(securedAPIKey));
}

var decodedKey = Encoding.UTF8.GetString(Convert.FromBase64String(securedAPIKey));

var regex = new Regex(@"validUntil=\d+");
var matches = regex.Matches(decodedKey);

if (matches.Count == 0)
{
throw new AlgoliaException("The SecuredAPIKey doesn't have a validUntil parameter.");
}

// Select the validUntil parameter and its value
var validUntilMatch = matches.Cast<Match>().Select(x => x.Value).First();

// Extracting and converting the timestamp
long timeStamp = Convert.ToInt64(validUntilMatch.Replace("validUntil=", string.Empty));

return TimeSpan.FromSeconds(timeStamp - DateTime.UtcNow.ToUnixTimeSeconds());
}

/// <inheritdoc />
public ListApiKeysResponse ListApiKeys(RequestOptions requestOptions = null) =>
AsyncHelper.RunSync(() => ListApiKeysAsync(requestOptions));
Expand Down

0 comments on commit aa5d5f0

Please sign in to comment.