draft login

This commit is contained in:
Celogeek 2021-12-12 22:06:11 +01:00
parent 0cc636e7b6
commit ddb44fd6eb
Signed by: celogeek
GPG Key ID: E6B7BDCFC446233A

View File

@ -1,6 +1,13 @@
package main
import "fmt"
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type LoginCommand struct {
Url string `short:"u" long:"url" description:"Url of the instance"`
@ -10,9 +17,58 @@ type LoginCommand struct {
var loginCommand LoginCommand
type Result struct {
Stat string `json:"stat"`
Result bool `json:"result"`
}
func (c *LoginCommand) Execute(args []string) error {
fmt.Printf("Login on %s...\n", c.Url)
Url, err := url.Parse(c.Url)
if err != nil {
return err
}
Url.Path = "ws.php"
q := Url.Query()
q.Set("format", "json")
q.Set("method", "pwg.session.login")
Url.RawQuery = q.Encode()
fmt.Println(Url.String())
Form := url.Values{}
Form.Set("username", c.Login)
Form.Set("password", c.Password)
r, err := http.PostForm(Url.String(), Form)
if err != nil {
return err
}
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
result := Result{}
err = json.Unmarshal(b, &result)
if err != nil {
return err
}
if !result.Result {
return errors.New("can't login with the credential provided")
}
for _, c := range r.Cookies() {
if c.Name == "pwg_id" {
fmt.Println("Token:", c.Value)
break
}
}
return nil
}