forked from marcotuna/win-dns-api-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
213 lines (179 loc) · 6.63 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main
import (
"bitbucket.org/HelgeOlav/jwtauthrequest/jwtauthapi"
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"os/exec"
"regexp"
"strings"
)
var jwt *jwtauthapi.ClientConfig
// validateToken confirms if the passed token is valid, returns true if token is valid
func validateToken(req *http.Request) error {
if req == nil {
return errors.New("nil request passed")
}
// find token from http.Request
var token string
if keys, ok := req.URL.Query()[jwt.TokenName]; ok {
if len(keys) > 0 {
token = keys[0]
}
} else {
token = req.Header.Get(jwt.TokenName)
if len(jwt.TrimPrefix) > 0 {
token = strings.TrimPrefix(token, jwt.TrimPrefix)
}
}
// validate token
err := jwt.ValidateJWT(token)
if err != nil {
log.Println(err, token)
}
return err
}
// DoDNSSet Set
func DoDNSSet(w http.ResponseWriter, r *http.Request) {
// check JWT
{
err := validateToken(r)
if err != nil {
respondWithJSON(w, http.StatusForbidden, map[string]string{"message": err.Error()})
return
}
}
vars := mux.Vars(r)
zoneName, dnsType, nodeName, ipAddress := vars["zoneName"], vars["dnsType"], vars["nodeName"], vars["ipAddress"]
// Validate DNS Type
if dnsType != "A" {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "You specified an invalid record type ('" + dnsType + "'). Currently, only the 'A' (alias) record type is supported. e.g. /dns/my.zone/A/.."})
return
}
// Validate DNS Type
var validZoneName = regexp.MustCompile(`[^A-Za-z0-9\.-]+`)
if validZoneName.MatchString(zoneName) {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "Invalid zone name ('" + zoneName + "'). Zone names can only contain letters, numbers, dashes (-), and dots (.)."})
return
}
// Validate Node Name
var validNodeName = regexp.MustCompile(`[^A-Za-z0-9\.-]+`)
if validNodeName.MatchString(nodeName) {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "Invalid node name ('" + nodeName + "'). Node names can only contain letters, numbers, dashes (-), and dots (.)."})
return
}
// Validate Ip Address
var validIPAddress = regexp.MustCompile(`^(([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)$`)
if !validIPAddress.MatchString(ipAddress) {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "Invalid IP address ('" + ipAddress + "'). Currently, only IPv4 addresses are accepted."})
return
}
dnsCmdDeleteRecord := exec.Command("cmd", "/C", "dnscmd /recorddelete "+zoneName+" "+nodeName+" "+dnsType+" /f")
if err := dnsCmdDeleteRecord.Run(); err != nil {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": err.Error()})
return
}
dnsAddDeleteRecord := exec.Command("cmd", "/C", "dnscmd /recordadd "+zoneName+" "+nodeName+" "+dnsType+" "+ipAddress)
if err := dnsAddDeleteRecord.Run(); err != nil {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": err.Error()})
return
}
respondWithJSON(w, http.StatusOK, map[string]string{"message": "The alias ('A') record '" + nodeName + "." + zoneName + "' was successfully updated to '" + ipAddress + "'."})
}
// DoDNSRemove Remove
func DoDNSRemove(w http.ResponseWriter, r *http.Request) {
// check JWT
{
err := validateToken(r)
if err != nil {
respondWithJSON(w, http.StatusForbidden, map[string]string{"message": err.Error()})
return
}
}
vars := mux.Vars(r)
zoneName, dnsType, nodeName := vars["zoneName"], vars["dnsType"], vars["nodeName"]
// Validate DNS Type
if dnsType != "A" {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "You specified an invalid record type ('" + dnsType + "'). Currently, only the 'A' (alias) record type is supported. e.g. /dns/my.zone/A/.."})
return
}
// Validate DNS Type
var validZoneName = regexp.MustCompile(`[^A-Za-z0-9\.-]+`)
if validZoneName.MatchString(zoneName) {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "Invalid zone name ('" + zoneName + "'). Zone names can only contain letters, numbers, dashes (-), and dots (.)."})
return
}
// Validate Node Name
var validNodeName = regexp.MustCompile(`[^A-Za-z0-9\.-]+`)
if validNodeName.MatchString(nodeName) {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "Invalid node name ('" + nodeName + "'). Node names can only contain letters, numbers, dashes (-), and dots (.)."})
return
}
dnsCmdDeleteRecord := exec.Command("cmd", "/C", "dnscmd /recorddelete "+zoneName+" "+nodeName+" "+dnsType+" /f")
if err := dnsCmdDeleteRecord.Run(); err != nil {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": err.Error()})
return
}
respondWithJSON(w, http.StatusAccepted, map[string]string{"message": "The alias ('A') record '" + nodeName + "." + zoneName + "' was successfully removed."})
}
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
respondWithJSON(w, http.StatusBadRequest, map[string]string{"message": "Could not get the requested route."})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
const (
serverPort = 3111
)
func main() {
// load jwt config
var err error
jwt, err = jwtauthapi.LoadJsonFromFile("config.json")
if err != nil {
log.Println("Could not load config.json from current directoy, using defaults")
var myKeyAsByte = []byte("mysharedsecret")
tf := jwtauthapi.TokenFactory{
HMAC: myKeyAsByte,
Issuer: "win-dns-api-go",
ExpireTime: 60 * 60 * 24,
Audience: "win-dns-api-go",
Extras: nil,
}
tmpJwt := tf.GetClientConfig()
jwt = &tmpJwt
jwt.TokenName = "token"
token, err := tf.Issue()
if err != nil {
log.Fatalln(err)
}
log.Println("Debug token:", token)
}
// init
err = jwt.Init()
if err != nil {
log.Fatalln(err)
}
// start HTTP server
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(notFoundHandler)
r.Methods("GET").Path("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
respondWithJSON(w, http.StatusOK, map[string]string{"message": "Welcome to Win DNS API Go"})
})
r.Methods(http.MethodGet).Path("/dns/{zoneName}/{dnsType}/{nodeName}/set/{ipAddress}").HandlerFunc(DoDNSSet)
r.Methods(http.MethodGet).Path("/dns/{zoneName}/{dnsType}/{nodeName}/remove").HandlerFunc(DoDNSRemove)
r.Methods(http.MethodDelete).Path("/dns/{zoneName}/{dnsType}/{nodeName}").HandlerFunc(DoDNSRemove)
fmt.Printf("Listening on port %d.\n", serverPort)
// Start HTTP Server
if err := http.ListenAndServe(
fmt.Sprintf(":%d", serverPort),
r,
); err != nil {
log.Fatal(err)
}
}