Skip to content

Commit

Permalink
feat: add cors headers if allowed origin is defined (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
swiknaba authored Sep 23, 2024
1 parent 553626f commit fa9d842
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
2 changes: 2 additions & 0 deletions lib/kirei/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,7 @@ class Config < T::Struct
#
# Source: https://sorbet.org/docs/tstruct#from_hash-gotchas
prop :db_strict_type_resolving, T.nilable(T::Boolean), default: nil

prop :allowed_origins, T::Array[String], default: []
end
end
1 change: 0 additions & 1 deletion lib/kirei/model/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ def vector_column?(column_name)
col_info.fetch(:db_type).match?(/vector\(\d+\)/)
end

# New method to cast an array to a vector
sig { params(value: T.any(T::Array[Numeric], Sequel::SQL::Expression)).returns(Sequel::SQL::Expression) }
def cast_to_vector(value)
return value if value.is_a?(Sequel::SQL::Expression) || value.is_a?(Sequel::SQL::PlaceholderLiteralString)
Expand Down
15 changes: 14 additions & 1 deletion lib/kirei/routing/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ def call(env)
headers[header_name] ||= default_value
end

add_cors_headers(headers, env)

[
status,
headers,
Expand Down Expand Up @@ -143,7 +145,6 @@ def render(body, status: 200, headers: {})

sig { returns(T::Hash[String, String]) }
def default_headers
# "Access-Control-Allow-Origin": the user should set that, see comment about "cors" above
{
# security relevant headers
"X-Frame-Options" => "DENY",
Expand All @@ -159,6 +160,18 @@ def default_headers
}
end

sig { params(headers: T::Hash[String, String], env: RackEnvType).void }
def add_cors_headers(headers, env)
origin = T.cast(env.fetch("HTTP_ORIGIN"), String)
allowed_origins = Kirei::App.config.allowed_origins
return unless allowed_origins.include?(origin)

headers["Access-Control-Allow-Origin"] = origin
headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, Referer"
headers["Access-Control-Allow-Credentials"] = "true"
end

sig { params(hooks: NilableHooksType).void }
private def run_hooks(hooks)
return if hooks.nil? || hooks.empty?
Expand Down

0 comments on commit fa9d842

Please sign in to comment.