我有两组组合路由,公共路线,不需要身份验证,以及需要身份验证的私人路由。
(defroutes public-routes
(GET "/" [] homepage-handler))
(defroutes private-routes
(GET "/secrets" [] secrets-handler))
我创建了一个中间件,该中间件是用户身份验证的,并继续中间软件链或升高。
(defn wrap-must-be-authenticated [handler]
(fn [request]
(if (authenticated? request)
(handler request)
(throw-unauthorized))))
(def app
(-> private-routes
(wrap-must-be-authenticated)))
这很好,所有"私人路线"都需要身份验证。
我将如何添加public-routes
,因此它们被排除在wrap-must-be-authenticated
?
我相信defroutes
返回戒指处理程序,所以我认为我需要做类似的事情:
(-> (wrap-must-be-authenticated private-routes)
public-routes)
做到这一点的一种方法是将多个routes
定义放在包含的routes
中,然后包装(wrap-routes
(中间件中的适当路由以限制访问:
(def all-routes
(routes
(-> #'private-routes
(wrap-routes wrap-must-be-authenticated))
#'public-routes
(route/not-found
(:body
(error-page {:status 404
:title "page not found"})))))
我正在使用Buddy.auth的restrict
的项目的另一个示例:
(defn wrap-admin [handler]
(restrict handler {:handler (fn [req]
(boolean (get-in req [:session :admin?])))}))
(def app-routes
(routes
(-> #'admin-routes
(wrap-routes wrap-admin)
(wrap-routes middleware/wrap-csrf)
(wrap-routes middleware/wrap-formats))
(-> #'home-routes
(wrap-routes middleware/wrap-csrf)
(wrap-routes middleware/wrap-formats))))