nodeHttpController.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. package controller
  2. import (
  3. "github.com/gravitl/netmaker/models"
  4. "errors"
  5. "github.com/gravitl/netmaker/functions"
  6. "github.com/gravitl/netmaker/mongoconn"
  7. "golang.org/x/crypto/bcrypt"
  8. "time"
  9. "strings"
  10. "fmt"
  11. "context"
  12. "encoding/json"
  13. "net/http"
  14. "github.com/gorilla/mux"
  15. "go.mongodb.org/mongo-driver/bson"
  16. "go.mongodb.org/mongo-driver/mongo/options"
  17. )
  18. func nodeHandlers(r *mux.Router) {
  19. r.HandleFunc("/api/nodes", authorize(false, "master", http.HandlerFunc(getAllNodes))).Methods("GET")
  20. r.HandleFunc("/api/nodes/{network}", authorize(true, "network", http.HandlerFunc(getNetworkNodes))).Methods("GET")
  21. r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
  22. r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
  23. r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
  24. r.HandleFunc("/api/nodes/{network}/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
  25. r.HandleFunc("/api/nodes/{network}/{macaddress}/creategateway", authorize(true, "master", http.HandlerFunc(createGateway))).Methods("POST")
  26. r.HandleFunc("/api/nodes/{network}/{macaddress}/deletegateway", authorize(true, "master", http.HandlerFunc(deleteGateway))).Methods("DELETE")
  27. r.HandleFunc("/api/nodes/{network}/{macaddress}/approve", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
  28. r.HandleFunc("/api/nodes/{network}", createNode).Methods("POST")
  29. r.HandleFunc("/api/nodes/adm/{network}/lastmodified", authorize(true, "network", http.HandlerFunc(getLastModified))).Methods("GET")
  30. r.HandleFunc("/api/nodes/adm/{network}/authenticate", authenticate).Methods("POST")
  31. }
  32. //Node authenticates using its password and retrieves a JWT for authorization.
  33. func authenticate(response http.ResponseWriter, request *http.Request) {
  34. //Auth request consists of Mac Address and Password (from node that is authorizing
  35. //in case of Master, auth is ignored and mac is set to "mastermac"
  36. var authRequest models.AuthParams
  37. var result models.Node
  38. var errorResponse = models.ErrorResponse{
  39. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  40. }
  41. //Get password fnd mac rom request
  42. decoder := json.NewDecoder(request.Body)
  43. decoderErr := decoder.Decode(&authRequest)
  44. defer request.Body.Close()
  45. if decoderErr != nil {
  46. returnErrorResponse(response, request, errorResponse)
  47. return
  48. } else {
  49. errorResponse.Code = http.StatusBadRequest
  50. if authRequest.MacAddress == "" {
  51. errorResponse.Message = "W1R3: MacAddress can't be empty"
  52. returnErrorResponse(response, request, errorResponse)
  53. return
  54. } else if authRequest.Password == "" {
  55. errorResponse.Message = "W1R3: Password can't be empty"
  56. returnErrorResponse(response, request, errorResponse)
  57. return
  58. } else {
  59. //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
  60. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  61. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  62. var err = collection.FindOne(ctx, bson.M{ "macaddress": authRequest.MacAddress, "ispending": false }).Decode(&result)
  63. defer cancel()
  64. if err != nil {
  65. returnErrorResponse(response, request, errorResponse)
  66. return
  67. }
  68. //compare password from request to stored password in database
  69. //might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text...
  70. //TODO: Consider a way of hashing the password client side before sending, or using certificates
  71. err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password))
  72. if err != nil {
  73. returnErrorResponse(response, request, errorResponse)
  74. return
  75. } else {
  76. //Create a new JWT for the node
  77. tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Network)
  78. if tokenString == "" {
  79. returnErrorResponse(response, request, errorResponse)
  80. return
  81. }
  82. var successResponse = models.SuccessResponse{
  83. Code: http.StatusOK,
  84. Message: "W1R3: Device " + authRequest.MacAddress + " Authorized",
  85. Response: models.SuccessfulLoginResponse{
  86. AuthToken: tokenString,
  87. MacAddress: authRequest.MacAddress,
  88. },
  89. }
  90. //Send back the JWT
  91. successJSONResponse, jsonError := json.Marshal(successResponse)
  92. if jsonError != nil {
  93. returnErrorResponse(response, request, errorResponse)
  94. return
  95. }
  96. response.WriteHeader(http.StatusOK)
  97. response.Header().Set("Content-Type", "application/json")
  98. response.Write(successJSONResponse)
  99. }
  100. }
  101. }
  102. }
  103. //The middleware for most requests to the API
  104. //They all pass through here first
  105. //This will validate the JWT (or check for master token)
  106. //This will also check against the authNetwork and make sure the node should be accessing that endpoint,
  107. //even if it's technically ok
  108. //This is kind of a poor man's RBAC. There's probably a better/smarter way.
  109. //TODO: Consider better RBAC implementations
  110. func authorize(networkCheck bool, authNetwork string, next http.Handler) http.HandlerFunc {
  111. return func(w http.ResponseWriter, r *http.Request) {
  112. var errorResponse = models.ErrorResponse{
  113. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  114. }
  115. var params = mux.Vars(r)
  116. networkexists, _ := functions.NetworkExists(params["network"])
  117. //check that the request is for a valid network
  118. //if (networkCheck && !networkexists) || err != nil {
  119. if (networkCheck && !networkexists) {
  120. errorResponse = models.ErrorResponse{
  121. Code: http.StatusNotFound, Message: "W1R3: This network does not exist. ",
  122. }
  123. returnErrorResponse(w, r, errorResponse)
  124. return
  125. } else {
  126. w.Header().Set("Content-Type", "application/json")
  127. //get the auth token
  128. bearerToken := r.Header.Get("Authorization")
  129. var tokenSplit = strings.Split(bearerToken, " ")
  130. //I put this in in case the user doesn't put in a token at all (in which case it's empty)
  131. //There's probably a smarter way of handling this.
  132. var authToken = "928rt238tghgwe@TY@$Y@#WQAEGB2FC#@HG#@$Hddd"
  133. if len(tokenSplit) > 1 {
  134. authToken = tokenSplit[1]
  135. } else {
  136. errorResponse = models.ErrorResponse{
  137. Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
  138. }
  139. returnErrorResponse(w, r, errorResponse)
  140. return
  141. }
  142. //This checks if
  143. //A: the token is the master password
  144. //B: the token corresponds to a mac address, and if so, which one
  145. //TODO: There's probably a better way of dealing with the "master token"/master password. Plz Halp.
  146. macaddress, _, err := functions.VerifyToken(authToken)
  147. if err != nil {
  148. errorResponse = models.ErrorResponse{
  149. Code: http.StatusUnauthorized, Message: "W1R3: Error Verifying Auth Token.",
  150. }
  151. returnErrorResponse(w, r, errorResponse)
  152. return
  153. }
  154. var isAuthorized = false
  155. //The mastermac (login with masterkey from config) can do everything!! May be dangerous.
  156. if macaddress == "mastermac" {
  157. isAuthorized = true
  158. //for everyone else, there's poor man's RBAC. The "cases" are defined in the routes in the handlers
  159. //So each route defines which access network should be allowed to access it
  160. } else {
  161. switch authNetwork {
  162. case "all":
  163. isAuthorized = true
  164. case "nodes":
  165. isAuthorized = (macaddress != "")
  166. case "network":
  167. node, err := functions.GetNodeByMacAddress(params["network"], macaddress)
  168. if err != nil {
  169. errorResponse = models.ErrorResponse{
  170. Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
  171. }
  172. returnErrorResponse(w, r, errorResponse)
  173. return
  174. }
  175. isAuthorized = (node.Network == params["network"])
  176. case "node":
  177. isAuthorized = (macaddress == params["macaddress"])
  178. case "master":
  179. isAuthorized = (macaddress == "mastermac")
  180. default:
  181. isAuthorized = false
  182. }
  183. }
  184. if !isAuthorized {
  185. errorResponse = models.ErrorResponse{
  186. Code: http.StatusUnauthorized, Message: "W1R3: You are unauthorized to access this endpoint.",
  187. }
  188. returnErrorResponse(w, r, errorResponse)
  189. return
  190. } else {
  191. //If authorized, this function passes along it's request and output to the appropriate route function.
  192. next.ServeHTTP(w, r)
  193. }
  194. }
  195. }
  196. }
  197. //Gets all nodes associated with network, including pending nodes
  198. func getNetworkNodes(w http.ResponseWriter, r *http.Request) {
  199. w.Header().Set("Content-Type", "application/json")
  200. var nodes []models.ReturnNode
  201. var params = mux.Vars(r)
  202. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  203. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  204. filter := bson.M{"network": params["network"]}
  205. //Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
  206. cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
  207. if err != nil {
  208. returnErrorResponse(w,r,formatError(err, "internal"))
  209. return
  210. }
  211. defer cancel()
  212. for cur.Next(context.TODO()) {
  213. //Using a different model for the ReturnNode (other than regular node).
  214. //Either we should do this for ALL structs (so Networks and Keys)
  215. //OR we should just use the original struct
  216. //My preference is to make some new return structs
  217. //TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
  218. var node models.ReturnNode
  219. err := cur.Decode(&node)
  220. if err != nil {
  221. returnErrorResponse(w,r,formatError(err, "internal"))
  222. return
  223. }
  224. // add item our array of nodes
  225. nodes = append(nodes, node)
  226. }
  227. //TODO: Another fatal error we should take care of.
  228. if err := cur.Err(); err != nil {
  229. returnErrorResponse(w,r,formatError(err, "internal"))
  230. return
  231. }
  232. //Returns all the nodes in JSON format
  233. w.WriteHeader(http.StatusOK)
  234. json.NewEncoder(w).Encode(nodes)
  235. }
  236. //A separate function to get all nodes, not just nodes for a particular network.
  237. //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
  238. func getAllNodes(w http.ResponseWriter, r *http.Request) {
  239. w.Header().Set("Content-Type", "application/json")
  240. var nodes []models.ReturnNode
  241. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  242. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  243. // Filter out them ID's again
  244. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  245. if err != nil {
  246. returnErrorResponse(w,r,formatError(err, "internal"))
  247. return
  248. }
  249. defer cancel()
  250. for cur.Next(context.TODO()) {
  251. var node models.ReturnNode
  252. err := cur.Decode(&node)
  253. if err != nil {
  254. returnErrorResponse(w,r,formatError(err, "internal"))
  255. return
  256. }
  257. // add node to our array
  258. nodes = append(nodes, node)
  259. }
  260. //TODO: Fatal error
  261. if err := cur.Err(); err != nil {
  262. returnErrorResponse(w,r,formatError(err, "internal"))
  263. return
  264. }
  265. //Return all the nodes in JSON format
  266. w.WriteHeader(http.StatusOK)
  267. json.NewEncoder(w).Encode(nodes)
  268. }
  269. //This function get's called when a node "checks in" at check in interval
  270. //Honestly I'm not sure what all it should be doing
  271. //TODO: Implement the necessary stuff, including the below
  272. //Check the last modified of the network
  273. //Check the last modified of the nodes
  274. //Write functions for responding to these two thingies
  275. func checkIn(w http.ResponseWriter, r *http.Request) {
  276. //TODO: Current thoughts:
  277. //Dont bother with a networklastmodified
  278. //Instead, implement a "configupdate" boolean on nodes
  279. //when there is a network update that requrires a config update, then the node will pull its new config
  280. // set header.
  281. w.Header().Set("Content-Type", "application/json")
  282. var params = mux.Vars(r)
  283. var node models.Node
  284. //Retrieves node with DB Call which is inefficient. Let's just get the time and set it.
  285. //node = functions.GetNodeByMacAddress(params["network"], params["macaddress"])
  286. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  287. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  288. filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
  289. //old code was inefficient, this is all we need.
  290. time := time.Now().String()
  291. //node.SetLastCheckIn()
  292. // prepare update model with new time
  293. update := bson.D{
  294. {"$set", bson.D{
  295. {"lastcheckin", time},
  296. }},
  297. }
  298. err := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  299. defer cancel()
  300. if err != nil {
  301. returnErrorResponse(w,r,formatError(err, "internal"))
  302. return
  303. }
  304. //TODO: check node last modified vs network last modified
  305. w.WriteHeader(http.StatusOK)
  306. json.NewEncoder(w).Encode(node)
  307. }
  308. //Get an individual node. Nothin fancy here folks.
  309. func getNode(w http.ResponseWriter, r *http.Request) {
  310. // set header.
  311. w.Header().Set("Content-Type", "application/json")
  312. var params = mux.Vars(r)
  313. node, err := GetNode(params["macaddress"], params["network"])
  314. if err != nil {
  315. returnErrorResponse(w,r,formatError(err, "internal"))
  316. return
  317. }
  318. w.WriteHeader(http.StatusOK)
  319. json.NewEncoder(w).Encode(node)
  320. }
  321. //Get the time that a network of nodes was last modified.
  322. //TODO: This needs to be refactored
  323. //Potential way to do this: On UpdateNode, set a new field for "LastModified"
  324. //If we go with the existing way, we need to at least set network.NodesLastModified on UpdateNode
  325. func getLastModified(w http.ResponseWriter, r *http.Request) {
  326. // set header.
  327. w.Header().Set("Content-Type", "application/json")
  328. var network models.Network
  329. var params = mux.Vars(r)
  330. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  331. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  332. filter := bson.M{"netid": params["network"]}
  333. err := collection.FindOne(ctx, filter).Decode(&network)
  334. defer cancel()
  335. if err != nil {
  336. returnErrorResponse(w,r,formatError(err, "internal"))
  337. return
  338. }
  339. w.WriteHeader(http.StatusOK)
  340. w.Write([]byte(string(network.NodesLastModified)))
  341. }
  342. //This one's a doozy
  343. //To create a node
  344. //Must have valid key and be unique
  345. func createNode(w http.ResponseWriter, r *http.Request) {
  346. w.Header().Set("Content-Type", "application/json")
  347. var params = mux.Vars(r)
  348. var errorResponse = models.ErrorResponse{
  349. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  350. }
  351. networkName := params["network"]
  352. //Check if network exists first
  353. //TODO: This is inefficient. Let's find a better way.
  354. //Just a few rows down we grab the network anyway
  355. networkexists, err := functions.NetworkExists(networkName)
  356. if err != nil {
  357. returnErrorResponse(w,r,formatError(err, "internal"))
  358. return
  359. } else if !networkexists {
  360. errorResponse = models.ErrorResponse{
  361. Code: http.StatusNotFound, Message: "W1R3: Network does not exist! ",
  362. }
  363. returnErrorResponse(w, r, errorResponse)
  364. return
  365. }
  366. var node models.Node
  367. //get node from body of request
  368. err = json.NewDecoder(r.Body).Decode(&node)
  369. if err != nil {
  370. returnErrorResponse(w,r,formatError(err, "internal"))
  371. return
  372. }
  373. node.Network = networkName
  374. network, err := node.GetNetwork()
  375. if err != nil {
  376. returnErrorResponse(w,r,formatError(err, "internal"))
  377. return
  378. }
  379. //Check to see if key is valid
  380. //TODO: Triple inefficient!!! This is the third call to the DB we make for networks
  381. validKey := functions.IsKeyValid(networkName, node.AccessKey)
  382. if !validKey {
  383. //Check to see if network will allow manual sign up
  384. //may want to switch this up with the valid key check and avoid a DB call that way.
  385. if *network.AllowManualSignUp {
  386. node.IsPending = true
  387. } else {
  388. errorResponse = models.ErrorResponse{
  389. Code: http.StatusUnauthorized, Message: "W1R3: Key invalid, or none provided.",
  390. }
  391. returnErrorResponse(w, r, errorResponse)
  392. return
  393. }
  394. }
  395. err = ValidateNode("create", networkName, node)
  396. if err != nil {
  397. returnErrorResponse(w,r,formatError(err, "badrequest"))
  398. return
  399. }
  400. node, err = CreateNode(node, networkName)
  401. if err != nil {
  402. returnErrorResponse(w,r,formatError(err, "internal"))
  403. return
  404. }
  405. w.WriteHeader(http.StatusOK)
  406. json.NewEncoder(w).Encode(node)
  407. }
  408. //Takes node out of pending state
  409. //TODO: May want to use cordon/uncordon terminology instead of "ispending".
  410. func uncordonNode(w http.ResponseWriter, r *http.Request) {
  411. w.Header().Set("Content-Type", "application/json")
  412. var params = mux.Vars(r)
  413. var node models.Node
  414. node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
  415. if err != nil {
  416. returnErrorResponse(w,r,formatError(err, "internal"))
  417. return
  418. }
  419. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  420. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  421. // Create filter
  422. filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
  423. node.SetLastModified()
  424. fmt.Println("Uncordoning node " + node.Name)
  425. // prepare update model.
  426. update := bson.D{
  427. {"$set", bson.D{
  428. {"ispending", false},
  429. }},
  430. }
  431. err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  432. defer cancel()
  433. if err != nil {
  434. returnErrorResponse(w,r,formatError(err, "internal"))
  435. return
  436. }
  437. fmt.Println("Node " + node.Name + " uncordoned.")
  438. w.WriteHeader(http.StatusOK)
  439. json.NewEncoder(w).Encode("SUCCESS")
  440. }
  441. func createGateway(w http.ResponseWriter, r *http.Request) {
  442. w.Header().Set("Content-Type", "application/json")
  443. var params = mux.Vars(r)
  444. var gateway models.GatewayRequest
  445. err := json.NewDecoder(r.Body).Decode(&gateway)
  446. if err != nil {
  447. returnErrorResponse(w,r,formatError(err, "internal"))
  448. return
  449. }
  450. gateway.NetID = params["network"]
  451. gateway.NodeID = params["macaddress"]
  452. node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
  453. if err != nil {
  454. returnErrorResponse(w,r,formatError(err, "internal"))
  455. return
  456. }
  457. err = validateGateway(gateway)
  458. if err != nil {
  459. returnErrorResponse(w,r,formatError(err, "internal"))
  460. return
  461. }
  462. var nodechange models.Node
  463. nodechange.IsGateway = true
  464. nodechange.GatewayRange = gateway.RangeString
  465. if gateway.PostUp == "" {
  466. nodechange.PostUp = "iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o " + gateway.Interface + " -j MASQUERADE"
  467. } else {
  468. nodechange.PostUp = gateway.PostUp
  469. }
  470. if gateway.PostDown == "" {
  471. nodechange.PostDown = "iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o " + gateway.Interface + " -j MASQUERADE"
  472. } else {
  473. nodechange.PostDown = gateway.PostDown
  474. }
  475. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  476. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  477. // Create filter
  478. filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
  479. nodechange.SetLastModified()
  480. // prepare update model.
  481. update := bson.D{
  482. {"$set", bson.D{
  483. {"postup", nodechange.PostUp},
  484. {"postdown", nodechange.PostDown},
  485. {"isgateway", nodechange.IsGateway},
  486. {"gatewayrange", nodechange.GatewayRange},
  487. {"lastmodified", nodechange.LastModified},
  488. }},
  489. }
  490. var nodeupdate models.Node
  491. err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&nodeupdate)
  492. defer cancel()
  493. if err != nil {
  494. returnErrorResponse(w,r,formatError(err, "internal"))
  495. return
  496. }
  497. err = SetNetworkNodesLastModified(params["network"])
  498. if err != nil {
  499. returnErrorResponse(w,r,formatError(err, "internal"))
  500. return
  501. }
  502. w.WriteHeader(http.StatusOK)
  503. json.NewEncoder(w).Encode(node)
  504. }
  505. func validateGateway(gateway models.GatewayRequest) error {
  506. var err error
  507. isIpv4 := functions.IsIpv4CIDR(gateway.RangeString)
  508. empty := gateway.RangeString == ""
  509. if empty || !isIpv4 {
  510. err = errors.New("IP Range Not Valid")
  511. }
  512. return err
  513. }
  514. func deleteGateway(w http.ResponseWriter, r *http.Request) {
  515. w.Header().Set("Content-Type", "application/json")
  516. var params = mux.Vars(r)
  517. node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
  518. if err != nil {
  519. returnErrorResponse(w,r,formatError(err, "internal"))
  520. return
  521. }
  522. var nodechange models.Node
  523. nodechange.IsGateway = false
  524. nodechange.GatewayRange = ""
  525. nodechange.PostUp = ""
  526. nodechange.PostDown = ""
  527. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  528. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  529. // Create filter
  530. filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
  531. nodechange.SetLastModified()
  532. // prepare update model.
  533. update := bson.D{
  534. {"$set", bson.D{
  535. {"postup", nodechange.PostUp},
  536. {"preup", nodechange.PostDown},
  537. {"isgateway", nodechange.IsGateway},
  538. {"gatewayrange", nodechange.GatewayRange},
  539. {"lastmodified", nodechange.LastModified},
  540. }},
  541. }
  542. var nodeupdate models.Node
  543. err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&nodeupdate)
  544. defer cancel()
  545. if err != nil {
  546. returnErrorResponse(w,r,formatError(err, "internal"))
  547. return
  548. }
  549. err = SetNetworkNodesLastModified(params["networkname"])
  550. if err != nil {
  551. returnErrorResponse(w,r,formatError(err, "internal"))
  552. return
  553. }
  554. w.WriteHeader(http.StatusOK)
  555. json.NewEncoder(w).Encode(node)
  556. }
  557. func updateNode(w http.ResponseWriter, r *http.Request) {
  558. w.Header().Set("Content-Type", "application/json")
  559. var params = mux.Vars(r)
  560. //Get id from parameters
  561. //id, _ := primitive.ObjectIDFromHex(params["id"])
  562. var node models.Node
  563. //start here
  564. node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
  565. if err != nil {
  566. returnErrorResponse(w,r,formatError(err, "internal"))
  567. return
  568. }
  569. var nodechange models.Node
  570. // we decode our body request params
  571. _ = json.NewDecoder(r.Body).Decode(&nodechange)
  572. if nodechange.Network == "" {
  573. nodechange.Network = node.Network
  574. }
  575. if nodechange.MacAddress == "" {
  576. nodechange.MacAddress = node.MacAddress
  577. }
  578. err = ValidateNode("update", params["network"], nodechange)
  579. if err != nil {
  580. returnErrorResponse(w,r,formatError(err, "badrequest"))
  581. return
  582. }
  583. node, err = UpdateNode(nodechange, node)
  584. if err != nil {
  585. returnErrorResponse(w,r,formatError(err, "internal"))
  586. return
  587. }
  588. w.WriteHeader(http.StatusOK)
  589. json.NewEncoder(w).Encode(node)
  590. }
  591. //Delete a node
  592. //Pretty straightforward
  593. func deleteNode(w http.ResponseWriter, r *http.Request) {
  594. // Set header
  595. w.Header().Set("Content-Type", "application/json")
  596. // get params
  597. var params = mux.Vars(r)
  598. success, err := DeleteNode(params["macaddress"], params["network"])
  599. if err != nil {
  600. returnErrorResponse(w,r,formatError(err, "internal"))
  601. return
  602. } else if !success {
  603. err = errors.New("Could not delete node " + params["macaddress"])
  604. returnErrorResponse(w,r,formatError(err, "internal"))
  605. return
  606. }
  607. w.WriteHeader(http.StatusOK)
  608. json.NewEncoder(w).Encode(params["macaddress"] + " deleted.")
  609. }