diff options
Diffstat (limited to 'src/pics/handler/upload.clj')
-rw-r--r-- | src/pics/handler/upload.clj | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/pics/handler/upload.clj b/src/pics/handler/upload.clj new file mode 100644 index 0000000..d3fa2cc --- /dev/null +++ b/src/pics/handler/upload.clj @@ -0,0 +1,37 @@ +(ns pics.handler.upload + (:require [clojure.string :as cstr] + [dotenv :as env] + [ring.util.response :as ruresp] + [clojure.java.io :as cjio])) + +(def ^:private name-chars "abcdefghijklmnopqrstuvwxyz") +(defn gen-random-name [] + (->> (map (fn [_] (rand-nth name-chars)) + (range 10)) + vec + (apply str))) + +(defn save-image [multipart-params name] + (cjio/copy (get-in multipart-params ["image" :tempfile]) + (cjio/file (str "./img/" name "." (-> multipart-params + (get-in ["image" :content-type]) + (cstr/split #"\/") + second))))) + +(defn authorized? [multipart-params] + (let [auth-keys-str (env/env "AUTH_KEYS") + auth-keys (delay (cstr/split auth-keys-str #","))] + (and (not (cstr/blank? auth-keys-str)) + (some #(= % (get multipart-params "auth-key")) @auth-keys)))) + +(defn handle [req] + (let [multipart-params (:multipart-params req) + name (gen-random-name)] + (if (authorized? multipart-params) + (do (save-image multipart-params name) + (ruresp/response (str "http://" (:server-name req) + (when (not= (:server-port req) 80) + (str ":" (:server-port req))) + "/" name))) + (-> (ruresp/response "Forbidden.") + (ruresp/status 403))))) |