nodeHttpController.go 24 KB

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