Created
February 25, 2010 17:53
-
-
Save neaf/314817 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'bcrypt' | |
| module Ark | |
| module Mixins | |
| module BCryptUser | |
| def self.included(base) | |
| base.class_eval do | |
| attr_accessor :password, :password_confirmation | |
| before_save :encrypt_password | |
| field :crypted_password, :type => String, :length => 60 | |
| validates_presence_of :password, :password_confirmation, :if => proc { self.password_required? } | |
| validates_confirmation_of :password, :if => proc { self.password_required? } | |
| extend Ark::Mixins::BCryptUser::ClassMethods | |
| include Ark::Mixins::BCryptUser::InstanceMethods | |
| end | |
| end | |
| module ClassMethods | |
| def authenticate(username, password) | |
| puts username | |
| puts password | |
| u = User.find(username) | |
| u && u.authenticated?(password) ? u : nil | |
| end | |
| end | |
| module InstanceMethods | |
| def authenticated?(password) | |
| bcrypt_password == password | |
| end | |
| def bcrypt_password | |
| @bcrypt_password ||= BCrypt::Password.new(crypted_password) | |
| end | |
| def password_required? | |
| crypted_password.blank? || !password.blank? | |
| end | |
| def encrypt_password | |
| return if password.blank? | |
| cost = BCrypt::Engine::DEFAULT_COST | |
| self.crypted_password = BCrypt::Password.create(password, :cost => cost) | |
| end | |
| end | |
| end | |
| end | |
| end |
This file contains hidden or 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
| Warden::Strategies.add(:basic) do | |
| def valid? | |
| params["user"]["username"] && params["user"]["password"] | |
| end | |
| def authenticate! | |
| u = User.authenticate(params["user"]["username"], params["user"]["password"]) | |
| u.nil? ? fail!("Could not log in") : success!(u) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment