portainer-devtool/go/tasks/jwt_token_gen.go

58 lines
1.2 KiB
Go
Raw Normal View History

2022-09-21 15:42:47 +10:00
package tasks
2022-09-22 11:56:37 +10:00
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"ocl/portainer-devtool/configs"
)
2022-09-21 15:42:47 +10:00
type GenerateJwtTokenTask struct {
Config *configs.Config
}
2022-09-22 11:56:37 +10:00
type GenerateJwtTokenResponse struct {
JWT string `json:"jwt"`
}
2022-09-21 15:42:47 +10:00
func NewGenerateJwtTokenTask(cfg *configs.Config) *GenerateJwtTokenTask {
return &GenerateJwtTokenTask{
Config: cfg,
}
}
func (task *GenerateJwtTokenTask) Execute() error {
2022-09-22 11:56:37 +10:00
postBody, _ := json.Marshal(map[string]string{
"username": task.Config.LoginCredential.Username,
"password": task.Config.LoginCredential.Password,
})
responseBody := bytes.NewBuffer(postBody)
resp, err := http.Post(task.Config.LoginCredential.Address, "application/json", responseBody)
if err != nil {
return fmt.Errorf("http requset error: %s", err.Error())
}
defer resp.Body.Close()
//Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to parse the response body: %s", err.Error())
}
var ret GenerateJwtTokenResponse
err = json.Unmarshal(body, &ret)
if err != nil {
return err
}
fmt.Printf("jwt token is:\n%s\n", ret.JWT)
2022-09-21 15:42:47 +10:00
return nil
}
func (task *GenerateJwtTokenTask) String() string {
2022-12-25 22:53:51 +11:00
return "Generate JWT Token"
2022-09-21 15:42:47 +10:00
}