require 'digest/sha1' module SimpleAuth module Authenticated # Hook for all Clearance::User modules. # # If you need to override parts of Clearance::User, # extend and include à la carte. # # @example # extend ClassMethods # include InstanceMethods # include AttrAccessor # include Callbacks # # @see ClassMethods # @see InstanceMethods # @see AttrAccessible # @see AttrAccessor # @see Validations # @see Callbacks def self.included(model) model.extend(ClassMethods) model.send(:include , AttrAccessor) model.send(:include, InstanceMethods) model.send(:include, Callbacks) end module Callbacks def self.included(model) model.class_eval do before_save :initialize_salt, :encrypt_password before_create :generate_confirmation_token , :generate_remember_token end end end module AttrAccessor # Hook for attr_accessor virtual attributes. # # :password def self.included(model) model.class_eval do attr_accessor :password end end end module InstanceMethods def authenticated?(password) encrypted_password == encrypt(password) end def confirm! self.confirmed = true self.confirmation_token = nil primary_contact = self.contacts.where(:value => self.login , :confirmed => false).first primary_contact.confirm! save(:validate => false) end def reset_remember_token! generate_remember_token save(:validate => false) end def forgot_password! generate_confirmation_token save(:validate => false) end protected def initialize_salt if new_record? self.password_salt = Digest::SHA1.hexdigest Time.now.to_s end end def generate_remember_token self.remember_token = encrypt("#{Time.now} -- #{Time.now}") end def generate_confirmation_token self.confirmation_token = encrypt("#{Time.now} -- #{Time.now}") end def encrypt_password self.encrypted_password = encrypt(password) unless password.blank? end def encrypt(password) Digest::SHA1.hexdigest "#{password}#{password_salt}" end end module ClassMethods def authenticate(login, password) return nil unless user = find_by_login(login) return user if user.authenticated?(password) end end end end