DEV Community

Cover image for Clojure Is Awesome!!! [PART 4]
André Borba
André Borba

Posted on

1

Clojure Is Awesome!!! [PART 4]

(ns monostate)

(def ^:private session-state
  (atom {:user-id nil
         :permissions #{}
         :last-access nil}))

(defn start-session
  "Starts a new user session with ID and permissions."
  [user-id permissions]
  (reset! session-state {:user-id user-id
                         :permissions permissions
                         :last-access (java.time.Instant/now)}))

(defn end-session
  "Ends the session, resetting the state to default values."
  []
  (reset! session-state {:user-id nil
                         :permissions #{}
                         :last-access nil}))

(defn update-last-access
  "Updates the last access timestamp to the current time."
  []
  (swap! session-state assoc :last-access (java.time.Instant/now)))

(defn get-session
  "Retrieves the complete state of the current session."
  []
  @session-state)

(defn has-permission?
  "Checks if the user has a specific permission."
  [permission]
  (contains? (:permissions @session-state) permission))

(comment
  (start-session "user-123" #{"read" "write"})
  ;; => {:user-id "user-123", :permissions #{"read" "write"}, :last-access <timestamp>}

  (has-permission? "read") ;; => true
  (has-permission? "delete") ;; => false

  (update-last-access)

  (get-session)
  ;; => {:user-id "user-123", :permissions #{"read" "write"}, :last-access <new-timestamp>}

  (end-session)
  ;; => {:user-id nil, :permissions #{}, :last-access nil}
)
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay