nodeHttpController.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. package controller
  2. import (
  3. "github.com/gravitl/netmaker/models"
  4. "github.com/gravitl/netmaker/functions"
  5. "github.com/gravitl/netmaker/mongoconn"
  6. "golang.org/x/crypto/bcrypt"
  7. "time"
  8. "strings"
  9. "fmt"
  10. "context"
  11. "encoding/json"
  12. "log"
  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/{group}/nodes", authorize(true, "group", http.HandlerFunc(getGroupNodes))).Methods("GET")
  20. r.HandleFunc("/api/nodes", authorize(false, "master", http.HandlerFunc(getAllNodes))).Methods("GET")
  21. r.HandleFunc("/api/{group}/peerlist", authorize(true, "group", http.HandlerFunc(getPeerList))).Methods("GET")
  22. r.HandleFunc("/api/{group}/lastmodified", authorize(true, "group", http.HandlerFunc(getLastModified))).Methods("GET")
  23. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
  24. r.HandleFunc("/api/{group}/nodes", createNode).Methods("POST")
  25. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
  26. r.HandleFunc("/api/{group}/nodes/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
  27. r.HandleFunc("/api/{group}/nodes/{macaddress}/uncordon", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
  28. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
  29. r.HandleFunc("/api/{group}/authenticate", authenticate).Methods("POST")
  30. }
  31. //Node authenticates using its password and retrieves a JWT for authorization.
  32. func authenticate(response http.ResponseWriter, request *http.Request) {
  33. //Auth request consists of Mac Address and Password (from node that is authorizing
  34. //in case of Master, auth is ignored and mac is set to "mastermac"
  35. var authRequest models.AuthParams
  36. var result models.Node
  37. var errorResponse = models.ErrorResponse{
  38. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  39. }
  40. //Get password fnd mac rom request
  41. decoder := json.NewDecoder(request.Body)
  42. decoderErr := decoder.Decode(&authRequest)
  43. defer request.Body.Close()
  44. if decoderErr != nil {
  45. returnErrorResponse(response, request, errorResponse)
  46. } else {
  47. errorResponse.Code = http.StatusBadRequest
  48. if authRequest.MacAddress == "" {
  49. errorResponse.Message = "W1R3: MacAddress can't be empty"
  50. returnErrorResponse(response, request, errorResponse)
  51. } else if authRequest.Password == "" {
  52. errorResponse.Message = "W1R3: Password can't be empty"
  53. returnErrorResponse(response, request, errorResponse)
  54. } else {
  55. //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
  56. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  57. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  58. var err = collection.FindOne(ctx, bson.M{ "macaddress": authRequest.MacAddress, "ispending": false }).Decode(&result)
  59. defer cancel()
  60. if err != nil {
  61. returnErrorResponse(response, request, errorResponse)
  62. }
  63. //compare password from request to stored password in database
  64. //might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text...
  65. //TODO: Consider a way of hashing the password client side before sending, or using certificates
  66. err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password))
  67. if err != nil {
  68. returnErrorResponse(response, request, errorResponse)
  69. } else {
  70. //Create a new JWT for the node
  71. tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Group)
  72. if tokenString == "" {
  73. returnErrorResponse(response, request, errorResponse)
  74. }
  75. var successResponse = models.SuccessResponse{
  76. Code: http.StatusOK,
  77. Message: "W1R3: Device " + authRequest.MacAddress + " Authorized",
  78. Response: models.SuccessfulLoginResponse{
  79. AuthToken: tokenString,
  80. MacAddress: authRequest.MacAddress,
  81. },
  82. }
  83. //Send back the JWT
  84. successJSONResponse, jsonError := json.Marshal(successResponse)
  85. if jsonError != nil {
  86. returnErrorResponse(response, request, errorResponse)
  87. }
  88. response.Header().Set("Content-Type", "application/json")
  89. response.Write(successJSONResponse)
  90. }
  91. }
  92. }
  93. }
  94. //The middleware for most requests to the API
  95. //They all pass through here first
  96. //This will validate the JWT (or check for master token)
  97. //This will also check against the authGroup and make sure the node should be accessing that endpoint,
  98. //even if it's technically ok
  99. //This is kind of a poor man's RBAC. There's probably a better/smarter way.
  100. //TODO: Consider better RBAC implementations
  101. func authorize(groupCheck bool, authGroup string, next http.Handler) http.HandlerFunc {
  102. return func(w http.ResponseWriter, r *http.Request) {
  103. var errorResponse = models.ErrorResponse{
  104. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  105. }
  106. var params = mux.Vars(r)
  107. groupexists, _ := functions.GroupExists(params["group"])
  108. //check that the request is for a valid group
  109. //if (groupCheck && !groupexists) || err != nil {
  110. if (groupCheck && !groupexists) {
  111. errorResponse = models.ErrorResponse{
  112. Code: http.StatusNotFound, Message: "W1R3: This group does not exist. ",
  113. }
  114. returnErrorResponse(w, r, errorResponse)
  115. } else {
  116. w.Header().Set("Content-Type", "application/json")
  117. //get the auth token
  118. bearerToken := r.Header.Get("Authorization")
  119. var tokenSplit = strings.Split(bearerToken, " ")
  120. //I put this in in case the user doesn't put in a token at all (in which case it's empty)
  121. //There's probably a smarter way of handling this.
  122. var authToken = "928rt238tghgwe@TY@$Y@#WQAEGB2FC#@HG#@$Hddd"
  123. if len(tokenSplit) > 1 {
  124. authToken = tokenSplit[1]
  125. } else {
  126. errorResponse = models.ErrorResponse{
  127. Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
  128. }
  129. returnErrorResponse(w, r, errorResponse)
  130. }
  131. //This checks if
  132. //A: the token is the master password
  133. //B: the token corresponds to a mac address, and if so, which one
  134. //TODO: There's probably a better way of dealing with the "master token"/master password. Plz Halp.
  135. macaddress, _, err := functions.VerifyToken(authToken)
  136. if err != nil {
  137. errorResponse = models.ErrorResponse{
  138. Code: http.StatusUnauthorized, Message: "W1R3: Error Verifying Auth Token.",
  139. }
  140. returnErrorResponse(w, r, errorResponse)
  141. }
  142. var isAuthorized = false
  143. //The mastermac (login with masterkey from config) can do everything!! May be dangerous.
  144. if macaddress == "mastermac" {
  145. isAuthorized = true
  146. //for everyone else, there's poor man's RBAC. The "cases" are defined in the routes in the handlers
  147. //So each route defines which access group should be allowed to access it
  148. } else {
  149. switch authGroup {
  150. case "all":
  151. isAuthorized = true
  152. case "nodes":
  153. isAuthorized = (macaddress != "")
  154. case "group":
  155. node, err := functions.GetNodeByMacAddress(params["group"], macaddress)
  156. if err != nil {
  157. errorResponse = models.ErrorResponse{
  158. Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
  159. }
  160. returnErrorResponse(w, r, errorResponse)
  161. }
  162. isAuthorized = (node.Group == params["group"])
  163. case "node":
  164. isAuthorized = (macaddress == params["macaddress"])
  165. case "master":
  166. isAuthorized = (macaddress == "mastermac")
  167. default:
  168. isAuthorized = false
  169. }
  170. }
  171. if !isAuthorized {
  172. errorResponse = models.ErrorResponse{
  173. Code: http.StatusUnauthorized, Message: "W1R3: You are unauthorized to access this endpoint.",
  174. }
  175. returnErrorResponse(w, r, errorResponse)
  176. } else {
  177. //If authorized, this function passes along it's request and output to the appropriate route function.
  178. next.ServeHTTP(w, r)
  179. }
  180. }
  181. }
  182. }
  183. //Returns a list of peers in "plaintext" format, which can be piped straight to a file (peers.conf) on a local machine
  184. //Not sure if it would be better to do that here or to let the client handle the formatting.
  185. //TODO: May want to consider a different approach
  186. func getPeerList(w http.ResponseWriter, r *http.Request) {
  187. w.Header().Set("Content-Type", "application/json")
  188. var nodes []models.Node
  189. var params = mux.Vars(r)
  190. //Connection mongoDB with mongoconn class
  191. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  192. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  193. //Get all nodes in the relevant group which are NOT in pending state
  194. filter := bson.M{"group": params["group"], "ispending": false}
  195. cur, err := collection.Find(ctx, filter)
  196. if err != nil {
  197. mongoconn.GetError(err, w)
  198. return
  199. }
  200. // Close the cursor once finished and cancel if it takes too long
  201. defer cancel()
  202. for cur.Next(context.TODO()) {
  203. var node models.Node
  204. err := cur.Decode(&node)
  205. if err != nil {
  206. log.Fatal(err)
  207. }
  208. // add the node to our node array
  209. //maybe better to just return this? But then that's just GetNodes...
  210. nodes = append(nodes, node)
  211. }
  212. //Uh oh, fatal error! This needs some better error handling
  213. //TODO: needs appropriate error handling so the server doesnt shut down.
  214. if err := cur.Err(); err != nil {
  215. log.Fatal(err)
  216. }
  217. //Writes output in the style familiar to WireGuard
  218. //Get's piped to peers.conf locally after client request
  219. for _, n := range nodes {
  220. w.Write([]byte("[Peer] \n"))
  221. w.Write([]byte("PublicKey = " + n.PublicKey + "\n"))
  222. w.Write([]byte("AllowedIPs = " + n.Address + "/32" + "\n"))
  223. w.Write([]byte("PersistentKeepalive = " + fmt.Sprint(n.PersistentKeepalive) + "\n"))
  224. w.Write([]byte("Endpoint = " + n.Endpoint + ":" + fmt.Sprint(n.ListenPort) + "\n\n"))
  225. }
  226. }
  227. //Gets all nodes associated with group, including pending nodes
  228. func getGroupNodes(w http.ResponseWriter, r *http.Request) {
  229. w.Header().Set("Content-Type", "application/json")
  230. var nodes []models.ReturnNode
  231. var params = mux.Vars(r)
  232. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  233. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  234. filter := bson.M{"group": params["group"]}
  235. //Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
  236. cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
  237. if err != nil {
  238. mongoconn.GetError(err, w)
  239. return
  240. }
  241. defer cancel()
  242. for cur.Next(context.TODO()) {
  243. //Using a different model for the ReturnNode (other than regular node).
  244. //Either we should do this for ALL structs (so Groups and Keys)
  245. //OR we should just use the original struct
  246. //My preference is to make some new return structs
  247. //TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
  248. var node models.ReturnNode
  249. err := cur.Decode(&node)
  250. if err != nil {
  251. log.Fatal(err)
  252. }
  253. // add item our array of nodes
  254. nodes = append(nodes, node)
  255. }
  256. //TODO: Another fatal error we should take care of.
  257. if err := cur.Err(); err != nil {
  258. log.Fatal(err)
  259. }
  260. //Returns all the nodes in JSON format
  261. json.NewEncoder(w).Encode(nodes)
  262. }
  263. //A separate function to get all nodes, not just nodes for a particular group.
  264. //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
  265. func getAllNodes(w http.ResponseWriter, r *http.Request) {
  266. w.Header().Set("Content-Type", "application/json")
  267. var nodes []models.ReturnNode
  268. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  269. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  270. // Filter out them ID's again
  271. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  272. if err != nil {
  273. mongoconn.GetError(err, w)
  274. return
  275. }
  276. defer cancel()
  277. for cur.Next(context.TODO()) {
  278. var node models.ReturnNode
  279. err := cur.Decode(&node)
  280. //TODO: Fatal error
  281. if err != nil {
  282. log.Fatal(err)
  283. }
  284. // add node to our array
  285. nodes = append(nodes, node)
  286. }
  287. //TODO: Fatal error
  288. if err := cur.Err(); err != nil {
  289. log.Fatal(err)
  290. }
  291. //Return all the nodes in JSON format
  292. json.NewEncoder(w).Encode(nodes)
  293. }
  294. //This function get's called when a node "checks in" at check in interval
  295. //Honestly I'm not sure what all it should be doing
  296. //TODO: Implement the necessary stuff, including the below
  297. //Check the last modified of the group
  298. //Check the last modified of the nodes
  299. //Write functions for responding to these two thingies
  300. func checkIn(w http.ResponseWriter, r *http.Request) {
  301. //TODO: Current thoughts:
  302. //Dont bother with a grouplastmodified
  303. //Instead, implement a "configupdate" boolean on nodes
  304. //when there is a group update that requrires a config update, then the node will pull its new config
  305. // set header.
  306. w.Header().Set("Content-Type", "application/json")
  307. var params = mux.Vars(r)
  308. var node models.Node
  309. //Retrieves node with DB Call which is inefficient. Let's just get the time and set it.
  310. //node = functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  311. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  312. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  313. filter := bson.M{"macaddress": params["macaddress"]}
  314. //old code was inefficient, this is all we need.
  315. time := time.Now().String()
  316. //node.SetLastCheckIn()
  317. // prepare update model with new time
  318. update := bson.D{
  319. {"$set", bson.D{
  320. {"lastcheckin", time},
  321. }},
  322. }
  323. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  324. defer cancel()
  325. if errN != nil {
  326. mongoconn.GetError(errN, w)
  327. return
  328. }
  329. //TODO: check node last modified vs group last modified
  330. json.NewEncoder(w).Encode(node)
  331. }
  332. //Get an individual node. Nothin fancy here folks.
  333. func getNode(w http.ResponseWriter, r *http.Request) {
  334. // set header.
  335. w.Header().Set("Content-Type", "application/json")
  336. var params = mux.Vars(r)
  337. node, err := GetNode(params["macaddress"], params["group"])
  338. if err != nil {
  339. mongoconn.GetError(err, w)
  340. return
  341. }
  342. json.NewEncoder(w).Encode(node)
  343. }
  344. //Get the time that a group of nodes was last modified.
  345. //TODO: This needs to be refactored
  346. //Potential way to do this: On UpdateNode, set a new field for "LastModified"
  347. //If we go with the existing way, we need to at least set group.NodesLastModified on UpdateNode
  348. func getLastModified(w http.ResponseWriter, r *http.Request) {
  349. // set header.
  350. w.Header().Set("Content-Type", "application/json")
  351. var group models.Group
  352. var params = mux.Vars(r)
  353. collection := mongoconn.Client.Database("wirecat").Collection("groups")
  354. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  355. filter := bson.M{"nameid": params["group"]}
  356. err := collection.FindOne(ctx, filter).Decode(&group)
  357. defer cancel()
  358. if err != nil {
  359. fmt.Println(err)
  360. //log.Fatal(err)
  361. }
  362. w.Write([]byte(string(group.NodesLastModified)))
  363. }
  364. //This one's a doozy
  365. //To create a node
  366. //Must have valid key and be unique
  367. func createNode(w http.ResponseWriter, r *http.Request) {
  368. w.Header().Set("Content-Type", "application/json")
  369. var params = mux.Vars(r)
  370. var errorResponse = models.ErrorResponse{
  371. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  372. }
  373. groupName := params["group"]
  374. //Check if group exists first
  375. //TODO: This is inefficient. Let's find a better way.
  376. //Just a few rows down we grab the group anyway
  377. groupexists, errgroup := functions.GroupExists(groupName)
  378. if !groupexists || errgroup != nil {
  379. errorResponse = models.ErrorResponse{
  380. Code: http.StatusNotFound, Message: "W1R3: Group does not exist! ",
  381. }
  382. returnErrorResponse(w, r, errorResponse)
  383. return
  384. }
  385. var node models.Node
  386. //get node from body of request
  387. _ = json.NewDecoder(r.Body).Decode(&node)
  388. node.Group = groupName
  389. group, _ := node.GetGroup()
  390. //Check to see if key is valid
  391. //TODO: Triple inefficient!!! This is the third call to the DB we make for groups
  392. validKey := functions.IsKeyValid(groupName, node.AccessKey)
  393. if !validKey {
  394. //Check to see if group will allow manual sign up
  395. //may want to switch this up with the valid key check and avoid a DB call that way.
  396. if *group.AllowManualSignUp {
  397. node.IsPending = true
  398. } else {
  399. errorResponse = models.ErrorResponse{
  400. Code: http.StatusUnauthorized, Message: "W1R3: Key invalid, or none provided.",
  401. }
  402. returnErrorResponse(w, r, errorResponse)
  403. return
  404. }
  405. }
  406. err := ValidateNode("create", groupName, node)
  407. if err != nil {
  408. return
  409. }
  410. node, err = CreateNode(node, groupName)
  411. if err != nil {
  412. return
  413. }
  414. json.NewEncoder(w).Encode(node)
  415. }
  416. //Takes node out of pending state
  417. //TODO: May want to use cordon/uncordon terminology instead of "ispending".
  418. func uncordonNode(w http.ResponseWriter, r *http.Request) {
  419. w.Header().Set("Content-Type", "application/json")
  420. var params = mux.Vars(r)
  421. var node models.Node
  422. node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  423. if err != nil {
  424. mongoconn.GetError(err, w)
  425. return
  426. }
  427. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  428. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  429. // Create filter
  430. filter := bson.M{"macaddress": params["macaddress"]}
  431. node.SetLastModified()
  432. fmt.Println("Uncordoning node " + node.Name)
  433. // prepare update model.
  434. update := bson.D{
  435. {"$set", bson.D{
  436. {"ispending", false},
  437. }},
  438. }
  439. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  440. defer cancel()
  441. if errN != nil {
  442. mongoconn.GetError(errN, w)
  443. return
  444. }
  445. fmt.Println("Node " + node.Name + " uncordoned.")
  446. json.NewEncoder(w).Encode("SUCCESS")
  447. }
  448. func updateNode(w http.ResponseWriter, r *http.Request) {
  449. w.Header().Set("Content-Type", "application/json")
  450. var params = mux.Vars(r)
  451. //Get id from parameters
  452. //id, _ := primitive.ObjectIDFromHex(params["id"])
  453. var node models.Node
  454. //start here
  455. node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  456. if err != nil {
  457. json.NewEncoder(w).Encode(err)
  458. return
  459. }
  460. var nodechange models.Node
  461. // we decode our body request params
  462. _ = json.NewDecoder(r.Body).Decode(&nodechange)
  463. if nodechange.Group == "" {
  464. nodechange.Group = node.Group
  465. }
  466. if nodechange.MacAddress == "" {
  467. nodechange.MacAddress = node.MacAddress
  468. }
  469. err = ValidateNode("update", params["group"], nodechange)
  470. if err != nil {
  471. json.NewEncoder(w).Encode(err)
  472. return
  473. }
  474. node, err = UpdateNode(nodechange, node)
  475. if err != nil {
  476. json.NewEncoder(w).Encode(err)
  477. return
  478. }
  479. json.NewEncoder(w).Encode(node)
  480. }
  481. //Delete a node
  482. //Pretty straightforward
  483. func deleteNode(w http.ResponseWriter, r *http.Request) {
  484. // Set header
  485. w.Header().Set("Content-Type", "application/json")
  486. // get params
  487. var params = mux.Vars(r)
  488. success, err := DeleteNode(params["macaddress"], params["group"])
  489. if err != nil || !success {
  490. json.NewEncoder(w).Encode("Could not delete node " + params["macaddress"])
  491. return
  492. }
  493. json.NewEncoder(w).Encode(params["macaddress"] + " deleted.")
  494. }
  495. //A fun lil method for handling errors with http
  496. //Used in some cases but not others
  497. //1. This should probably be an application-wide function
  498. //2. All the API calls should probably be using this
  499. //3. The mongoconn should probably use this.
  500. //4. Need a consistent approach to error handling generally. Very haphazard at the moment
  501. //TODO: This is important. All Handlers should be replying with appropriate error code.
  502. func returnErrorResponse(response http.ResponseWriter, request *http.Request, errorMesage models.ErrorResponse) {
  503. httpResponse := &models.ErrorResponse{Code: errorMesage.Code, Message: errorMesage.Message}
  504. jsonResponse, err := json.Marshal(httpResponse)
  505. if err != nil {
  506. panic(err)
  507. }
  508. response.Header().Set("Content-Type", "application/json")
  509. response.WriteHeader(errorMesage.Code)
  510. response.Write(jsonResponse)
  511. }