-
-
Save dsci/1433856 to your computer and use it in GitHub Desktop.
Sinatra + Warden & Rails + Devise Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /config.ru | |
# This file is used by Rack-based servers to start the application. | |
# File generated by "rails create MyApp" | |
# For Rails | |
require ::File.expand_path('../config/environment', __FILE__) | |
# For Sinatra | |
require './slim/slim.rb' | |
# - Make sinatra play nice | |
use Rack::MethodOverride | |
disable :run, :reload | |
# Mapping | |
# ------- | |
# Rest with Rails | |
map "/" do | |
run MyApp::Application | |
end | |
# Anything urls starting with /slim will go to Sinatra | |
map "/slim" do | |
# make sure :key and :secret be in-sync with initializers/secret_store.rb initializers/secret_token.rb | |
use Rack::Session::Cookie, :key => '<< see, initializers/secret_store.rb >>', :secret => '<< copy from initializers/secret_token.rb >>' | |
# Point Warden to the Sinatra App | |
use Warden::Manager do |manager| | |
manager.failure_app = AppMain | |
manager.default_scope = Devise.default_scope | |
end | |
# Borrowed from https://gist.github.com/217362 | |
Warden::Manager.before_failure do |env, opts| | |
env['REQUEST_METHOD'] = "POST" | |
end | |
run AppMain | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /slim/slim.rb | |
APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) | |
require 'rubygems' | |
require 'sinatra' | |
require 'warden' | |
require 'json' | |
# ============= | |
# Const | |
# ============= | |
RACK_ENV = "#{ENV['RACK_ENV']}".downcase | |
EMPTY_JSON = JSON.generate({}) | |
class AppMain < Sinatra::Application | |
set :root, APP_ROOT | |
get '/' do | |
redirect '/app.html' | |
end | |
get '/protected' do | |
if env['warden'].unauthenticated? | |
halt 401, "User is not logged in." | |
end | |
'Hello World' | |
end | |
# ------------- | |
# Auth | |
# ------------- | |
# See, from https://gist.github.com/217362 | |
post '/unauthenticated/?' do | |
options = env['warden.options'] || {} | |
code = options[:code] || 401 | |
message = options[:message] || 'Unauthorized' | |
json = { | |
:code => code, | |
:message => message, | |
:options => options | |
} | |
halt code, JSON.generate(json) | |
end | |
get '/logout/?' do | |
env['warden'].logout | |
redirect '/app.html' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment