Skip to content

Commit

Permalink
add: generate scoped search keys function (#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcMeszaros authored Aug 8, 2023
1 parent 6b58fb5 commit 7aa8800
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
20 changes: 20 additions & 0 deletions typesense/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@ package typesense

import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"

"github.com/typesense/typesense-go/typesense/api"
)

type KeysInterface interface {
Create(key *api.ApiKeySchema) (*api.ApiKey, error)
Retrieve() ([]*api.ApiKey, error)
GenerateScopedSearchKey(searchKey string, params map[string]interface{}) (string, error)
}

type keys struct {
Expand Down Expand Up @@ -37,3 +43,17 @@ func (k *keys) Retrieve() ([]*api.ApiKey, error) {
}
return response.JSON200.Keys, nil
}

func (k *keys) GenerateScopedSearchKey(searchKey string, params map[string]interface{}) (string, error) {
paramsStr, err := json.Marshal(params)
if err != nil {
return "", err
}

mac := hmac.New(sha256.New, []byte(searchKey))
mac.Write(paramsStr)

digest := base64.StdEncoding.EncodeToString(mac.Sum(nil))
rawScopedKey := fmt.Sprintf("%s%s%s", digest, searchKey[0:4], paramsStr)
return base64.StdEncoding.EncodeToString([]byte(rawScopedKey)), nil
}
13 changes: 13 additions & 0 deletions typesense/keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,16 @@ func TestKeysRetrieveOnHttpStatusErrorCodeReturnsError(t *testing.T) {
_, err := client.Keys().Retrieve()
assert.NotNil(t, err)
}

func TestKeysGenerateScopedSearchKey(t *testing.T) {
// setup example from the docs
searchKey := "RN23GFr1s6jQ9kgSNg2O7fYcAUXU7127"
scopedSearchKey := "SC9sT0hncHFwTHNFc3U3d3psRDZBUGNXQUViQUdDNmRHSmJFQnNnczJ4VT1STjIzeyJmaWx0ZXJfYnkiOiJjb21wYW55X2lkOjEyNCJ9"

scopedKey, err := (&keys{}).GenerateScopedSearchKey(searchKey, map[string]interface{}{
"filter_by": "company_id:124",
})

assert.NoError(t, err)
assert.Equal(t, scopedKey, scopedSearchKey)
}

0 comments on commit 7aa8800

Please sign in to comment.