Skip to content

Commit 6e3cf85

Browse files
committed
added: GetSecuredApiKeyRemainingValidity
Fix #612 [changelog] New SearchClient method to get the remaining validity (seconds) of a securedAPIKey
1 parent c9a8429 commit 6e3cf85

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

algoliasearch-core/src/main/java/com/algolia/search/SearchClientAPIKeys.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,13 @@
1010
import com.algolia.search.models.common.CallType;
1111
import com.algolia.search.util.AlgoliaUtils;
1212
import com.algolia.search.util.HmacShaUtils;
13+
import java.time.Duration;
14+
import java.time.Instant;
15+
import java.util.Base64;
1316
import java.util.List;
1417
import java.util.Objects;
1518
import java.util.concurrent.CompletableFuture;
19+
import java.util.regex.*;
1620
import javax.annotation.Nonnull;
1721

1822
public interface SearchClientAPIKeys extends SearchClientBase {
@@ -422,4 +426,35 @@ default String generateSecuredAPIKey(
422426
@Nonnull String parentAPIKey, SecuredApiKeyRestriction restriction) throws Exception {
423427
return HmacShaUtils.generateSecuredApiKey(parentAPIKey, restriction);
424428
}
429+
430+
/**
431+
* Gets how many seconds are left before the secured API key expires.
432+
*
433+
* @param securedAPIKey The secured API Key to check
434+
* @throws AlgoliaRuntimeException if <code>securedAPIKey</code> is null, empty or whitespaces.
435+
* @throws AlgoliaRuntimeException if <code>securedAPIKey</code> doesn't have a <code>validUntil
436+
* </code> parameter.
437+
*/
438+
default Duration getSecuredApiKeyRemainingValidity(@Nonnull String securedAPIKey) {
439+
440+
if (AlgoliaUtils.isNullOrEmptyWhiteSpace(securedAPIKey)) {
441+
throw new AlgoliaRuntimeException("securedAPIKey must not be empty, null or whitespaces");
442+
}
443+
444+
byte[] decodedBytes = Base64.getDecoder().decode(securedAPIKey);
445+
String decodedString = new String(decodedBytes);
446+
447+
Pattern pattern = Pattern.compile("validUntil=\\d+");
448+
Matcher matcher = pattern.matcher(decodedString);
449+
450+
if (!matcher.find()) {
451+
throw new AlgoliaRuntimeException("The Secured API Key doesn't have a validUntil parameter.");
452+
}
453+
454+
String validUntilMatch = matcher.group(0);
455+
456+
long timeStamp = Long.parseLong(validUntilMatch.replace("validUntil=", ""));
457+
458+
return Duration.ofSeconds(timeStamp - Instant.now().getEpochSecond());
459+
}
425460
}

0 commit comments

Comments
 (0)