1

I've just saved the current logged-in user in session. Now how do I get user's id from session in Selmer templates?. Thanks

 (defn login-form [{:keys [flash]}]
  (layout/render
   "login_form.html"
   (merge (select-keys flash [:id :pass :errors]))))

(defn authenticate [id pass]
  (when-let [user (db/get-user {:id id})]
    (when (hashers/check pass (:pass user))
      id)))

(defn login! [{:keys [params]}]
  (if-let [id (authenticate (:id params) (:pass params))] ;TODO: Refactor
    (do
    >>>>>>>>>  (update (response/found "/") :session {:id id}))
    (layout/render "login_form.html" {:invalid-credentials? true})))

(defroutes auth-routes
  (GET "/accounts/login/" request (login-form request))
  (POST "/accounts/login/" request (login! request)))

Update

I've updated my login function. and it works.

 (defn login! [{:keys [params session]}]
  (if-let [id (authenticate (:id params) (:pass params))] ;TODO: Refactor
    (-> (response/found "/")
      (assoc :session
        (assoc session :id id)))
    (layout/render "login_form.html" {:invalid-credentials? true})))

To print the user's id, I've changed the home-routes.

 (defn home-page [opts]
  (layout/render "home.html" opts))

(defroutes home-routes
  (GET "/" {:keys [flash session]} (home-page (or flash session))))

Now I can print user's id in home.html template. But If I use any other url then user's id stopped `displaying``.

Question > So do I need to pass {:keys [flash session]} in every routes?

no_freedom
  • 1,963
  • 10
  • 30
  • 48

1 Answers1

1

You can make use of the wrap-identity middleware which Luminus provides by making sure it's in your wrap-base stack, then change :id to :identity in your session. You can now call (layout/render "home.html") (even without providing opts!) and you can access the identity using {{identity}}

Alan Tran
  • 58
  • 6