csctl/internal/daemon.go

95 lines
2.3 KiB
Go
Raw Normal View History

2020-12-18 20:25:22 -05:00
package internal
import (
"bufio"
"crypto/hmac"
"crypto/sha256"
"csctl/config"
// "csctl/config"
"encoding/hex"
"encoding/json"
"net"
"strings"
"time"
)
// TCPData is a struct of information to be sent over to the CS daemon
type TCPData struct {
Username, Type, Message string
}
// Account struct for user account information
type Account struct {
Username string `json:"username"`
UserID string `json:"userID"`
EmailAddress string `json:"emailAddress"`
CreatedBy string `json:"createdBy"`
CreatedAt time.Time `json:"createdAt"`
Locked bool `json:"locked"`
Tier int `json:"tier"`
SupportKey string `json:"supportKey"`
ReferralCode string `json:"referralCode"`
TotalReferrals int `json:"totalReferrals"`
Root bool `json:"root"`
}
// FetchAccount is a helper function that fetches account information from CSD
func FetchAccount(username string) (*Account, error) {
data, err := ContactSR(&TCPData{
Username: username,
Type: "userinfo",
})
if err != nil {
return nil, err
}
var account Account
2020-12-25 17:20:30 -05:00
if err := json.Unmarshal([]byte(data), &account); err != nil {
2020-12-18 20:25:22 -05:00
return nil, err
}
return &account, nil
}
// Contact one way contact function, sends message to CSD. Doesn't expect response back.
func Contact(data *TCPData) error {
conn, err := net.Dial("tcp", "localhost:8124")
if err != nil {
return err
}
newHmac := hmac.New(sha256.New, config.FetchHMACKey())
jsonMarshal, err := json.Marshal(data)
if err != nil {
return err
}
newHmac.Write(jsonMarshal)
encoded := hex.EncodeToString(newHmac.Sum(nil))
write := string(jsonMarshal) + "$" + encoded
conn.Write([]byte(write))
conn.Close()
return nil
}
// ContactSR two-way communication with CSD
func ContactSR(data *TCPData) (string, error) {
conn, err := net.Dial("tcp", "localhost:8124")
if err != nil {
return "", err
}
newHmac := hmac.New(sha256.New, config.FetchHMACKey())
jsonMarshal, err := json.Marshal(data)
if err != nil {
return "", err
}
newHmac.Write(jsonMarshal)
encoded := hex.EncodeToString(newHmac.Sum(nil))
write := string(jsonMarshal) + "$" + encoded
conn.Write([]byte(write))
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
return "", err
}
defer conn.Close()
return strings.ReplaceAll(message, "\n", ""), nil
}