Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'digest/sha1'
- # this model expects a certain database layout and its based on the name/login pattern.
- module AuthenticatedUser
- SALT = "s@xx%^&omemealsdfj234lL@#23-= _4ksdsdlasdf9asd0f9"
- DELAYED_DELETE_DAYS = 3
- SECURITY_TOKEN_LIFE_HOURS = 1024
- USE_EMAIL_NOTIFICATION = true
- EMAIL_FROM = "info@whatever.com"
- APP_NAME = "Whatever"
- def self.included(base)
- base.extend(ClassMethods)
- end
- # This module contains class methods
- module ClassMethods
- def authenticate(login, pass)
- user = find(:first, :conditions => ["login = ? AND verified = 1 AND deleted = 0", login])
- return nil if user.nil?
- user = find(:first, :conditions => ["login = ? AND salted_password = ? AND verified = 1", login, AuthenticatedUser.salted_password(user.salt, AuthenticatedUser.hashed(pass))])
- return nil if user.nil?
- user.update_attribute(:logged_in_at, Time.now)
- logger.debug("Authenticated by login and pass user: #{user.id} at #{user.logged_in_at}")
- return user
- end
- def hashed(str)
- # check if a salt has been set...
- if SALT == nil
- raise "SALT cannot be nil"
- end
- return Digest::SHA1.hexdigest("#{SALT}--#{str}--}")[0..39]
- end
- def salted_password(salt, hashed_password)
- hashed(salt hashed_password)
- end
- def acts_as_authenticated
- include InstanceMethods
- attr_accessor :new_password
- attr_accessor :password, :password_confirmation
- validates_presence_of :login
- validates_length_of :login, :within => 3..40
- validates_uniqueness_of :login
- validates_uniqueness_of :email
- validates_format_of :email, :with => /^[^@] @. $/
- validates_presence_of :password, :if => :validate_password?
- validates_confirmation_of :password, :if => :validate_password?
- validates_length_of :password, { :minimum => 5, :if => :validate_password? }
- validates_length_of :password, { :maximum => 40, :if => :validate_password? }
- after_validation :crypt_password
- after_save :falsify_new_password
- end
- end
- # This module contains instance methods
- module InstanceMethods
- def initialize(attributes = nil)
- super
- @new_password = false
- end
- def change_password(pass, confirm = nil)
- self.password = pass
- self.password_confirmation = confirm.nil? ? pass : confirm
- @new_password = true
- end
- protected
- def validate_password?
- @new_password
- end
- def crypt_password
- if @new_password
- self.salt = AuthenticatedUser.hashed("salt-#{Time.now}")
- self.salted_password = AuthenticatedUser.salted_password(salt, AuthenticatedUser.hashed(@password))
- end
- end
- def falsify_new_password
- @new_password = false
- true
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement