/
payload.clj
68 lines (58 loc) · 1.9 KB
/
payload.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
(ns exoscale.compute.api.payload
"Functions to work with appropriate cloudstack payloads."
(:require [clojure.string :as str]
[exoscale.compute.api.hmac :as hmac]
[exoscale.compute.api.expiry :as expiry]))
(defn url-encode
"Encode URL"
[s]
(java.net.URLEncoder/encode s "UTF-8"))
(defn quote-plus
"Replace + in encoded URL by %20"
[s]
(str/replace (str s) "+" "%20"))
(defn serialize-pair
"Encode a key/value pair"
[[k v]]
(str (name k) "=" (url-encode v)))
(defn transform-maps
"For a list of maps, produce the expected key/value pairs."
[param maps]
(for [[[k v] i] (partition 2 (interleave maps (range)))]
[(format "%s[%d].%s" param i (name k) (str v))]))
(defn transform-arg
"Transform argument into a list of key/value pairs."
[[k v]]
(let [k (name k)
v (if (keyword? v) (name v) v)]
(when (or (and (sequential? v) (seq v)) (some? v))
(cond
(and (sequential? v) (-> v first map?))
(transform-maps (name k) v)
(sequential? v)
[[k (str/join "," (map name v))]]
:else
[[k (str v)]]))))
(defn query-args
"Build arguments, ready to be signed."
[params]
(->> (mapcat transform-arg params)
(sort-by first)
(map serialize-pair)
(str/join "&")))
(defn sign
"Sign the given query"
[query api-secret]
(hmac/sha1 api-secret (-> query str/lower-case quote-plus))
;; (-> query str/lower-case quote-plus)
)
(defn build-payload
"Build a signed payload for a given config, opcode and args triplet"
([config opcode params]
(build-payload config (assoc params :command opcode)))
([{:keys [api-key api-secret ttl]} params]
(let [payload (merge (expiry/args ttl)
(assoc params :apikey api-key :response "json"))]
(assoc payload :signature (sign (query-args payload) api-secret))
;;(sign (query-args payload) api-secret)
)))