|
1 | 1 | # Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
|
2 | 2 |
|
| 3 | +require 'openssl' |
| 4 | +require 'base64' |
| 5 | + |
3 | 6 | module Algolia
|
4 | 7 | class SearchClient
|
5 | 8 | attr_accessor :api_client
|
@@ -3129,5 +3132,53 @@ def browse_synonyms(index_name, search_synonyms_params = Search::SearchSynonymsP
|
3129 | 3132 |
|
3130 | 3133 | synonyms unless block_given?
|
3131 | 3134 | end
|
| 3135 | + |
| 3136 | + # Helper: Generates a secured API key based on the given `parent_api_key` and given `restrictions`. |
| 3137 | + # |
| 3138 | + # @param parent_api_key [String] Parent API key used the generate the secured key |
| 3139 | + # @param restrictions [SecuredApiKeyRestrictions] Restrictions to apply on the secured key |
| 3140 | + # |
| 3141 | + # @return [String] |
| 3142 | + # |
| 3143 | + def generate_secured_api_key(parent_api_key, restrictions = {}) |
| 3144 | + restrictions = restrictions.to_hash |
| 3145 | + if restrictions.key?(:searchParams) |
| 3146 | + # merge searchParams with the root of the restrictions |
| 3147 | + |
| 3148 | + restrictions.merge!(restrictions[:searchParams]) |
| 3149 | + restrictions.delete(:searchParams) |
| 3150 | + end |
| 3151 | + |
| 3152 | + url_encoded_restrictions = Algolia::Transport.stringify_query_params(restrictions).sort.to_h.map do |key, value| |
| 3153 | + "#{key}=#{value}" |
| 3154 | + end.join('&') |
| 3155 | + |
| 3156 | + hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), parent_api_key, url_encoded_restrictions) |
| 3157 | + |
| 3158 | + puts "hmac: #{hmac}" |
| 3159 | + puts "url_encoded_restrictions: #{url_encoded_restrictions}" |
| 3160 | + Base64.encode64("#{hmac}#{url_encoded_restrictions}").gsub("\n", '') |
| 3161 | + end |
| 3162 | + |
| 3163 | + # Helper: Retrieves the remaining validity of the previous generated `secured_api_key`, the `validUntil` parameter must have been provided. |
| 3164 | + # |
| 3165 | + # @param secured_api_key [String] |
| 3166 | + # |
| 3167 | + # @return [Integer] |
| 3168 | + # |
| 3169 | + def get_secured_api_key_remaining_validity(secured_api_key) |
| 3170 | + now = Time.now.to_i |
| 3171 | + decoded_key = Base64.decode64(secured_api_key) |
| 3172 | + regex = 'validUntil=(\d+)' |
| 3173 | + matches = decoded_key.match(regex) |
| 3174 | + |
| 3175 | + if matches.nil? |
| 3176 | + raise AlgoliaError, 'The SecuredApiKey doesn\'t have a validUntil parameter.' |
| 3177 | + end |
| 3178 | + |
| 3179 | + valid_until = matches[1].to_i |
| 3180 | + |
| 3181 | + valid_until - now |
| 3182 | + end |
3132 | 3183 | end
|
3133 | 3184 | end
|
0 commit comments