Created
May 25, 2012 10:50
-
-
Save metacritical/2787278 to your computer and use it in GitHub Desktop.
model.rb
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
class User < ActiveRecord::Base | |
attr_accessible :email, :firstname, :lastname, :password_hash, :password_salt , :password , | |
:password_confirmation, :user_type | |
before_save :encrypt_password | |
attr_accessor :password | |
validates_confirmation_of :password | |
validates :email, presence: {:message => 'Email cannot be blank'} | |
validates :firstname, presence: {:message => 'Firstname can\'t be blank'} | |
validates :lastname, presence: {:message => 'Lastname can\'t be blank'} | |
validates_uniqueness_of :email | |
validates_presence_of :password, :on => :create | |
validates_presence_of :password_confirmation, :on => :create | |
before_create {generate_token(:auth_token)} | |
def encrypt_password | |
if password.present? | |
self.password_salt = BCrypt::Engine.generate_salt | |
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) | |
end | |
end | |
def authenticate(email,password) | |
user = User.find_by_email(email) | |
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) | |
user | |
else | |
nil | |
end | |
end | |
def generate_token(column) | |
begin | |
self[column] = SecureRandom.urlsafe_base64 | |
end while User.exists?(column => self[column]) | |
end | |
def sent_password_reset | |
generate_token(:password_reset_token) | |
self.password_reset_sent_at = Time.now | |
save! | |
UserMailer.password_reset(self).deliver | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment