gpt4 book ai didi

clojure - 如何验证环应用中的路由子集?

转载 作者:行者123 更新时间:2023-12-04 01:58:35 25 4
gpt4 key购买 nike

我有两套compojure路由,公共(public)路由,不需要身份验证,私有(private)路由需要身份验证。

(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)))

这很好用,所有“私有(private)路由”都需要身份验证。

我将如何添加 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))))

关于clojure - 如何验证环应用中的路由子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com