Skip to content

Instantly share code, notes, and snippets.

@kartikrustagi
Created April 15, 2012 11:23
Show Gist options
  • Save kartikrustagi/2391991 to your computer and use it in GitHub Desktop.
Save kartikrustagi/2391991 to your computer and use it in GitHub Desktop.
Auth using Sinatra-Warden
require 'openssl'
class AppUser < Sequel::Model(:AppUsers)
AppUser.unrestrict_primary_key
def self.authenticate(username, password)
#TODO: Store salt in config
puts "In Auth"
user = self.first(:username => username)
user if user && (user.password == OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('md5'), "secretsalt", password))
end
def self.signup(username, password)
AppUser.create(
:username => username,
:password => OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('md5'), "secretsalt", password),
:created_at => Time.now
)
end
end
class AuthApp < Sinatra::Base
set :root, File.dirname("../")
post '/unauthenticated' do
uri = env['REQUEST_URI']
env['rack.session'][:return_to] = env['warden.options'][:attempted_path]
[302, {'Location' => '/login'}, '']
end
get '/login/?' do
haml :login
end
post '/login/?' do
env['warden'].authenticate!
redirect env['rack.session'][:return_to]
end
#TODO: Do signups manually for now
get '/logout/?' do
env['warden'].logout
redirect '/login'
end
end
class Example < Sinatra::Base
get '/upload' do
env['warden'].authenticate!
puts env['warden'].user
haml :upload
end
end
.container
%form.well.form-inline{:name => "login form", :action => "/login", :method => "post"}
%input.input-small{:placeholder => "username", :type => "text", :name => "username"}
%input.input-small{:placeholder => "passsword", :type => "password", :name => "password"}
%button.btn{:type => "submit"} Sign In
class Main < Sinatra::Base
use Rack::Session::Cookie, :secret => "secret salt" #TODO: Make part of config files
Warden::Manager.serialize_into_session{|user| user.id}
Warden::Manager.serialize_from_session{|id| AppUser.get(id)}
Warden::Strategies.add(:password) do #password is the name of the stratergy
def valid?
params["username"] || params["password"]
end
def authenticate!
user = AppUser.authenticate(params["username"], params["password"])
user.nil? ? fail!("Invalid credentials. Login failed") : success!(user, "Auth success")
end
end
use Warden::Manager do |manager|
manager.default_strategies :password
manager.failure_app = AuthApp
end
get '/check' do
env['warden'].authenticate!
redirect ('/')
end
use Example
end
require 'sequel'
Sequel.migration do
change do
create_table(:AppUsers) do
primary_key :id, :auto_increment=>true
String :username, :unique => true
String :password
DateTime :created_at
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment