Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added support for JSON data in tracker-api.

  • Loading branch information...
commit bd471b45917f3cf03ad28794d2b1aa42ba88cc5b 1 parent dc7008f
@jsyrjala jsyrjala authored
View
4 src/ruuvi_server/api.clj
@@ -32,20 +32,16 @@
(GET [(str url-prefix "/trackers/:id") :id #"([0-9+],?)+"] [id]
(-> (fn [request] (client-api/fetch-tracker request id))
(wrap-request-logger "fetch-trackers")
- (wrap-json-params)
))
(GET (str url-prefix "/v1-dev/trackers") []
(-> #'client-api/fetch-trackers
(wrap-request-logger "fetch-trackers")
- (wrap-json-params)
))
(GET [(str url-prefix "/events/:id") :id #"([0-9+],?)+"] [id]
(-> (fn [request] (client-api/fetch-event request id))
(wrap-request-logger "fetch-trackers")
- (wrap-json-params)
))
(GET (str url-prefix "/events") []
(-> #'client-api/fetch-events
(wrap-request-logger "fetch-events")
- (wrap-json-params)
)))
View
46 src/ruuvi_server/tracker_api.clj
@@ -5,6 +5,9 @@
(:use [clojure.tools.logging :only (debug info warn error)])
(:import [java.security MessageDigest])
(:import [org.apache.commons.codec.binary Hex])
+ (:use ring.middleware.json-params)
+ (:use ring.middleware.keyword-params)
+ (:use ring.middleware.params)
)
(defn- map-api-event-to-internal [params]
@@ -20,7 +23,11 @@
})))
;; TODO handle authentication correctly
-(defn- create-event [request]
+(defn- create-event
+ "Checks if user is authenticated correctly and stores event to database.
+TODO auth check should not be a part of this method.
+"
+ [request]
(if (request :authenticated-tracker)
(try
(let [internal-event (map-api-event-to-internal (request :params))]
@@ -40,14 +47,14 @@
:body "not authorized"}
))
-(defn- compute-mac [params tracker]
+(defn- compute-mac [params tracker mac-field]
(let [secret (tracker :shared_secret)
- request-mac (params "mac")
+ request-mac (params :mac)
; sort keys alphabetically
sorted-keys (sort (keys params))
; remove :mac key
included-keys (filter (fn [param-key]
- (not= "mac" param-key))
+ (not= mac-field param-key))
sorted-keys)
; make included-keys a vector and convert to non-lazy list
param-keys (vec included-keys)]
@@ -64,7 +71,7 @@
computed-mac-hex
))))
-(defn- wrap-create-event-tracker
+(defn- wrap-find-tracker
"Find track with :tracker_code and set value to :tracker key"
[app]
(fn [request]
@@ -75,8 +82,8 @@
(app (merge request {:tracker tracker}))
(app request)))))
-(defn- wrap-create-event-auth
-"Marks authentication status to request:
+(defn- wrap-authentication-info
+ "Marks authentication status to request:
Sets keys
- :authenticated-tracker, if properly authenticated.
- :not-authenticated, if client chooses not to use autentication.
@@ -85,10 +92,10 @@ Sets keys
"
[app]
(fn [request]
- (let [params (request :form-params)
+ (let [params (request :params)
tracker (request :tracker)]
(cond
- (not (params "mac")) (do
+ (not (params :mac)) (do
(debug "Client does not use authentication")
(app (merge request {:not-authenticated true} )))
(not tracker) (do
@@ -96,8 +103,8 @@ Sets keys
(app (merge request {:unknown-tracker true})))
:else
- (let [computed-mac (compute-mac params (request :tracker))
- request-mac (params "mac")]
+ (let [computed-mac (compute-mac params (request :tracker) :mac)
+ request-mac (params :mac)]
(if (= computed-mac request-mac)
(do
(debug "Tracker is authenticated successfully")
@@ -107,9 +114,16 @@ Sets keys
(app (merge request {:authentication-failed true})))
))))))
+(defn handle-create-event [request]
+ ;; TODO modifications done to request at
+ ;; higher levels do not affect anything here
+ (->
+ #'create-event
+ (wrap-authentication-info)
+ (wrap-find-tracker)
+ (wrap-keyword-params)
+ (wrap-params)
+ (wrap-json-params)
+ ))
+
-(defn handle-create-event [req]
- (-> #'create-event
- (wrap-create-event-auth)
- (wrap-create-event-tracker)
- ))
View
52 test-utils/client.py
@@ -1,4 +1,5 @@
import httplib, urllib, hashlib
+import json
import time, sys, getopt
from urlparse import urlparse
@@ -6,20 +7,38 @@
def usage():
print """USAGE:
- python client.py URL sharedSecret trackerCode param1key param1value param2key param2value ...
+ python client.py dataformat URL sharedSecret trackerCode param1key param1value param2key param2value ...
+
+PARAMS:
+ - dataformat: either json or form
EXAMPLE:
- python client.py http://localhost:8080/api/v1/events VerySecret1 490154203237518 latitude 4916.46,N longitude 12311.12,W"""
-
-def makeQuery(url, content):
+ python client.py json http://localhost:8080/api/v1/events VerySecret1 490154203237518 latitude 4916.46,N longitude 12311.12,W"""
+
+def createJsonQuery(data):
+ return json.dumps(data)
+
+def createPostQuery(data):
+ return urllib.urlencode(data)
+
+def makeQuery(url, content, data_format):
headers = {
- 'Content-type': 'application/x-www-form-urlencoded',
'User-Agent': 'RuuviTracker test client/1.0',
}
connection = httplib.HTTPConnection(url.hostname, url.port)
- connection.request("POST", url.path, urllib.urlencode(content), headers)
+ if data_format == "json":
+ headers['Content-type'] = 'application/json'
+ dataToSend = createJsonQuery(content)
+ else:
+ headers['Content-type'] = 'application/x-www-form-urlencoded'
+ dataToSend = createPostQuery(content)
+ print("Data to send:");
+ print(headers)
+ print(dataToSend)
+ print(" ------- ")
+ connection.request("POST", url.path, dataToSend, headers)
response = connection.getresponse()
- print("%s %s" % (response.status, response.reason))
+ print("Response: %s %s" % (response.status, response.reason))
connection.close()
def computeMac(data, sharedSecret):
@@ -41,18 +60,23 @@ def createContent(data, sharedSecret, trackerCode):
return data
if __name__ == '__main__':
- if len(sys.argv) < 4:
+ if len(sys.argv) < 5:
+ usage()
+ sys.exit(1)
+
+ data_format = sys.argv[1]
+ if not data_format in ["json", "form"]:
usage()
sys.exit(1)
- url = urlparse(sys.argv[1])
- sharedSecret = sys.argv[2]
- trackerCode = sys.argv[3]
+ url = urlparse(sys.argv[2])
+ sharedSecret = sys.argv[3]
+ trackerCode = sys.argv[4]
- fields = sys.argv[4:]
+ fields = sys.argv[5:]
data = {}
for item in zip(fields, fields[1:])[::2]:
data[item[0]]=item[1]
- content = createContent(data,sharedSecret, trackerCode)
- makeQuery(url, content)
+ content = createContent(data, sharedSecret, trackerCode)
+ makeQuery(url, content, data_format)
Please sign in to comment.
Something went wrong with that request. Please try again.