diff --git a/src/handlers/auth_handler.cr b/src/handlers/auth_handler.cr index 472e60d..26a149a 100644 --- a/src/handlers/auth_handler.cr +++ b/src/handlers/auth_handler.cr @@ -19,8 +19,14 @@ class AuthHandler < Kemal::Handler end def require_auth(env) - env.session.string "callback", env.request.path - redirect env, "/login" + if request_path_startswith env, ["/api"] + # Do not redirect API requests + env.response.status_code = 401 + send_text env, "Unauthorized" + else + env.session.string "callback", env.request.path + redirect env, "/login" + end end def validate_token(env) @@ -44,8 +50,9 @@ class AuthHandler < Kemal::Handler return true end if value.starts_with? BEARER - token = value.split(" ")[1] - return Storage.default.verify_token token + session_id = value.split(" ")[1] + token = Kemal::Session.get(session_id).try &.string? "token" + return !token.nil? && Storage.default.verify_token token end end end diff --git a/src/routes/api.cr b/src/routes/api.cr index a0f7cfb..5f33234 100644 --- a/src/routes/api.cr +++ b/src/routes/api.cr @@ -77,8 +77,8 @@ struct APIRouter env.session.string "token", token send_json env, { - "success" => true, - "token" => token, + "success" => true, + "session_id" => env.session.id, }.to_json rescue e Logger.error e diff --git a/src/server.cr b/src/server.cr index eb79374..b0a022d 100644 --- a/src/server.cr +++ b/src/server.cr @@ -24,9 +24,15 @@ class Server ReaderRouter.new APIRouter.new - options "/api/*" do |env| - cors - halt env + {% for path in %w(/api/* /uploads/* /img/*) %} + options {{path}} do |env| + cors + halt env + end + {% end %} + + static_headers do |response| + response.headers.add("Access-Control-Allow-Origin", "*") end Kemal.config.logging = false diff --git a/src/util/web.cr b/src/util/web.cr index 3662edb..4202177 100644 --- a/src/util/web.cr +++ b/src/util/web.cr @@ -43,10 +43,24 @@ macro send_img(env, img) send_file {{env}}, {{img}}.data, {{img}}.mime end +def get_token_from_auth_header(env) : String? + value = env.request.headers["Authorization"] + if value && value.starts_with? "Bearer" + session_id = value.split(" ")[1] + return Kemal::Session.get(session_id).try &.string? "token" + end +end + macro get_username(env) begin - token = env.session.string "token" - (Storage.default.verify_token token).not_nil! + # Check if we can get the session id from the cookie + token = env.session.string? "token" + if token.nil? + # If not, check if we can get the session id from the auth header + token = get_token_from_auth_header env + end + # If we still don't have a token, we handle it in `resuce` with `not_nil!` + (Storage.default.verify_token token.not_nil!).not_nil! rescue e if Config.current.disable_login Config.current.default_username