               :message "Unauthorized owner access"}))))
 
 (defn- distribution-access
-  [{:keys [path-params] :as request}]
-  (let [user (get-in (:identity request) [:usr :username])
+  [{:keys [path-params identity]}]
+  (let [user (get-in identity [:usr :username])
         entity (cc/get-doc (:id path-params))]
     (if (or (= (:owner entity) user)
             (:public entity))
       true
       (error {:code    403
               :message "Unauthorized distribution access"}))))
+
+(defn- service-distribution-access
+  [{:keys [json-params identity]}]
+  (let [user (get-in identity [:usr :username])
+        distribution-id (get-in json-params ["distribution" "id"])]
+    (if (nil? distribution-id)
+      true
+      (let [entity (cc/get-doc distribution-id)]
+        (if (or (= (:owner entity) user)
+                (:public entity))
+          true
+          (error {:code    403
+                  :message "Unauthorized distribution access"}))))))
 
 (def rules [{:pattern #"^/admin/.*"
              :handler {:and [authenticated-access admin-access]}}

  true)

(defn- admin-access
  [request]
  (let [role (get-in (:identity request) [:usr :role])]
    (if (= "admin" role)
      true
      (error {:code    403
              :message "Unauthorized admin access"}))))

(defn- owner-access
  [{:keys [path-params] :as request}]
  (let [user (get-in (:identity request) [:usr :username])
        entity (cc/get-doc (:id path-params))]
    (if (= (:owner entity) user)
      true

             :request-method :get
             :handler        {:and [authenticated-access distribution-access]}}
            {:pattern        #"^/distribution/dockerhub/[a-zA-Z0-9]*$"
             :request-method #{:get :delete :post}
             :handler        {:and [authenticated-access owner-access]}}
            {:pattern        #"^/services$"
             :request-method :post
             :handler        {:and [authenticated-access service-distribution-access]}}
            {:pattern #"^/.*"
             :handler {:and [authenticated-access]}}])

