-
-
Save TiagoTi/ae78b5df966c2e6d8d99 to your computer and use it in GitHub Desktop.
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
require 'sinatra' | |
require 'warden' | |
class YourApp < Sinatra::Application | |
get "/" do | |
erb 'index'.to_sym | |
end | |
get "/protected_pages" do | |
check_authentication | |
erb 'admin_only_page'.to_sym | |
end | |
get "/login" do | |
erb '/login'.to_sym | |
end | |
post "/session" do | |
warden_handler.authenticate! | |
if warden_handler.authenticated? | |
redirect "/users/#{warden_handler.user.id}" | |
else | |
redirect "/" | |
end | |
end | |
get "/logout" do | |
warden_handler.logout | |
redirect '/login' | |
end | |
post "/unauthenticated" do | |
redirect "/" | |
end | |
# Warden configuration code | |
use Rack::Session::Cookie | |
use Warden::Manager do |manager| | |
manager.default_strategies :password | |
manager.failure_app = YourApp | |
manager.serialize_into_session {|user| user.id} | |
manager.serialize_from_session {|id| Datastore.for(:user).find_by_id(id)} | |
end | |
Warden::Manager.before_failure do |env,opts| | |
env['REQUEST_METHOD'] = 'POST' | |
end | |
Warden::Strategies.add(:password) do | |
def valid? | |
params["email"] || params["password"] | |
end | |
def authenticate! | |
user = Datastore.for(:user).find_by_email(params["email"]) | |
if user && user.authenticate(params["password"]) | |
success!(user) | |
else | |
fail!("Could not log in") | |
end | |
end | |
end | |
def warden_handler | |
env['warden'] | |
end | |
def check_authentication | |
unless warden_handler.authenticated? | |
redirect '/login' | |
end | |
end | |
def current_user | |
warden_handler.user | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment