Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validation to API keys #78

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions posthog.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,29 @@ type client struct {
lastEventMutex sync.RWMutex
}

func (c *client) validateAPIKey() error {
url := c.Endpoint + "/decide/?v=3"
req, err := http.NewRequest("POST", url, nil)
if err != nil {
return fmt.Errorf("error creating request: %v", err)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.key)

resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("invalid API key: received status code %d", resp.StatusCode)
}

return nil
}

// Instantiate a new client that uses the write key passed as first argument to
// send messages to the backend.
// The client is created with the default configuration.
Expand Down Expand Up @@ -125,6 +148,11 @@ func NewWithConfig(apiKey string, config Config) (cli Client, err error) {
}

if len(c.PersonalApiKey) > 0 {

if err := c.validateAPIKey(); err != nil {
return nil, fmt.Errorf("failed to initialize client: %v", err)
}

c.featureFlagsPoller = newFeatureFlagsPoller(
c.key,
c.Config.PersonalApiKey,
Expand Down Expand Up @@ -181,6 +209,10 @@ func dereferenceMessage(msg Message) Message {
}

func (c *client) Enqueue(msg Message) (err error) {
if c.key == "" {
return errors.New("client not properly initialized: invalid API key")
}

msg = dereferenceMessage(msg)
if err = msg.Validate(); err != nil {
return
Expand Down
Loading