如何在 compojure web 项目中将用户保存在黑色会话中?

How to save a user in noir session in a compojure web project?

我必须在会话中保存用户名,但我似乎无法让它工作。这是我的代码(sesh 是黑色会话):

(defn set-loggedin [username password]
(do
(sesh/put! :username (:user username))
(sesh/put! :password (:pass password))))

(defn login-handler [username password]
(let [user (datab/login username password)]
(if (empty? user)
(view/login-form "Wrong username/password")
(do
(set-loggedin username password)
(response/redirect "/main")))))

(defroutes app-routes
(GET "/" [] (view/login-form "" ))
(POST "/" [username password] (login-handler username password))
(GET "/main" [] (view/main-page))
(route/resources "/")
(route/not-found "Not Found"))

(def app
(sesh/wrap-noir-session
(wrap-defaults  app-routes (assoc-in site-defaults [:security :anti-forgery] 
false))))

这是 hiccup 的主页,当我登录时它没有显示用户:

(defn main-page []
(html[:head [:title "main"]] [:body
                             (sesh/get :username)] ))

如有任何帮助,我们将不胜感激!

在您的 set-loggedin 函数中,您试图从 'username' 获取 :user 密钥,我怀疑它是一个字符串,而从 'password' 获取 :pass 密钥可能是一个字符串.

do 在函数定义中也是不必要的,所以试试这个:

(defn set-loggedin [username password]
  (sesh/put! :username username)
  (sesh/put! :password password)))