Class: RodaPlugins::Kabk::RouteTree

Inherits:
Object
  • Object
show all
Defined in:
lib/roda/plugins/kabk/route_tree.rb

Overview

The HTTP glue layer isolating Roda logic from Kabk core logic

Constant Summary collapse

PUBLIC_DIR =
File.expand_path("../../../../public", __dir__)

Class Method Summary collapse

Class Method Details

.call(r, opts) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/roda/plugins/kabk/route_tree.rb', line 13

def self.call(r, opts)
  # Helper to respond with JSON safely
  respond_json = lambda do |response_hash, status_code = 200|
    r.response.status = status_code
    r.response["Content-Type"] = "application/json"
    response_hash.to_json
  end

  respond_error = lambda do |error|
    respond_json.call(error.to_h, error.http_status)
  end

  auth_strategy = opts[:auth_strategy]
  serve_ui = opts[:serve_ui] != false
  mount_at = opts[:mount_at] || "/api/admin"

  is_auth_route = r.path.include?("/auth/")
   = is_auth_route && (r.path.end_with?("/login") || r.path.end_with?("/refresh"))

  is_ui_request = serve_ui && (
    r.path == mount_at ||
    r.path == "#{mount_at}/" ||
    r.path == "#{mount_at}/index.html" ||
    r.path == "#{mount_at}/ui" ||
    r.path.include?("/assets/") ||
    r.path.end_with?("/simurgh-logo.svg")
  )

  user_context = nil
  # Middleware for Authentication check if auth strategy is present and route is not login/refresh or UI
  if auth_strategy && ! && !is_ui_request
    auth_header = r.env["HTTP_AUTHORIZATION"]
    begin
      raise ::Kabk::UnauthorizedError, "Missing Authorization Header" unless auth_header&.start_with?("Bearer ")
      token = auth_header.split(" ").last
      user_context = auth_strategy.verify_access_token!(token)
    rescue ::Kabk::ApiError => e
      return respond_error.call(e)
    end
  end

  if serve_ui
    serve_index_html = lambda do
      index_path = File.join(PUBLIC_DIR, "index.html")
      if File.file?(index_path)
        content = File.read(index_path)
        base_url = mount_at

        # Dynamically render registered Kabk schema
        sys_config = opts[:system_config] || {}
        
        # Strip trailing slash if present for clean concatenation, unless it's just '/'
        base = mount_at == "/" ? "" : mount_at
        
        sys_config[:endpoints] ||= {
          login: "#{base}/auth/login",
          me: "#{base}/auth/me",
          logout: "#{base}/auth/logout",
          refresh: "#{base}/auth/refresh",
          upload: "#{base}/uploads"
        }
        schema_renderer = ::Kabk::SchemaRenderer.new(system_config: sys_config)
        dynamic_schema = schema_renderer.render
        dynamic_schema_json = JSON.pretty_generate(dynamic_schema)

        # Replace embedded simurgh-schema script tag content
        content = content.sub(%r{<script id="simurgh-schema" type="application/json">.*?</script>}m, "<script id=\"simurgh-schema\" type=\"application/json\">\n#{dynamic_schema_json}\n    </script>")

        # Set baseURL in APP_CONFIG
        config_snippet = "window.APP_CONFIG = { baseURL: '#{base_url}' };"
        content = content.sub(/window\.APP_CONFIG\s*=\s*\{[^}]*\};/m, config_snippet)

        if mount_at != "" && mount_at != "/"
          content = content.gsub('href="/assets/', "href=\"#{mount_at}/assets/")
                           .gsub('src="/assets/', "src=\"#{mount_at}/assets/")
                           .gsub('href="/simurgh-logo.svg"', "href=\"#{mount_at}/simurgh-logo.svg\"")
                           .gsub('src="/simurgh-logo.svg"', "src=\"#{mount_at}/simurgh-logo.svg\"")
        end

        r.response["Content-Type"] = "text/html; charset=utf-8"
        content
      else
        respond_error.call(::Kabk::NotFoundError.new("Simurgh UI index.html not found"))
      end
    end

    r.get "assets", String do |asset_name|
      asset_path = File.join(PUBLIC_DIR, "assets", asset_name)
      if File.file?(asset_path)
        ext = File.extname(asset_name).downcase
        content_type = case ext
                       when ".js" then "application/javascript; charset=utf-8"
                       when ".css" then "text/css; charset=utf-8"
                       when ".svg" then "image/svg+xml"
                       when ".woff2" then "font/woff2"
                       when ".png" then "image/png"
                       else "application/octet-stream"
                       end
        r.response["Content-Type"] = content_type
        
        if ext == ".js"
          # Remove hardcoded "/api/admin/" from API calls in the JS bundle
          # because the Axios frontend will prepend the dynamic APP_CONFIG.baseURL anyway.
          content = File.read(asset_path)
          return content.gsub('"/api/admin/', '"/')
        end

        return File.read(asset_path)
      end
    end

    r.get "simurgh-logo.svg" do
      logo_path = File.join(PUBLIC_DIR, "simurgh-logo.svg")
      if File.file?(logo_path)
        r.response["Content-Type"] = "image/svg+xml"
        return File.read(logo_path)
      end
    end

    r.is do
      r.get do
        return serve_index_html.call
      end
    end

    r.is "index.html" do
      r.get do
        return serve_index_html.call
      end
    end

    r.is "ui" do
      r.get do
        return serve_index_html.call
      end
    end
  end

  r.on "auth" do
    r.post "login" do
      body = JSON.parse(r.body.read) rescue {}
      begin
         = opts[:login_handler]
        raise ::Kabk::ApiError.new("Login handler not configured", code: "NOT_SUPPORTED", http_status: 501) unless 

        response = auth_strategy.(body["username"], body["password"]) do |username, password|
          .call(username, password)
        end
        respond_json.call(response)
      rescue ::Kabk::ApiError => e
        respond_error.call(e)
      end
    end

    r.post "refresh" do
      body = JSON.parse(r.body.read) rescue {}
      begin
        response = auth_strategy.refresh(body["refresh_token"])
        respond_json.call(response)
      rescue ::Kabk::ApiError => e
        respond_error.call(e)
      end
    end

    r.get "me" do
      respond_json.call({
        success: true,
        data: user_context
      })
    end

    r.post "logout" do
      # Basic logout
      respond_json.call({ success: true, message: "Successfully logged out" })
    end

    r.post "change-password" do
      body = JSON.parse(r.body.read) rescue {}
      begin
        cp_handler = opts[:change_password_handler]
        raise ::Kabk::ApiError.new("Change password handler not configured", code: "NOT_SUPPORTED", http_status: 501) unless cp_handler
        
        cp_handler.call(user_context, body["old_password"], body["new_password"])
        respond_json.call({ success: true, message: "Password updated successfully" })
      rescue ::Kabk::ApiError => e
        respond_error.call(e)
      end
    end
  end

  r.post "uploads" do
    file_param = r.params["file"] || r.params
    upload_handler = opts[:upload_handler]

    if upload_handler.respond_to?(:call)
      result = upload_handler.call(file_param, r)
      respond_json.call(::Kabk::UploadHandler.format_response(
        url: result[:url] || result["url"],
        file_name: result[:file_name] || result["file_name"] || result[:filename] || result["filename"],
        size: result[:size] || result["size"],
        mime_type: result[:mime_type] || result["mime_type"]
      ))
    elsif file_param.is_a?(Hash) && file_param[:tempfile]
      respond_json.call(::Kabk::UploadHandler.format_response(
        url: "/uploads/#{file_param[:filename]}",
        file_name: file_param[:filename],
        size: file_param[:tempfile].size,
        mime_type: file_param[:type]
      ))
    else
      respond_error.call(::Kabk::ApiError.new("No file uploaded or file parameter missing", code: "BAD_REQUEST", http_status: 400))
    end
  end

  # Generic Resource Routes
  r.on String do |plural_name|
    # Match plural_name to a registered resource
    resource = ::Kabk::Registry.instance.all.find { |res| res.plural_name == plural_name }
    if resource.nil?
      return respond_error.call(::Kabk::NotFoundError.new("Endpoint not found"))
    end

    engine = ::Kabk::RestEngine.new(resource.name)

    r.is do
      # GET /:plural_name
      r.get do
        # We use request.params directly, it parses the query string nicely
        begin
          respond_json.call(engine.list(r.params))
        rescue ::Kabk::ApiError => e
          respond_error.call(e)
        end
      end

      # POST /:plural_name
      r.post do
        body = JSON.parse(r.body.read) rescue {}
        begin
          respond_json.call(engine.create(body))
        rescue ::Kabk::ApiError => e
          respond_error.call(e)
        end
      end
    end

    r.on "export" do
      r.get do
        begin
          format = r.params["format"] || "csv"
          # For streaming/buffering
          # Just call ExportHandler
          dataset = ::Kabk::QueryBuilder.build(resource, r.params)
          file_data = ::Kabk::ExportHandler.export(resource, dataset, format: format)
          
          r.response["Content-Disposition"] = "attachment; filename=\"#{plural_name}_export.#{format}\""
          r.response["Content-Type"] = format == "csv" ? "text/csv" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          file_data
        rescue ::Kabk::ApiError => e
          respond_error.call(e)
        end
      end
    end

    r.on String do |id|
      record_id = id.to_i

      r.is do
        # GET /:plural_name/:id
        r.get do
          begin
            respond_json.call(engine.get(record_id))
          rescue ::Kabk::ApiError => e
            respond_error.call(e)
          end
        end

        # PUT /:plural_name/:id
        r.put do
          body = JSON.parse(r.body.read) rescue {}
          begin
            respond_json.call(engine.update(record_id, body))
          rescue ::Kabk::ApiError => e
            respond_error.call(e)
          end
        end

        # DELETE /:plural_name/:id
        r.delete do
          begin
            respond_json.call(engine.delete(record_id))
          rescue ::Kabk::ApiError => e
            respond_error.call(e)
          end
        end
      end
    end
  end
end