Skip to content

Commit

Permalink
Update: delete synced records vs delete all ts records
Browse files Browse the repository at this point in the history
  • Loading branch information
aaanh committed May 26, 2024
1 parent 7b33a45 commit dfc1f75
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 34 deletions.
4 changes: 2 additions & 2 deletions app/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func viewCurrentConfigs(cfg *structs.Config) {
// return nil
// }

func performSync(config *structs.Config) {
func performSync(config *structs.Config, added *structs.Devices) {
cf.CheckCloudflareToken(config)
cf.AddCloudflareDnsRecords(config, ts.GetTailscaleDevices(config))
cf.AddCloudflareDnsRecords(config, ts.GetTailscaleDevices(config), added)
}
20 changes: 12 additions & 8 deletions app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func displayHeader(version string) {
fmt.Println()
}

func choiceHandler(choice int, config *structs.Config) {
func choiceHandler(choice int, config *structs.Config, added *structs.Devices) {
switch choice {
case 1:
ts.ConfigureTailscale(config)
Expand All @@ -31,12 +31,14 @@ func choiceHandler(choice int, config *structs.Config) {
case 4:
cf.ConfigureCloudflareZoneId(config)
case 5:
performSync(config)
performSync(config, added)
case 6:
cf.DeleteAddedDnsRecords(config)
cf.DeleteAddedDnsRecords(config, added)
case 7:
viewCurrentConfigs(config)
cf.DeleteAllTailscaleRecords(config)
case 8:
viewCurrentConfigs(config)
case 9:
{
fmt.Println("\n=== Thanks for using Tailflare :> ===")
os.Exit(0)
Expand All @@ -48,12 +50,12 @@ func choiceHandler(choice int, config *structs.Config) {
}
}

func program(config *structs.Config) {
func program(config *structs.Config, added *structs.Devices) {
for {
updateStates(config)
displayHeader(config.Version)
choice := Menu(config)
choiceHandler(choice, config)
choiceHandler(choice, config, added)
}
}

Expand All @@ -70,6 +72,8 @@ func main() {
var tailnetOrg string
var cloudflareZoneId string

var added structs.Devices

defer func() {
if err := recover(); err != nil {
fmt.Println("Panic occurred during environment variable load.")
Expand All @@ -92,7 +96,7 @@ func main() {
},
}

program(&config)
program(&config, &added)
}
}()
env.Load("./config.cfg", "./.env")
Expand All @@ -114,6 +118,6 @@ func main() {
},
}

program(&config)
program(&config, &added)

}
17 changes: 9 additions & 8 deletions app/menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,39 @@ import (

func Menu(cfg *structs.Config) int {
menuOptions := map[int]string{
1: fmt.Sprintf("Configure Tailscale API key (%s)", func() string {
1: fmt.Sprintf("[#] Configure Tailscale API key (%s)", func() string {
if cfg.States.TailscaleKeyExist {
return "Added"
} else {
return "Not added"
}
}()),
2: fmt.Sprintf("Configure Tailnet Organization (%s)", func() string {
2: fmt.Sprintf("[#] Configure Tailnet Organization (%s)", func() string {
if cfg.States.TailnetOrgExist {
return cfg.TailnetOrg
} else {
return "Not added"
}
}()),
3: fmt.Sprintf("Configure Cloudflare API key (%s)", func() string {
3: fmt.Sprintf("[#] Configure Cloudflare API key (%s)", func() string {
if cfg.States.CloudflareKeyExist {
return "Added"
} else {
return "Not added"
}
}()),
4: fmt.Sprintf("Configure Cloudflare Zone ID (%s - %s)", cf.GetDomainFromZoneId(cfg), func() string {
4: fmt.Sprintf("[#] Configure Cloudflare Zone ID (%s - %s)", cf.GetDomainFromZoneId(cfg), func() string {
if cfg.States.CloudflareZoneIdExist {
return cfg.CloudflareZoneId
} else {
return "Not added"
}
}()),
5: "Perform Sync",
6: "Delete synced records",
7: "View configurations and keys",
8: "Exit",
5: "[+] Perform Sync",
6: "[-] Delete synced records",
7: "[-] Delete all Tailscale records from Cloudflare",
8: "[i] View configurations and keys",
9: "[x] Exit",
}

// Solve the misordered printing by sorting the keys in the map
Expand Down
77 changes: 61 additions & 16 deletions lib/cloudflare/cf.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,34 @@ func CheckCloudflareToken(config *structs.Config) {
func ConstructCloudflareDnsPayload(device structs.Device, uri string) structs.Payload {
deviceName := strings.Split(device.Name, ".")[0]

payload := structs.Payload{
Content: device.Addresses[0],
Name: deviceName + "." + uri,
Proxied: false,
Type: "A",
Ttl: 3600,
}
if len(uri) == 0 {
payload := structs.Payload{
Content: device.Addresses[0],
Name: deviceName,
Proxied: false,
Type: "A",
Ttl: 3600,
}

return payload
return payload
} else {
payload := structs.Payload{
Content: device.Addresses[0],
Name: deviceName + "." + uri,
Proxied: false,
Type: "A",
Ttl: 3600,
}

return payload
}
}

func AddCloudflareDnsRecords(config *structs.Config, devices structs.Devices) {
fmt.Println("Enter your domain URI (e.g. devices.my-domain.com)")
func AddCloudflareDnsRecords(config *structs.Config, devices structs.Devices, added *structs.Devices) {
fmt.Println("Enter your subdomain URI, if left blank, the added record will be some-device.domain-name.tld")
fmt.Printf("> ")
var discard string
fmt.Scanln(&discard)
var uri string
fmt.Scanln(&uri)

Expand All @@ -97,6 +111,7 @@ func AddCloudflareDnsRecords(config *structs.Config, devices structs.Devices) {
fmt.Printf(">>> Adding device %d\n", idx)
payload := ConstructCloudflareDnsPayload(device, uri)
marshalled, err := json.Marshal(payload)

if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
Expand All @@ -114,9 +129,15 @@ func AddCloudflareDnsRecords(config *structs.Config, devices structs.Devices) {

defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
var unmarshalledBody structs.CloudflareAddedRecords
_ = json.Unmarshal(body, &unmarshalledBody)

fmt.Println(res)
fmt.Println(string(body))
if unmarshalledBody.Success {
added.Devices = append(added.Devices, device)
added.Devices[len(added.Devices)-1].Id = unmarshalledBody.Result.Id
}

fmt.Printf("%+v\n", unmarshalledBody)
fmt.Printf("\n\n")
}
}
Expand Down Expand Up @@ -176,7 +197,34 @@ func GetDnsRecordsFromZoneId(cfg *structs.Config) []structs.CloudflareDnsRecord
return records
}

func DeleteAddedDnsRecords(cfg *structs.Config) {
func DeleteAddedDnsRecords(cfg *structs.Config, added *structs.Devices) {
client := &http.Client{}
endpoints := utils.GenerateEndpoints(cfg)

for _, device := range added.Devices {
fmt.Printf(">>> Deleting record %+v\n", device)
fmt.Println(device.Id)
req, _ := http.NewRequest("DELETE", endpoints.CloudflareDeleteRecordById+"/"+device.Id, nil)

req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+cfg.Keys.CloudflareApiKey)

res, err := client.Do(req)
if err != nil {
fmt.Println(">>> Error occurred with Cloudflare API request.")
}

defer res.Body.Close()
body, _ := io.ReadAll(res.Body)

fmt.Println(res)
fmt.Println(string(body))
fmt.Printf("\n\n")
}

}

func DeleteAllTailscaleRecords(cfg *structs.Config) {
devices := tailscale.GetTailscaleDevices(cfg)
var devicesToDelete []struct {
Name string
Expand All @@ -199,10 +247,8 @@ func DeleteAddedDnsRecords(cfg *structs.Config) {
for _, r := range records {
// Iterate over elements in array B
for _, d := range devicesToDelete {
fmt.Println(strings.Split(d.Name, ".")[0] + " == " + strings.Split(r.Name, ".")[0] + " - " + r.Content + " == " + d.Ipv4)
if strings.Split(r.Name, ".")[0] == strings.Split(d.Name, ".")[0] && r.Content == d.Ipv4 {
recordsToDelete = append(recordsToDelete, r.Id)
fmt.Println(recordsToDelete)
}
}
}
Expand Down Expand Up @@ -230,5 +276,4 @@ func DeleteAddedDnsRecords(cfg *structs.Config) {
fmt.Println(string(body))
fmt.Printf("\n\n")
}

}
5 changes: 5 additions & 0 deletions lib/structs/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,8 @@ type CloudflareDnsRecord struct {
type CloudflareDnsRecordsResponse struct {
Result []CloudflareDnsRecord `json:"result"`
}

type CloudflareAddedRecords struct {
Result CloudflareDnsRecord `json:"result"`
Success bool
}

0 comments on commit dfc1f75

Please sign in to comment.