1
mirror of https://gitlab.com/jessieh/simple-shortener.git synced 2025-04-12 16:41:46 +00:00
simple-shortener/src/handlers/ValidateAPIHandler.fnl

53 lines
2.0 KiB
Fennel

;; handlers/ValidateAPIHandler.fnl
;; Provides a ValidateAPIHandler that handles service logic for the /validate API endpoint
;; -------------------------------------------------------------------------- ;;
;; Dependencies
(local turbo (require :turbo))
;; -------------------------------------------------------------------------- ;;
;; Local modules
(local link_utils (require :modules.link_utils))
(local links_db (require :modules.links_db))
(local sessions_db (require :modules.sessions_db))
;; -------------------------------------------------------------------------- ;;
;; Handler definition
(local ValidateAPIHandler (class "ValidateHandler" turbo.web.RequestHandler))
(fn ValidateAPIHandler.prepare [self]
"Check that the client session is authorized before handling the request.
Responds with 401 Unauthorized and finished the request if the client session is not authorized."
(let [session_id (self:get_cookie "session_id")]
(when (not (and session_id
(sessions_db.is_session_active? session_id)))
(self:set_status 401)
(self:finish))))
;; ---------------------------------- ;;
;; GET
(fn ValidateAPIHandler.get [self data_type]
"Validate data (provided in GET body) against the standard for `data_type`.
Responds with 204 No Content if the data is valid for `data_type`.
Responds with 406 Not Acceptable if the data is not valid for `data_type`.
Responds with 400 Bad Request if `data_type` is not recognized."
(let [data (self:get_argument "data" nil true)]
(match data_type
"link_id" (if (and (link_utils.valid_link_id? data)
(links_db.link_id_available? data))
(self:set_status 204)
(self:set_status 406))
"link_dest" (if (link_utils.valid_link_dest? (link_utils.normalize_uri data))
(self:set_status 204)
(self:set_status 406))
_ (self:set_status 400))))
;; -------------------------------------------------------------------------- ;;
;; Return handler
ValidateAPIHandler