Skip to content

Instantly share code, notes, and snippets.

@nu7hatch
Created August 4, 2010 09:32
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nu7hatch/507894 to your computer and use it in GitHub Desktop.
Save nu7hatch/507894 to your computer and use it in GitHub Desktop.
Padrino authentication with Warden
require 'authtools/password'
class Account
include Mongoid::Document
include Mongoid::Timestamps
#include Mongoid::Paranoia
attr_accessor :password
field :email, :type => String
field :crypted_password, :type => String
field :role, :type => String
validates_presence_of :email
validates_uniqueness_of :email
validates_presence_of :password, :if => proc {|u| u.new_record?}
validates_confirmation_of :password, :if => proc {|u| !u.password.nil? }
before_save :generate_password_if_needed
def self.authenticate(email, password)
if account = where(:email => email).first
account.authenticate(password)
end
end
def authenticate(password)
self if Authtools::Password.check(password, self.crypted_password)
end
protected
def generate_password_if_needed
self.crypted_password = Authtools::Password.generate(password) if password
end
end
class MyApp < Padrino::Application
register Padrino::Mailer
register Padrino::Helpers
register Padrino::Warden
register SassInitializer
set :raise_errors
enable :store_location
enable :sessions
layout :application
Warden::Strategies.add(:password) do
def valid?
params["email"] || params["password"]
end
def authenticate!
account = Account.authenticate(params["email"], params["password"])
account.nil? ? fail!("Invalid username or password") : success!(account)
end
end
Warden::Manager.serialize_into_session {|account| account.email }
Warden::Manager.serialize_from_session {|email| Account.where(:email => email).first }
alias_method :current_account, :user
def store_location!
session['warden.location'] = request.path
end
def redirect_back_or(*args)
if back = session['warden.location']
session.delete('warden.location')
redirect(back)
else
redirect(*args)
end
end
end
# ...
gem 'padrino-warden', :git => "git://github.com/zmack/padrino-warden.git"
gem 'authtools'
- content_for :header, "Login to your account..."
= flash_tag :notice
- form_tag(url(:sessions_login), :id => 'new_session') do
.inputs
.field.string
%label.label(for='email') Login
= text_field_tag :email, :value => params[:email]
.field.string.password
%label.label(for='password') Password
= password_field_tag :password
.buttons
= submit_tag('Sign In')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment