Skip to content

Commit

Permalink
Add csrf token to login request
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtmc committed Apr 6, 2021
1 parent f74c404 commit 31eba8f
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions plausibleclient/client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package plausibleclient

import (
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
Expand All @@ -18,13 +19,33 @@ type Client struct {
}

func (c *Client) login() error {
doc, err := c.getDocument("/login")
if err != nil {
return err
}

csrfToken := ""
csrfTokenExists := false
doc.Find(`form > input[name="_csrf_token"]`).Each(func(i int, s *goquery.Selection) {
csrfToken, csrfTokenExists = s.Attr("value")
})
if !csrfTokenExists {
return fmt.Errorf("could not find csrf token in login page")
}

values := url.Values{}
values.Add("_csrf_token", csrfToken)
values.Add("email", c.username)
values.Add("password", c.password)
_, err := c.httpClient.PostForm("https://plausible.io/login", values)
resp, err := c.httpClient.PostForm("https://plausible.io/login", values)
if err != nil {
return err
}

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("could not login, received status: %s", resp.Status)
}

c.loggedIn = true
return nil
}
Expand All @@ -50,7 +71,12 @@ func NewClient(username, password string) *Client {
}

func (c *Client) getDocument(path string) (*goquery.Document, error) {
resp, err := c.httpClient.Get(c.baseURL + path)
req, err := http.NewRequest("GET", c.baseURL+path, nil)
if err != nil {
return nil, err
}

resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 31eba8f

Please sign in to comment.