LCOV - code coverage report
Current view: top level - matchscore/api - admin.clj Coverage Total Hit
Test: lcov.info Lines: 95.7 % 116 111
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.api.admin
       2              :   "Root-only HTTP handlers under `/api/admin/*`."
       3              :   (:require
       4              :    [cats.core :as c]
       5              :    [cats.monad.either :as either]
       6              :    [clojure.string :as str]
       7              :    [matchscore.access.resource :as access-resource]
       8              :    [matchscore.domain.event.query :as event-query]
       9              :    [matchscore.domain.permission.command :as perm-cmd]
      10              :    [matchscore.domain.permission.query :as perm-query]
      11              :    [matchscore.domain.template.query :as template-query]
      12              :    [matchscore.domain.user.command :as user-command]
      13              :    [matchscore.domain.user.repository.postgres :as user-repo]
      14              :    [ring.util.http-status :as status]
      15              :    [schemas.api.core :as api-schemas]
      16              :    [taoensso.carmine :as car]))
      17              : 
      18              : 
      19            4 : (defn- ok
      20              :   [data & [message]]
      21            4 :   {:status status/ok
      22            9 :    :body   {:message (or message "OK")
      23            1 :             :data    data}})
      24              : 
      25              : 
      26            4 : (defn- created
      27              :   [data & [message]]
      28            4 :   {:status status/created
      29            8 :    :body   {:message (or message "Created")
      30            1 :             :data    data}})
      31              : 
      32              : 
      33            7 : (defn- no-content [] {:status status/no-content})
      34              : 
      35              : 
      36            4 : (defn- bad-request
      37              :   [error]
      38            4 :   {:status status/bad-request
      39            6 :    :body   {:message (:message error)
      40            1 :             :error   error}})
      41              : 
      42              : 
      43            4 : (defn admin-roles-list-handler
      44              :  {:authz       {:obj     :admin
      45              :                 :act     :manage
      46              :                 :create? true}
      47              :   :summary     "List all roles in the catalog"
      48              :   :description "Returns the role lookup table used by the admin UI dropdowns."}
      49              :  [{:keys [ctx]
      50              :    :as   _request}]
      51            7 :  (ok (vec (perm-query/list-roles ctx))))
      52              : 
      53              : 
      54            4 : (defn admin-roles-create-handler
      55              :  {:malli/schema [:=>
      56              :                  [:cat api-schemas/RingRequest api-schemas/RoleCreateSchema]
      57              :                  api-schemas/RoleResponseSchema]
      58              :   :authz        {:obj     :admin
      59              :                  :act     :manage
      60              :                  :create? true}
      61              :   :summary      "Create a role in the catalog"
      62              :   :description  "Inserts a new entry into the `roles` lookup table."}
      63              :  [{:keys [ctx]
      64              :    :as   _request}
      65              :   role]
      66            5 :  (let [result (perm-cmd/create-role! ctx role)]
      67            4 :    (if (either/right? result)
      68           12 :      (created (c/extract result) (str "Role " (:name role) " created."))
      69            0 :      (bad-request (c/extract result)))))
      70              : 
      71              : 
      72            4 : (defn admin-roles-update-handler
      73              :  {:malli/schema     [:=>
      74              :                      [:cat api-schemas/RingRequest api-schemas/RoleUpdateSchema]
      75              :                      api-schemas/RoleResponseSchema]
      76              :   :malli/parameters {:path api-schemas/RolePathParamsSchema}
      77              :   :authz            {:obj     :admin
      78              :                      :act     :manage
      79              :                      :create? true}
      80              :   :summary          "Update a role in the catalog"
      81              :   :description      "Updates display name / description / scope of a role."}
      82              :  [{:keys [ctx route-params]
      83              :    :as   _request}
      84              :   updates]
      85            4 :  (let [role-name (:role-name route-params)
      86            4 :        existing  (perm-query/find-role ctx role-name)]
      87            5 :    (if (nil? existing)
      88            4 :      {:status status/not-found
      89            6 :       :body   {:message (str "Role not found: " role-name)}}
      90            8 :      (let [merged (merge existing updates {:name role-name})
      91            4 :            result (perm-cmd/update-role! ctx merged)]
      92            4 :        (if (either/right? result)
      93           10 :          (ok (c/extract result) (str "Role " role-name " updated."))
      94            0 :          (bad-request (c/extract result)))))))
      95              : 
      96              : 
      97            4 : (defn admin-roles-delete-handler
      98              :  {:malli/parameters {:path api-schemas/RolePathParamsSchema}
      99              :   :authz            {:obj     :admin
     100              :                      :act     :manage
     101              :                      :create? true}
     102              :   :summary          "Delete a role from the catalog"
     103              :   :description      "Removes a role from the lookup table."}
     104              :  [{:keys [ctx route-params]
     105              :    :as   _request}]
     106            7 :  (let [result (perm-cmd/delete-role! ctx (:role-name route-params))]
     107            6 :    (if (either/right? result) (no-content) (bad-request (c/extract result)))))
     108              : 
     109              : 
     110            4 : (defn admin-users-list-handler
     111              :  {:authz       {:obj     :admin
     112              :                 :act     :manage
     113              :                 :create? true}
     114              :   :summary     "List users with global roles"
     115              :   :description "Returns all users with their users.roles values."}
     116              :  [{:keys [ctx]
     117              :    :as   _request}]
     118           10 :  (ok (user-repo/get-all (get-in ctx [:repos :user-postgres-repo]))))
     119              : 
     120              : 
     121            4 : (defn admin-user-handler
     122              :  {:malli/parameters {:path api-schemas/UserListPathParamsSchema}
     123              :   :authz   {:obj     :admin
     124              :             :act     :manage
     125              :             :create? true}
     126              :   :summary "Get one user with global roles"}
     127              :  [{:keys [ctx route-params]
     128              :    :as   _request}]
     129            4 :  (let [user-uuid (:user-uuid route-params)
     130            9 :        user      (user-repo/find-by-id (get-in ctx [:repos :user-postgres-repo]) user-uuid)]
     131            5 :    (if (nil? user)
     132            4 :      {:status status/not-found
     133            3 :       :body   {:message "User not found"}}
     134            0 :      (ok user))))
     135              : 
     136              : 
     137            4 : (defn admin-user-update-handler
     138              :  {:malli/schema     [:=>
     139              :                      [:cat api-schemas/RingRequest api-schemas/AdminUserUpdateSchema]
     140              :                      api-schemas/AdminUserResponseSchema]
     141              :   :malli/parameters {:path api-schemas/UserListPathParamsSchema}
     142              :   :authz            {:obj     :admin
     143              :                      :act     :manage
     144              :                      :create? true}
     145              :   :summary          "Update a user's profile (name, username)"
     146              :   :description      "Updates a user's display name and/or username. Root only."}
     147              :  [{:keys [ctx route-params]
     148              :    :as   _request}
     149              :   {:keys [name]
     150              :    :as   body}]
     151            7 :  (let [repo      (get-in ctx [:repos :user-postgres-repo])
     152            3 :        user-uuid (:user-uuid route-params)
     153            4 :        existing  (user-repo/find-by-id repo user-uuid)]
     154            5 :    (if (nil? existing)
     155            4 :      {:status status/not-found
     156            3 :       :body   {:message "User not found"}}
     157              :      ;; Reuse the shared update-user! command (username uniqueness, change
     158              :      ;; detection, cache invalidation). telegram-id/photo-url come from the
     159              :      ;; existing record so change detection stays accurate. Only touch username
     160              :      ;; when the field is present in the payload, so an explicit null clears it
     161              :      ;; while an omitted field leaves it untouched.
     162           10 :      (let [account-data (cond->
     163            6 :                           {:uuid        user-uuid
     164            3 :                            :telegram-id (:telegram-id existing)
     165            3 :                            :photo-url   (:photo-url existing)
     166            1 :                            :name        name}
     167           10 :                           (contains? body :username)       (assoc :username (:username body))
     168            5 :                           (contains? body :name-localized) (assoc :name-localized
     169            3 :                                                             (:name-localized body)))
     170              :            ;; Admins may edit names the user has locked.
     171            7 :            result       (user-command/update-user! ctx account-data {:enforce-name-locks? false})]
     172            4 :        (if (either/right? result)
     173            8 :          (ok (:data (c/extract result)) "User updated.")
     174            5 :          (bad-request (c/extract result)))))))
     175              : 
     176              : 
     177            4 : (defn admin-user-name-locks-update-handler
     178              :  {:malli/schema [:=>
     179              :                  [:cat api-schemas/RingRequest api-schemas/UserNameLocksUpdateSchema]
     180              :                  api-schemas/AdminUserResponseSchema]
     181              :   :malli/parameters {:path api-schemas/UserListPathParamsSchema}
     182              :   :authz {:obj     :admin
     183              :           :act     :manage
     184              :           :create? true}
     185              :   :summary "Set which of a user's names are locked"
     186              :   :description
     187              :   "Replaces the languages (\"en\" = Latin name, \"uk\", ...) whose name the user can no longer change from their profile. Admins can still edit them. Root only."}
     188              :  [{:keys [ctx route-params]
     189              :    :as   _request}
     190              :   {:keys [languages]}]
     191            7 :  (let [repo      (get-in ctx [:repos :user-postgres-repo])
     192            3 :        user-uuid (:user-uuid route-params)]
     193            8 :    (if (nil? (user-repo/find-by-id repo user-uuid))
     194            4 :      {:status status/not-found
     195            3 :       :body   {:message "User not found"}}
     196            6 :      (let [result (user-command/set-name-locks! ctx user-uuid languages)]
     197            4 :        (if (either/right? result)
     198            6 :          (ok (c/extract result) "Name locks updated.")
     199            5 :          (bad-request (c/extract result)))))))
     200              : 
     201              : 
     202            4 : (defn admin-user-roles-update-handler
     203              :  {:malli/schema     [:=>
     204              :                      [:cat api-schemas/RingRequest api-schemas/UserRolesUpdateSchema]
     205              :                      api-schemas/AdminUserResponseSchema]
     206              :   :malli/parameters {:path api-schemas/UserListPathParamsSchema}
     207              :   :authz            {:obj     :admin
     208              :                      :act     :manage
     209              :                      :create? true}
     210              :   :summary          "Update a user's global roles"}
     211              :  [{:keys [ctx route-params]
     212              :    :as   _request}
     213              :   {:keys [roles]}]
     214            7 :  (let [repo      (get-in ctx [:repos :user-postgres-repo])
     215            3 :        user-uuid (:user-uuid route-params)
     216            4 :        existing  (user-repo/find-by-id repo user-uuid)
     217            3 :        roles     (access-resource/normalize-roles roles)]
     218            7 :    (cond (nil? existing)
     219            4 :          {:status status/not-found
     220            3 :           :body   {:message "User not found"}}
     221              : 
     222            8 :          (empty? roles) (bad-request {:message "At least one valid role is required."})
     223              : 
     224              :          :else
     225            6 :          (let [result (user-repo/update-roles-preserving-last-root! repo user-uuid roles)]
     226            4 :            (if (either/right? result)
     227            6 :              (ok (c/extract result) "User roles updated.")
     228            0 :              (bad-request (c/extract result)))))))
     229              : 
     230              : 
     231            4 : (defn admin-policies-list-handler
     232              :  {:authz   {:obj     :admin
     233              :             :act     :manage
     234              :             :create? true}
     235              :   :summary "List all Casbin policies"}
     236              :  [{:keys [ctx]
     237              :    :as   _request}]
     238            5 :  (ok (perm-query/list-policies ctx)))
     239              : 
     240              : 
     241            4 : (defn admin-policies-create-handler
     242              :  {:malli/schema [:=>
     243              :                  [:cat api-schemas/RingRequest api-schemas/PolicyMutateSchema]
     244              :                  api-schemas/PolicyMutateResponseSchema]
     245              :   :authz        {:obj     :admin
     246              :                  :act     :manage
     247              :                  :create? true}
     248              :   :summary      "Add a Casbin policy row"}
     249              :  [{:keys [ctx]
     250              :    :as   _request}
     251              :   policy]
     252            5 :  (let [result (perm-cmd/add-permission! ctx policy)]
     253            8 :    (if (either/right? result) (created policy "Policy added.") (bad-request (c/extract result)))))
     254              : 
     255              : 
     256            4 : (defn admin-policies-delete-handler
     257              :  {:malli/schema [:=>
     258              :                  [:cat api-schemas/RingRequest api-schemas/PolicyMutateSchema]
     259              :                  api-schemas/PolicyDeleteResponseSchema]
     260              :   :authz        {:obj     :admin
     261              :                  :act     :manage
     262              :                  :create? true}
     263              :   :summary      "Remove a Casbin policy row"}
     264              :  [{:keys [ctx]
     265              :    :as   _request}
     266              :   policy]
     267            5 :  (let [result (perm-cmd/remove-permission! ctx policy)]
     268            6 :    (if (either/right? result) (no-content) (bad-request (c/extract result)))))
     269              : 
     270              : 
     271              : ;; ---------------------------------------------------------------------------
     272              : ;; Events / Templates (read-only "see everything" listings)
     273              : ;; ---------------------------------------------------------------------------
     274              : 
     275              : 
     276            4 : (def ^:private list-all-pagination
     277              :   "Pagination that effectively disables paging so the admin sees every row."
     278           12 :   {:limit 100000})
     279              : 
     280              : 
     281            4 : (defn admin-events-list-handler
     282              :  {:malli/schema [:=> [:cat api-schemas/RingRequest] api-schemas/AdminEventListResponseSchema]
     283              :   :authz        {:obj     :admin
     284              :                  :act     :manage
     285              :                  :create? true}
     286              :   :summary      "List all events"
     287              :   :description  "Returns every event (all columns plus associated clubs), newest first. Root only."}
     288              :  [{:keys [ctx]
     289              :    :as   _request}]
     290            7 :  (let [repo   (get-in ctx [:repos :event-postgres-repo])
     291            5 :        result (event-query/search-events repo {} list-all-pagination)]
     292            7 :    (ok (:items (c/extract result)))))
     293              : 
     294              : 
     295            4 : (defn admin-templates-list-handler
     296              :  {:malli/schema [:=> [:cat api-schemas/RingRequest] api-schemas/AdminTemplateListResponseSchema]
     297              :   :authz {:obj     :admin
     298              :           :act     :manage
     299              :           :create? true}
     300              :   :summary "List all event templates"
     301              :   :description
     302              :   "Returns every event template (all columns plus associated clubs), newest first. Root only."}
     303              :  [{:keys [ctx]
     304              :    :as   _request}]
     305            7 :  (let [repo   (get-in ctx [:repos :template-postgres-repo])
     306            5 :        result (template-query/search-templates repo {} list-all-pagination)]
     307            7 :    (ok (:items (c/extract result)))))
     308              : 
     309              : 
     310            4 : (defn- delete-non-session-keys!
     311              :   "Scans the current Redis database and deletes every key except sessions
     312              :   (`session:*`), so active logins survive a cache clear. Returns the number of
     313              :   keys deleted."
     314              :   [redis]
     315            3 :   (loop [cursor  "0"
     316              :          deleted 0]
     317           42 :     (let [[next-cursor keys] (car/wcar redis (car/scan cursor "COUNT" 1000))
     318            8 :           to-delete (remove #(str/starts-with? % "session:") keys)
     319            4 :           deleted   (if (seq to-delete)
     320           42 :                       (+ deleted (car/wcar redis (apply car/del to-delete)))
     321            0 :                       deleted)]
     322            5 :       (if (= next-cursor "0") deleted (recur next-cursor deleted)))))
     323              : 
     324              : 
     325            4 : (defn admin-cache-clear-handler
     326              :  {:authz {:obj     :admin
     327              :           :act     :manage
     328              :           :create? true}
     329              :   :summary "Clear all Redis cache"
     330              :   :description
     331              :   "Flushes all keys except active sessions (`session:*`) from the current Redis database. Root only."}
     332              :  [{:keys [redis]
     333              :    :as   _request}]
     334            3 :  (delete-non-session-keys! redis)
     335            4 :  {:status status/ok
     336            3 :   :body   {:message "Cache cleared."}})
        

Generated by: LCOV version 2.0-1