使用re-frame实现登录系统

5

我刚接触re-frame,不太确定如何使用它构建用户身份验证/授权系统。

根据我的了解,我应该创建一个auth 拦截器,并将我的auth逻辑放在:before部分中,然后将拦截器注入到我想要保护的每个事件的reg-event-dbreg-event-fx中。

我走对了吗?

1个回答

3

我不确定我的解决方案是否特别地符合惯用法,但在我的一个项目中,我使用了下面类似的方法。可以将其视为适用于我。

创建一个用于ajax请求的映射,并针对错误情况设置一个特殊值(忽略context-uri函数):

(defn xhrio-map [method path format success-event]
  {:method          method
   :uri             (context-uri path)
   :timeout         5000
   :response-format format
   :on-success      [success-event]
   :on-failure      [::ajax-failure]})

然后我使用一个fx处理程序来处理失败情况(这有点复杂,因为它还处理了一个加载指示器):

(rf/reg-event-fx
 ::ajax-failure
 (fn [{:keys [db]} [_ http-result]]
   (if (= 403 (:status http-result))
     {:db (assoc db :loading-indicator nil)
      :dispatch [::logout]}
     {:db (assoc db :loading-indicator nil)
      :dispatch
      [::error-msg (str "Error fetching from " (:uri http-result)
                        ": " (:response http-result))]})))

::logout事件会设置文档位置。这还会在后端触发注销。

(rf/reg-event-fx
 ::logout
 (fn [coefx [ev]]
   {::location "./logout"}))

最终,资源的加载方式如下所示:
 (defn load-with-indicator [db xhrio-data]
  {:db (assoc db :loading-indicator true)
   :http-xhrio xhrio-data})

(rf/reg-event-fx
 ::load-documentation
 (fn [{:keys [db]} _]
   (load-with-indicator
    db
    (xhrio-map :get "documentation/"
               (ajax/json-response-format {:keywords? true})
               ::received-documentation))))
:received-documentation由一些代码处理,该代码会调用正确的显示功能。
这使用了day8.re-frame/http-fx ajax.core 在后端,我使用类似于我在https://github.com/ska2342/ring-routes-demo发布的演示代码。
希望这有所帮助。
本文中的代码除了遵循StackOverflow网站的默认许可证外,我还将这些行发布到Eclipse Public License第1.0版或(按您的选择)任何更高版本下。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接