Skip to content

Commit 6f52638

Browse files
coderhscoderhs
authored andcommitted
Add cors information to template
1 parent b0da7f3 commit 6f52638

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

template.rb

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,73 @@ class User < ApplicationRecord
102102
get "/secret", to: "confidential#secret", defaults: { format: :json }
103103
RUBY
104104

105+
gem "rack-cors"
106+
107+
remove_file "config/initializers/cors.rb"
108+
109+
CORS_FILE = <<~RUBY
110+
# Be sure to restart your server when you modify this file.
111+
112+
# Avoid CORS issues when API is called from the frontend app.
113+
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests.
114+
115+
# Read more: https://github.com/cyu/rack-cors
116+
117+
# Rails.application.config.middleware.insert_before 0, Rack::Cors do
118+
# allow do
119+
# origins "example.com"
120+
#
121+
# resource "*",
122+
# headers: :any,
123+
# methods: [:get, :post, :put, :patch, :delete, :options, :head]
124+
# end
125+
# end
126+
127+
if Rails.env.production?
128+
Rails.application.config.middleware.insert_before 0, Rack::Cors do
129+
allow do
130+
origins [ENV['FRONTEND_URL'], ENV['BACKEND_URL']]
131+
132+
resource '*',
133+
headers: :any,
134+
expose: ['Authorization'],
135+
methods: [:get, :post, :put, :patch, :delete, :options, :head],
136+
credentials: false
137+
end
138+
end
139+
else
140+
Rails.application.config.middleware.insert_before 0, Rack::Cors do
141+
allow do
142+
origins '*'
143+
144+
resource '*',
145+
headers: :any,
146+
expose: ['Authorization'],
147+
methods: [:get, :post, :put, :patch, :delete, :options, :head],
148+
credentials: false
149+
end
150+
end
151+
end
152+
RUBY
153+
154+
create_file "config/initializers/cors.rb", CORS_FILE
155+
156+
gsub_file "config/initializers/cors.rb", "devise_for :users", <<~RUBY
157+
devise_for :users,
158+
path: "",
159+
path_names: {
160+
sign_in: "login",
161+
sign_out: "logout",
162+
registration: "signup"
163+
},
164+
controllers: {
165+
sessions: "users/sessions",
166+
registrations: "users/registrations"
167+
}, defaults: { format: :json }
168+
169+
get "/secret", to: "confidential#secret", defaults: { format: :json }
170+
RUBY
171+
105172
after_bundle do
106173
master_key_path = "config/master.key"
107174

@@ -177,3 +244,4 @@ class User < ApplicationRecord
177244
end
178245
RUBY
179246
end
247+

0 commit comments

Comments
 (0)