diff --git a/app/middlewares/cors.cr b/app/middlewares/cors.cr new file mode 100644 index 0000000..4aa84b2 --- /dev/null +++ b/app/middlewares/cors.cr @@ -0,0 +1,29 @@ +module App::Middlewares + class CORSHandler < Kemal::Handler + exclude ["/api/ping", "/:slug"] + + def initialize( + @allow_origin = "*", + @allow_methods = "GET, POST, PUT, DELETE, OPTIONS", + @allow_headers = "Content-Type, Accept, Origin, X-Api-Key" + ) + end + + def call(env) + return call_next(env) if exclude_match?(env) + + env.response.headers["Access-Control-Allow-Origin"] = @allow_origin + env.response.headers["Access-Control-Allow-Methods"] = @allow_methods + env.response.headers["Access-Control-Allow-Headers"] = @allow_headers + + if env.request.method == "OPTIONS" + env.response.status_code = 200 + env.response.content_type = "text/plain" + env.response.print("") + return env + end + + call_next(env) + end + end +end diff --git a/app/routes.cr b/app/routes.cr index 8544e95..a66ee11 100644 --- a/app/routes.cr +++ b/app/routes.cr @@ -2,36 +2,8 @@ require "./controllers/**" require "kemal" -class CORSHandler < Kemal::Handler - exclude ["/:slug"] - - def initialize( - @allow_origin = "*", - @allow_methods = "GET, POST, PUT, DELETE, OPTIONS", - @allow_headers = "Content-Type, Accept, Origin, X-Api-Key" - ) - end - - def call(context) - return call_next(context) if exclude_match?(context) - - context.response.headers["Access-Control-Allow-Origin"] = @allow_origin - context.response.headers["Access-Control-Allow-Methods"] = @allow_methods - context.response.headers["Access-Control-Allow-Headers"] = @allow_headers - - # If this is a preflight OPTIONS request, we return immediately with 200 - if context.request.method == "OPTIONS" - context.response.status_code = 200 - context.response.content_type = "text/plain" - context.response.print("") - return context - end - - call_next(context) - end -end - -add_handler CORSHandler.new +add_handler App::Middlewares::CORSHandler.new +add_handler App::Middlewares::Auth.new module App get "/:slug", &App::Controllers::ClickController.redirect_handler diff --git a/bit.cr b/bit.cr index d9d6655..a2cf06f 100644 --- a/bit.cr +++ b/bit.cr @@ -10,8 +10,6 @@ require "./app/services/*" require "./app/routes" add_context_storage_type(App::Models::User) -add_handler(App::Middlewares::Auth.new) - App::Services::Cli.setup_admin_user Kemal.run