Skip to content

Instantly share code, notes, and snippets.

@stefanoc
Created February 3, 2009 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stefanoc/57558 to your computer and use it in GitHub Desktop.
Save stefanoc/57558 to your computer and use it in GitHub Desktop.
require "digest/sha1"
module AuthenticationModel
def self.included(base)
base.send(:include, InstanceMethods)
base.send(:extend, ClassMethods)
base.send(:validates_presence_of, :email, :message => "L'indirizzo email è richiesto.")
base.send(:validates_presence_of, :password, :if => :password_required?, :message => "La password è richiesta.")
base.send(:validates_uniqueness_of, :email, :case_sensitive => false, :message => "Questo indirizzo email è già presente.")
base.send(:validates_confirmation_of, :password, :if => :password_required?, :message => "La password non è stata confermata.")
base.send(:before_save, :encrypt_password)
base.send(:attr_accessor, :password, :password_confirmation)
end
module ClassMethods
def authenticate(email, password)
u = find_by_email(email)
u && u.authenticated?(password) && u.active? ? u : nil
end
def authenticate_in_public(id, key)
u = find(id)
u.public_authentication_key == key ? u : nil
rescue Exception
false
end
def encrypt(password, salt)
Digest::SHA1.hexdigest("--#{ salt }--#{ password }--")
end
end
module InstanceMethods
def encrypt(password)
self.class.encrypt(password, salt)
end
def remember_token?
remember_token_expires_at && Time.now.utc < remember_token_expires_at
end
def remember_me
self.remember_token_expires_at = 2.weeks.from_now.utc
self.remember_token = encrypt("#{ email }--#{ remember_token_expires_at }")
save(false)
end
def forget_me
self.remember_token_expires_at = nil
self.remember_token = nil
save(false)
end
def authenticated?(password)
hashed_password == encrypt(password)
end
PASSWORD_CHARS = (('a'..'z').to_a + ('0'..'9').to_a) - %w(i o 0 1 l 0)
def reset_password!
new_password = (1..6).collect{|a| PASSWORD_CHARS[rand(PASSWORD_CHARS.size)] }.join
self.password = new_password
save!
return new_password
end
def public_authentication_key
@public_authentication_key ||= encrypt(email)
end
private
def encrypt_password
return if password.nil?
self.salt = Digest::SHA1.hexdigest("--#{ Time.now.to_s }--#{ email }--") if new_record?
self.hashed_password = encrypt(password)
end
def password_required?
hashed_password.blank? || password
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment