|
10 | 10 | import com.algolia.search.models.common.CallType; |
11 | 11 | import com.algolia.search.util.AlgoliaUtils; |
12 | 12 | import com.algolia.search.util.HmacShaUtils; |
| 13 | +import java.time.Duration; |
| 14 | +import java.time.Instant; |
| 15 | +import java.util.Base64; |
13 | 16 | import java.util.List; |
14 | 17 | import java.util.Objects; |
15 | 18 | import java.util.concurrent.CompletableFuture; |
| 19 | +import java.util.regex.*; |
16 | 20 | import javax.annotation.Nonnull; |
17 | 21 |
|
18 | 22 | public interface SearchClientAPIKeys extends SearchClientBase { |
@@ -422,4 +426,35 @@ default String generateSecuredAPIKey( |
422 | 426 | @Nonnull String parentAPIKey, SecuredApiKeyRestriction restriction) throws Exception { |
423 | 427 | return HmacShaUtils.generateSecuredApiKey(parentAPIKey, restriction); |
424 | 428 | } |
| 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 | + } |
425 | 460 | } |
0 commit comments