windport/pkg/windscribe/auth.go
2023-08-13 16:19:23 -04:00

101 lines
1.7 KiB
Go

package windscribe
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
)
type Auth struct {
User string `json:"user"`
Password string `json:"password"`
Code string `json:"code"`
isAuthed bool
}
func (c *client) Auth(a Auth) error {
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, "GET", "https://windscribe.com/login", nil)
if err != nil {
return err
}
fillReq(req)
req.Header.Set("Accept", "*/*")
_, err = c.hc.Do(req)
if err != nil {
return err
}
csrf, err := c.getCSRF(ctx)
if err != nil {
return err
}
err = c.doInit(ctx)
if err != nil {
return err
}
values := url.Values{
"login": []string{"1"},
"upgrade": []string{"0"},
"csrf_time": []string{fmt.Sprint(csrf.Time)},
"csrf_token": []string{csrf.Token},
"username": []string{c.auth.User},
"password": []string{c.auth.Password},
"code": []string{c.auth.Code},
}
req, err = http.NewRequestWithContext(ctx, "POST", "https://windscribe.com/login", strings.NewReader(values.Encode()))
if err != nil {
return err
}
fillReq(req)
resp, err := c.hc.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 302 {
return fmt.Errorf("login failed %d", resp.StatusCode)
}
csrf, err = c.getCSRFfromBody(ctx, resp.Body)
if err != nil {
return err
}
cleanupBody(resp.Body)
c.auth.isAuthed = true
return nil
}
func (c *client) doInit(ctx context.Context) (error) {
req, err := http.NewRequestWithContext(ctx, "POST", "https://res.windscribe.com/res/init", strings.NewReader(url.Values{"wsref":[]string{"https://windscribe.com/"}}.Encode()))
if err != nil {
return err
}
req.Header.Set("Accept", "*/*")
fillReq(req)
resp, err := c.hc.Do(req)
if err != nil {
return err
}
cleanupBody(resp.Body)
return nil
}