telebit/internal/mgmt/auth.go

70 lines
1.7 KiB
Go
Raw Normal View History

2020-06-01 07:38:18 +00:00
package mgmt
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
2020-07-21 06:35:45 +00:00
"os"
2020-06-01 07:38:18 +00:00
2020-07-21 06:35:45 +00:00
telebit "git.rootprojects.org/root/telebit"
2020-07-20 22:20:59 +00:00
"git.rootprojects.org/root/telebit/dbg"
2020-11-13 09:43:17 +00:00
"git.rootprojects.org/root/telebit/internal/mgmt/authstore"
2020-06-01 07:38:18 +00:00
)
type SuccessResponse struct {
Success bool `json:"success"`
}
func Ping(authURL, token string) error {
msg, err := telebit.Request("POST", authURL+"/ping", token, nil)
if nil != err {
return err
}
if nil == msg {
return fmt.Errorf("invalid response")
}
resp := SuccessResponse{}
err = json.NewDecoder(msg).Decode(&resp)
if err != nil {
return err
}
if true != resp.Success {
return fmt.Errorf("expected successful response")
}
return nil
}
2020-06-01 07:38:18 +00:00
func Register(authURL, secret, ppid string) (kid string, err error) {
pub := authstore.ToPublicKeyString(ppid)
jsons := fmt.Sprintf(`{ "machine_ppid": "%s", "public_key": "%s" }`, ppid, pub)
jsonb := bytes.NewBuffer([]byte(jsons))
fullURL := authURL + "/register-device/" + secret
if dbg.Debug {
2020-07-21 06:35:45 +00:00
fmt.Fprintf(os.Stderr, "[debug] authURL=%s, secret=%s, ppid=%s\n", fullURL, secret, jsons)
}
msg, err := telebit.Request("POST", fullURL, "", jsonb)
2020-06-01 07:38:18 +00:00
if nil != err {
return "", err
}
if nil == msg {
return "", fmt.Errorf("invalid response")
}
auth := &authstore.Authorization{}
2020-07-22 05:47:47 +00:00
msgBytes, _ := ioutil.ReadAll(msg)
//err = json.NewDecoder(msg).Decode(auth)
err = json.Unmarshal(msgBytes, auth)
2020-06-01 07:38:18 +00:00
if err != nil {
return "", err
}
2020-07-22 05:47:47 +00:00
//msgBytes, _ := ioutil.ReadAll(msg)
2020-06-01 07:38:18 +00:00
if "" == auth.PublicKey {
return "", fmt.Errorf("unexpected server response: no public key: %s", string(msgBytes))
}
if pub != auth.PublicKey {
return "", fmt.Errorf("server disagrees about public key id: %s vs %s", kid, auth.PublicKey)
}
return auth.PublicKey, nil
}