windport/pkg/windscribe/auth.go
2023-08-13 23:22:48 -04:00

100 lines
1.8 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(ctx context.Context, a Auth) error {
req, err := http.NewRequestWithContext(ctx, "GET", "https://windscribe.com/login", nil)
if err != nil {
return err
}
fillReq(req)
req.Header.Set("Accept", "*/*")
resp, err := c.hc.Do(req)
if err != nil {
return err
}
cleanupBody(resp.Body)
c.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(c.csrf.Time)},
"csrf_token": []string{c.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)
}
c.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
}