Skip to content

Commit

Permalink
all the refactorings
Browse files Browse the repository at this point in the history
  • Loading branch information
synthomat committed Sep 25, 2024
1 parent bdba8f0 commit 116d104
Show file tree
Hide file tree
Showing 8 changed files with 135 additions and 80 deletions.
2 changes: 1 addition & 1 deletion deps.edn
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
clojure.java-time/clojure.java-time {:mvn/version "1.4.2"}

clj-http/clj-http {:mvn/version "3.13.0"} ; HTTP Client
;org.clj-commons/hickory {:mvn/version "0.7.3"} ; HTML parser
org.clj-commons/hickory {:mvn/version "0.7.4"} ; HTML parser
}


Expand Down
2 changes: 1 addition & 1 deletion resources/config.defaults.edn
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{:database {:url #or [#env DATABASE_URL "jdbc:postgresql://localhost:5432/myuri"]}
:server {:port #or [#env PORT 3000]
:cookie-secret #or [#env COOKIE_SECRET "agtjrfokft5rs9ksadjfla5g__"]}}
:cookie-secret #or [#env COOKIE_SECRET "agtjrfokft5rs9ad"]}}
1 change: 0 additions & 1 deletion resources/templates/settings/index.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{% extends "settings/_layout.html" %}

{% block content %}

<form method="post">
<input type="hidden" name="__anti-forgery-token" value="{{ req.anti-forgery-token }}"/>
<div class="field">
Expand Down
59 changes: 39 additions & 20 deletions src/myuri/db.clj
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,19 @@
(defn bookmarks
"docstring"
[ds user-id & {:keys [q]}]
(let [base-pred [:and [:= :user_id user-id]]
query (when (not-empty q)
[:or
[:ilike :site_title (str "%" q "%")]
[:ilike :site_url (str "%" q "%")]
[:ilike :site_description (str "%" q "%")]])
pred (conj base-pred query)]
(sql/query ds (hsql/format {:select [:*]
:from :bookmarks
:where pred
:order-by [[:created_at :desc]]}))))
(let [search-query (when (not-empty q)
[:or
[:ilike :site_title (str "%" q "%")]
[:ilike :site_url (str "%" q "%")]
[:ilike :site_description (str "%" q "%")]])
stmt (hsql/format
{:select :*
:from :bookmarks
:where [:and
[:= :user_id user-id]
search-query]
:order-by [[:created_at :desc]]})]
(sql/query ds stmt)))

(defn store!
"docstring"
Expand Down Expand Up @@ -118,26 +120,43 @@
([ds user-id]
(user-settings ds user-id nil))
([ds user-id setting-names]
(let [stmt (-> (apply hh/select
(or setting-names :*))
(hh/from :user_settings)
(hh/where [:= :user_id user-id])
hsql/format)]
(let [stmt (hsql/format
{:select (or setting-names :*)
:from :user_settings
:where [:= :user_id user-id]})]
(-> (sql/query ds stmt)
first))))

(defn set-user-settings!
"docstring"
[ds user-id settings]
(let [statement (-> (hh/update :user_settings)
(hh/set settings)
(hh/where [:= :user_id user-id])
hsql/format)]
(let [statement (hsql/format
{:update :user_settings
:set settings
:where [:= :user_id user-id]})]
(jdbc/execute! ds statement)))

(defn update-user! [ds user-id user-data]
(sql/update! ds :users user-data ["id = ?" user-id]))

(defn read-system-prop
"docstring"
[ds key]
(-> (sql/get-by-id ds :system_configs key :key nil)
:system_configs/value))

(defn write-system-prop
"docstring"
[ds key value]
(->> {:insert-into :system_configs
:values [{:key key, :value [:lift (->pgobject value)]}]
:on-conflict :key
:do-update-set :value
:returning [:*]}
hsql/format
(jdbc/execute! ds)))


;; Database Management --------------------------------------------------------

(defn migratus-config
Expand Down
3 changes: 2 additions & 1 deletion src/myuri/web/handler.clj
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
(assoc m k (get form k v)))
{}
allowed-settings)]
(prn safe-settings)
(db/set-user-settings! ds user-id safe-settings)
(resp/redirect "/settings")))))

Expand All @@ -131,7 +132,7 @@
(do
(prn resp)
(assoc (resp/redirect "/settings/security")
:flash {:class "is-success"
:flash {:class "is-success"
:message "Password changed successfully"}))
(tpl-resp "settings/security.html" {:errors "Wrong password"}))
:default (tpl-resp "settings/security.html")))))
Expand Down
44 changes: 22 additions & 22 deletions src/myuri/web/middleware.clj
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
(ns myuri.web.middleware
(:require [buddy.auth :refer [authenticated?]]
[buddy.auth.accessrules :as baa]
[buddy.auth.backends]
[buddy.auth.backends :as bab]
[buddy.auth.backends :as auth-backends]
[buddy.auth.middleware :as bam]
[myuri.web.auth.handler :refer [unauthorized-handler]]
[ring.middleware.session :as rms]
[ring.middleware.session.cookie :as cookie]
[myuri.web.templating :as tmpl]))

(def cookie-backend (bab/session {:unauthorized-handler unauthorized-handler}))

(defn any-role?
"docstring"
Expand All @@ -29,7 +27,7 @@
[req]
(if (authenticated? req)
(baa/success)
(baa/error {:code 401
(baa/error {:code 401
:message "You are not authenticated. Please log in."})))

(defn admin-access
Expand All @@ -38,25 +36,36 @@

(if (contains? (:roles identity) :admin)
(baa/success)
(baa/error {:code 403
:message "Unauthorized admin access"})))
;(tmpl/tpl-resp "errors/403-forbidden.html")
(baa/error (fn [req] (tmpl/tpl-resp "errors/403-forbidden.html")))
#_{:code 403
:message "Unauthorized admin access"}))

(def rules [{:pattern #"^/auth"
(def rules [{:uri "/auth"
:handler any-access}
{:pattern #"^/admin"
{:uri "/admin"
:handler admin-access}
{:pattern #"^/.*"
{:uri "/"
:handler authenticated-access}])

(defn wrap-authorization
(defn wrap-session
"docstring"
[handler]
(bam/wrap-authorization handler cookie-backend))
[handler key]
(let [store (cookie/cookie-store {:key (.getBytes key)})]
(rms/wrap-session handler {:store store})))

(def auth-backend (auth-backends/session
{:unauthorized-handler unauthorized-handler}))

(defn wrap-authentication
"docstring"
[handler]
(bam/wrap-authentication handler cookie-backend))
(bam/wrap-authentication handler auth-backend))

(defn wrap-authorization
"docstring"
[handler]
(bam/wrap-authorization handler auth-backend))

(defn wrap-access-rules
"docstring"
Expand All @@ -71,15 +80,6 @@
(assoc :ds (:ds opts))
(handler))))

(defn cookie-store
[key]
(let [byte-key (byte-array (map byte key))]
(cookie/cookie-store {:key byte-key})))

(defn wrap-session
"docstring"
[handler key]
(rms/wrap-session handler {:store (cookie-store key)}))

(defn wrap-templating
"docstring"
Expand Down
103 changes: 70 additions & 33 deletions src/myuri/web/routes.clj
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
[reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.parameters :as parameters]
[ring.middleware.keyword-params :as kpmw]
[reitit.coercion.malli]
[ring.middleware.anti-forgery :refer [wrap-anti-forgery]]
[ring.util.response :as resp]
[ring.middleware.flash :refer [wrap-flash]]
[selmer.parser :refer [render-file]]
[myuri.web.specs :as specs]))
[myuri.web.specs :as specs]
[reitit.ring.middleware.dev :as dev]
[reitit.coercion.malli :as rc]))

;; Utils ----------------------------------------------------------------------

Expand All @@ -39,7 +40,6 @@


(defn make-routes []

[["/"
{:get {:parameters {:query specs/GetBookmarksRequest}
:handler bh/index-handler}}]
Expand Down Expand Up @@ -88,47 +88,84 @@
:post {:parameters {:form [:map
[:target_blank {:optional true} boolean?]]}
:handler bh/settings-index}}]
["/security"
{:name "settings:security"
:get {:handler bh/security-handler}
:post {:handler bh/security-handler
:parameters {:form {:current_password string?
:new_password string?
:new_password2 string?}}}}]]]
)
["/security" {:name "settings:security"
:get {:handler bh/security-handler}
:post {:handler bh/security-handler
:parameters {:form {:current_password string?
:new_password string?
:new_password2 string?}}}}]]])

(def exception-middleware
(exception/create-exception-middleware
(merge exception/default-handlers
{})))

(defn default-routes
"docstring"
[]
(ring/routes
(ring/create-resource-handler {:path "/assets"})
(ring/create-default-handler {:not-found not-found-handler})))

(defn dummy
"docstring"
[handler ident]
(fn [req]
(prn (str "before " ident " <- " req))
(let [res (handler req)]
(prn (str "after " ident " -> " res))
res)))
(comment
(def app
(wrap-cors
(wrap-json-parsing
(wrap-authentication
(wrap-logging
(wrap-error-handling
(reitit.ring/ring-handler router)))))))
)


(defn ring-middlewares
"docstring"
[opts]
[[mw/wrap-system opts]

[mw/wrap-session (:cookie-secret opts)]

mw/wrap-authentication

mw/wrap-authorization
mw/wrap-access-rules
wrap-flash])

(defn reitit-middlewares
"docstring"
[]
[parameters/parameters-middleware
kpmw/wrap-keyword-params
muuntaja/format-middleware
wrap-anti-forgery

mw/wrap-templating

exception-middleware

rrc/coerce-request-middleware])


(defn app
[opts]
(ring/ring-handler
(ring/router
(make-routes)

;; router data affecting all routes
{:data {:coercion reitit.coercion.malli/coercion
{;:reitit.middleware/transform dev/print-request-diffs
:data {:coercion rc/coercion
:muuntaja mj/instance
:middleware [parameters/parameters-middleware
kpmw/wrap-keyword-params
exception-middleware
rrc/coerce-request-middleware
rrc/coerce-response-middleware
muuntaja/format-response-middleware
wrap-anti-forgery
mw/wrap-templating
mw/wrap-access-rules
]}})

(ring/routes
(ring/create-resource-handler {:path "/assets"})
(ring/create-default-handler {:not-found not-found-handler}))

{:middleware [[mw/wrap-session (:cookie-secret opts)]
wrap-flash

mw/wrap-authentication
mw/wrap-authorization
[mw/wrap-system opts]]}))
:middleware (reitit-middlewares)}})

(default-routes)

{:middleware (ring-middlewares opts)}))
1 change: 0 additions & 1 deletion src/myuri/web/server.clj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
(selmer.parser/cache-off!)

(let [{:keys [cookie-secret port dev?]} options

create-handler (fn []
(routes/app {:ds (:ds db)
:cookie-secret cookie-secret}))
Expand Down

0 comments on commit 116d104

Please sign in to comment.