2022-03-05 17:03:53 +01:00

61 lines
1.2 KiB
Go

package main
import (
"errors"
"fmt"
"github.com/go-resty/resty/v2"
)
type LoginCommand struct {
Url string `short:"u" long:"url" description:"Url of the instance" required:"true"`
Login string `short:"l" long:"login" description:"Login" required:"true"`
Password string `short:"p" long:"password" description:"Password" required:"true"`
}
type LoginRequest struct {
Login string `json:"login"`
Password string `json:"password"`
}
type LoginError struct {
Error string
}
type LoginResponse struct {
Token string
}
func (c *LoginCommand) Execute(args []string) error {
logger.Printf("Login on %s...\n", c.Url)
cli := resty.New().SetBaseURL(c.Url)
resp, err := cli.
R().
SetBody(&LoginRequest{c.Login, c.Password}).
SetResult(&LoginResponse{}).
SetError(&LoginError{}).
Post("/account/login")
if err != nil {
return err
}
if err, ok := resp.Error().(*LoginError); ok {
logger.Printf("Login failed!")
return errors.New(err.Error)
}
logger.Println("Login succeed!")
if result, ok := resp.Result().(*LoginResponse); ok {
fmt.Println(result.Token)
}
return nil
}
func init() {
parser.AddCommand("login", "Login", "", &LoginCommand{})
}