extClientHttpController.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. // "fmt"
  8. "net/http"
  9. "time"
  10. "strconv"
  11. "github.com/gorilla/mux"
  12. "github.com/gravitl/netmaker/functions"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/mongoconn"
  15. "go.mongodb.org/mongo-driver/bson"
  16. "go.mongodb.org/mongo-driver/mongo/options"
  17. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  18. "github.com/skip2/go-qrcode"
  19. )
  20. func extClientHandlers(r *mux.Router) {
  21. r.HandleFunc("/api/extclients", securityCheck(http.HandlerFunc(getAllExtClients))).Methods("GET")
  22. r.HandleFunc("/api/extclients/{network}", securityCheck(http.HandlerFunc(getNetworkExtClients))).Methods("GET")
  23. r.HandleFunc("/api/extclients/{network}/{clientid}", securityCheck(http.HandlerFunc(getExtClient))).Methods("GET")
  24. r.HandleFunc("/api/extclients/{network}/{clientid}/{type}", securityCheck(http.HandlerFunc(getExtClientConf))).Methods("GET")
  25. r.HandleFunc("/api/extclients/{network}/{clientid}", securityCheck(http.HandlerFunc(updateExtClient))).Methods("PUT")
  26. r.HandleFunc("/api/extclients/{network}/{clientid}", securityCheck(http.HandlerFunc(deleteExtClient))).Methods("DELETE")
  27. r.HandleFunc("/api/extclients/{network}/{macaddress}", securityCheck(http.HandlerFunc(createExtClient))).Methods("POST")
  28. }
  29. // TODO: Implement Validation
  30. func ValidateExtClientCreate(networkName string, extclient models.ExtClient) error {
  31. // v := validator.New()
  32. // _ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
  33. // var isFieldUnique bool = functions.IsFieldUnique(networkName, "macaddress", extclient.MacAddress)
  34. // return isFieldUnique
  35. // })
  36. // _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  37. // _, err := extclient.GetNetwork()
  38. // return err == nil
  39. // })
  40. // err := v.Struct(extclient)
  41. // if err != nil {
  42. // for _, e := range err.(validator.ValidationErrors) {
  43. // fmt.Println(e)
  44. // }
  45. // }
  46. return nil
  47. }
  48. // TODO: Implement Validation
  49. func ValidateExtClientUpdate(networkName string, extclient models.ExtClient) error {
  50. // v := validator.New()
  51. // _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  52. // _, err := extclient.GetNetwork()
  53. // return err == nil
  54. // })
  55. // err := v.Struct(extclient)
  56. // if err != nil {
  57. // for _, e := range err.(validator.ValidationErrors) {
  58. // fmt.Println(e)
  59. // }
  60. // }
  61. return nil
  62. }
  63. func checkIngressExists(network string, macaddress string) bool {
  64. node, err := functions.GetNodeByMacAddress(network, macaddress)
  65. if err != nil {
  66. return false
  67. }
  68. return node.IsIngressGateway
  69. }
  70. //Gets all extclients associated with network, including pending extclients
  71. func getNetworkExtClients(w http.ResponseWriter, r *http.Request) {
  72. w.Header().Set("Content-Type", "application/json")
  73. var extclients []models.ExtClient
  74. var params = mux.Vars(r)
  75. extclients, err := GetNetworkExtClients(params["network"])
  76. if err != nil {
  77. returnErrorResponse(w, r, formatError(err, "internal"))
  78. return
  79. }
  80. //Returns all the extclients in JSON format
  81. w.WriteHeader(http.StatusOK)
  82. json.NewEncoder(w).Encode(extclients)
  83. }
  84. func GetNetworkExtClients(network string) ([]models.ExtClient, error) {
  85. var extclients []models.ExtClient
  86. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  87. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  88. filter := bson.M{"network": network}
  89. //Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
  90. cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
  91. if err != nil {
  92. return []models.ExtClient{}, err
  93. }
  94. defer cancel()
  95. for cur.Next(context.TODO()) {
  96. //Using a different model for the ReturnExtClient (other than regular extclient).
  97. //Either we should do this for ALL structs (so Networks and Keys)
  98. //OR we should just use the original struct
  99. //My preference is to make some new return structs
  100. //TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
  101. var extclient models.ExtClient
  102. err := cur.Decode(&extclient)
  103. if err != nil {
  104. return []models.ExtClient{}, err
  105. }
  106. // add item our array of extclients
  107. extclients = append(extclients, extclient)
  108. }
  109. //TODO: Another fatal error we should take care of.
  110. if err := cur.Err(); err != nil {
  111. return []models.ExtClient{}, err
  112. }
  113. return extclients, nil
  114. }
  115. //A separate function to get all extclients, not just extclients for a particular network.
  116. //Not quite sure if this is necessary. Probably necessary based on front end but may want to review after iteration 1 if it's being used or not
  117. func getAllExtClients(w http.ResponseWriter, r *http.Request) {
  118. w.Header().Set("Content-Type", "application/json")
  119. extclients, err := functions.GetAllExtClients()
  120. if err != nil {
  121. returnErrorResponse(w, r, formatError(err, "internal"))
  122. return
  123. }
  124. //Return all the extclients in JSON format
  125. w.WriteHeader(http.StatusOK)
  126. json.NewEncoder(w).Encode(extclients)
  127. }
  128. //Get an individual extclient. Nothin fancy here folks.
  129. func getExtClient(w http.ResponseWriter, r *http.Request) {
  130. // set header.
  131. w.Header().Set("Content-Type", "application/json")
  132. var params = mux.Vars(r)
  133. var extclient models.ExtClient
  134. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  135. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  136. filter := bson.M{"network": params["network"], "clientid": params["clientid"]}
  137. err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&extclient)
  138. if err != nil {
  139. returnErrorResponse(w, r, formatError(err, "internal"))
  140. return
  141. }
  142. defer cancel()
  143. w.WriteHeader(http.StatusOK)
  144. json.NewEncoder(w).Encode(extclient)
  145. }
  146. //Get an individual extclient. Nothin fancy here folks.
  147. func getExtClientConf(w http.ResponseWriter, r *http.Request) {
  148. // set header.
  149. w.Header().Set("Content-Type", "application/json")
  150. var params = mux.Vars(r)
  151. var extclient models.ExtClient
  152. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  153. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  154. filter := bson.M{"network": params["network"], "clientid": params["clientid"]}
  155. err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&extclient)
  156. if err != nil {
  157. returnErrorResponse(w, r, formatError(err, "internal"))
  158. return
  159. }
  160. gwnode, err := functions.GetNodeByMacAddress(extclient.Network, extclient.IngressGatewayID)
  161. if err != nil {
  162. fmt.Println("Could not retrieve Ingress Gateway Node " + extclient.IngressGatewayID)
  163. returnErrorResponse(w, r, formatError(err, "internal"))
  164. return
  165. }
  166. network, err := functions.GetParentNetwork(extclient.Network)
  167. if err != nil {
  168. fmt.Println("Could not retrieve Ingress Gateway Network " + extclient.Network)
  169. returnErrorResponse(w, r, formatError(err, "internal"))
  170. return
  171. }
  172. keepalive := ""
  173. if network.DefaultKeepalive != 0 {
  174. keepalive = "PersistentKeepalive = " + strconv.Itoa(int(network.DefaultKeepalive))
  175. }
  176. gwendpoint := gwnode.Endpoint + ":" + strconv.Itoa(int(gwnode.ListenPort))
  177. config := fmt.Sprintf(`[Interface]
  178. Address = %s
  179. PrivateKey = %s
  180. %s
  181. [Peer]
  182. PublicKey = %s
  183. AllowedIPs = %s
  184. Endpoint = %s
  185. `, extclient.Address + "/32",
  186. extclient.PrivateKey,
  187. keepalive,
  188. gwnode.PublicKey,
  189. network.AddressRange,
  190. gwendpoint)
  191. if params["type"] == "qr" {
  192. bytes, err := qrcode.Encode(config, qrcode.Medium, 220)
  193. if err != nil {
  194. returnErrorResponse(w, r, formatError(err, "internal"))
  195. return
  196. }
  197. w.Header().Set("Content-Type", "image/png")
  198. w.WriteHeader(http.StatusOK)
  199. _, err = w.Write(bytes)
  200. if err != nil {
  201. returnErrorResponse(w, r, formatError(err, "internal"))
  202. return
  203. }
  204. return
  205. }
  206. if params["type"] == "file" {
  207. name := extclient.ClientID + ".conf"
  208. w.Header().Set("Content-Type", "application/config")
  209. w.Header().Set("Content-Disposition", "attachment; filename=\"" + name + "\"")
  210. w.WriteHeader(http.StatusOK)
  211. _, err := fmt.Fprint(w, config)
  212. if err != nil {
  213. returnErrorResponse(w, r, formatError(err, "internal"))
  214. }
  215. return
  216. }
  217. defer cancel()
  218. w.WriteHeader(http.StatusOK)
  219. json.NewEncoder(w).Encode(extclient)
  220. }
  221. func CreateExtClient(extclient models.ExtClient) error {
  222. fmt.Println(extclient)
  223. // Generate Private Key for new ExtClient
  224. if extclient.PrivateKey == "" {
  225. privateKey, err := wgtypes.GeneratePrivateKey()
  226. if err != nil {
  227. return err
  228. }
  229. extclient.PrivateKey = privateKey.String()
  230. extclient.PublicKey = privateKey.PublicKey().String()
  231. }
  232. if extclient.Address == "" {
  233. newAddress, err := functions.UniqueAddress(extclient.Network)
  234. if err != nil {
  235. return err
  236. }
  237. extclient.Address = newAddress
  238. }
  239. extclient.LastModified = time.Now().Unix()
  240. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  241. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  242. // insert our network into the network table
  243. _, err := collection.InsertOne(ctx, extclient)
  244. defer cancel()
  245. return err
  246. }
  247. //This one's a doozy
  248. //To create a extclient
  249. //Must have valid key and be unique
  250. func createExtClient(w http.ResponseWriter, r *http.Request) {
  251. w.Header().Set("Content-Type", "application/json")
  252. var params = mux.Vars(r)
  253. networkName := params["network"]
  254. macaddress := params["macaddress"]
  255. //Check if network exists first
  256. //TODO: This is inefficient. Let's find a better way.
  257. //Just a few rows down we grab the network anyway
  258. ingressExists := checkIngressExists(networkName, macaddress)
  259. if !ingressExists {
  260. returnErrorResponse(w, r, formatError(errors.New("ingress does not exist"), "internal"))
  261. return
  262. }
  263. var extclient models.ExtClient
  264. extclient.Network = networkName
  265. extclient.IngressGatewayID = macaddress
  266. //get extclient from body of request
  267. err := json.NewDecoder(r.Body).Decode(&extclient)
  268. if err != nil {
  269. returnErrorResponse(w, r, formatError(err, "internal"))
  270. return
  271. }
  272. err = ValidateExtClientCreate(params["network"], extclient)
  273. if err != nil {
  274. returnErrorResponse(w, r, formatError(err, "badrequest"))
  275. return
  276. }
  277. err = CreateExtClient(extclient)
  278. if err != nil {
  279. returnErrorResponse(w, r, formatError(err, "internal"))
  280. return
  281. }
  282. w.WriteHeader(http.StatusOK)
  283. }
  284. func updateExtClient(w http.ResponseWriter, r *http.Request) {
  285. w.Header().Set("Content-Type", "application/json")
  286. var params = mux.Vars(r)
  287. var newExtClient models.ExtClient
  288. var oldExtClient models.ExtClient
  289. // we decode our body request params
  290. _ = json.NewDecoder(r.Body).Decode(&newExtClient)
  291. // TODO: Validation for update.
  292. // err := ValidateExtClientUpdate(params["network"], params["clientid"], newExtClient)
  293. // if err != nil {
  294. // returnErrorResponse(w, r, formatError(err, "badrequest"))
  295. // return
  296. // }
  297. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  298. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  299. filter := bson.M{"network": params["network"], "clientid": params["clientid"]}
  300. err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&oldExtClient)
  301. if err != nil {
  302. returnErrorResponse(w, r, formatError(err, "internal"))
  303. return
  304. }
  305. success, err := DeleteExtClient(params["network"], params["clientid"])
  306. if err != nil {
  307. returnErrorResponse(w, r, formatError(err, "internal"))
  308. return
  309. } else if !success {
  310. returnErrorResponse(w, r, formatError(err, "internal"))
  311. return
  312. }
  313. oldExtClient.ClientID = newExtClient.ClientID
  314. CreateExtClient(oldExtClient)
  315. if err != nil {
  316. returnErrorResponse(w, r, formatError(err, "internal"))
  317. return
  318. }
  319. w.WriteHeader(http.StatusOK)
  320. json.NewEncoder(w).Encode(oldExtClient)
  321. }
  322. func DeleteExtClient(network string, clientid string) (bool, error) {
  323. deleted := false
  324. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  325. filter := bson.M{"network": network, "clientid": clientid}
  326. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  327. result, err := collection.DeleteOne(ctx, filter)
  328. deletecount := result.DeletedCount
  329. if deletecount > 0 {
  330. deleted = true
  331. }
  332. defer cancel()
  333. fmt.Println("Deleted extclient client " + clientid + " from network " + network)
  334. return deleted, err
  335. }
  336. //Delete a extclient
  337. //Pretty straightforward
  338. func deleteExtClient(w http.ResponseWriter, r *http.Request) {
  339. // Set header
  340. w.Header().Set("Content-Type", "application/json")
  341. // get params
  342. var params = mux.Vars(r)
  343. success, err := DeleteExtClient(params["network"], params["clientid"])
  344. if err != nil {
  345. returnErrorResponse(w, r, formatError(err, "internal"))
  346. return
  347. } else if !success {
  348. err = errors.New("Could not delete extclient " + params["clientid"])
  349. returnErrorResponse(w, r, formatError(err, "internal"))
  350. return
  351. }
  352. returnSuccessResponse(w, r, params["clientid"]+" deleted.")
  353. }