From 3071d44e324d1eb0cb16a11758325e9069ff2f74 Mon Sep 17 00:00:00 2001 From: Alex Ling Date: Sun, 17 Jan 2021 08:10:43 +0000 Subject: [PATCH] Fix admin API bypassing --- src/handlers/auth_handler.cr | 7 ++++++- src/server.cr | 4 ---- src/util/web.cr | 34 +++++++++++++++++++++++----------- 3 files changed, 29 insertions(+), 16 deletions(-) diff --git a/src/handlers/auth_handler.cr b/src/handlers/auth_handler.cr index 53af8e8..0bdadfe 100644 --- a/src/handlers/auth_handler.cr +++ b/src/handlers/auth_handler.cr @@ -82,7 +82,12 @@ class AuthHandler < Kemal::Handler if env.session.string? "token" should_reject = !validate_token_admin(env) end - env.response.status_code = 403 if should_reject + if should_reject + env.response.status_code = 403 + message = "HTTP 403: You are not authorized to visit #{env.request.path}" + send_error_page + return + end end call_next env diff --git a/src/server.cr b/src/server.cr index 71973d4..9d9cefa 100644 --- a/src/server.cr +++ b/src/server.cr @@ -7,10 +7,6 @@ require "./routes/*" class Server def initialize - error 403 do |env| - message = "HTTP 403: You are not authorized to visit #{env.request.path}" - layout "message" - end error 404 do |env| message = "HTTP 404: Mango cannot find the page #{env.request.path}" layout "message" diff --git a/src/util/web.cr b/src/util/web.cr index ee4108e..fd7e873 100644 --- a/src/util/web.cr +++ b/src/util/web.cr @@ -1,19 +1,23 @@ # Web related helper functions/macros +macro check_admin_access + is_admin = false + # The token (if exists) takes precedence over the default user option. + # this is why we check the default username first before checking the + # token. + if Config.current.disable_login + is_admin = Storage.default. + username_is_admin Config.current.default_username + end + if token = env.session.string? "token" + is_admin = Storage.default.verify_admin token + end +end + macro layout(name) base_url = Config.current.base_url + check_admin_access begin - is_admin = false - # The token (if exists) takes precedence over the default user option. - # this is why we check the default username first before checking the - # token. - if Config.current.disable_login - is_admin = Storage.default. - username_is_admin Config.current.default_username - end - if token = env.session.string? "token" - is_admin = Storage.default.verify_admin token - end page = {{name}} render "src/views/#{{{name}}}.html.ecr", "src/views/layout.html.ecr" rescue e @@ -24,6 +28,14 @@ macro layout(name) end end +macro send_error_page + base_url = Config.current.base_url + check_admin_access + page = "Error" + html = render "src/views/message.html.ecr", "src/views/layout.html.ecr" + send_file env, html.to_slice, "text/html" +end + macro send_img(env, img) send_file {{env}}, {{img}}.data, {{img}}.mime end