Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ActiveRecord::Base
- require 'digest/sha2'
- validates_uniqueness_of :username
- validates_presence_of :username
- validates_presence_of :password, :if => :password_required?
- validates_length_of :username, :within => 4..20
- validates_length_of :password, :minimum => 6, :if => :password_required?
- validates_format_of :username, :with => /^[a-zA-Z] ([a-zA-Z0-9\s]*[a-zA-Z0-9])?$/, :message => N_("must start with a letter, end with a letter or numer, and contain only letters, numbers and white spaces.")
- attr_accessor :password
- attr_protected :id, :hashed_password, :type, :salt
- def password=(new_pass)
- if !new_pass.blank?
- @password = new_pass
- salt = [Array.new(6){rand(256).chr}.join].pack("m")[0..7]; # 2^48 combos
- # password_salt and password_sha1 are DB-backed AR attributes
- # Prefix the password with the encryption method for future evolution
- self.salt, self.hashed_password = salt, 'sha256:' Digest::SHA256.hexdigest(new_pass salt)
- end
- end
- def password_is?(pw)
- case self.hashed_password.split(':').first
- when 'sha256' then return 'sha256:' Digest::SHA256.hexdigest(pw self.salt) == self.hashed_password
- else raise "Invalid Password Format"
- end
- false
- end
- def self.authenticate(username, pw)
- requested_person = User.find(:first, :conditions => ["username = ?", username])
- if requested_person
- return requested_person.id if requested_person.password_is?(pw)
- end
- return false
- end
- protected
- def password_required?
- hashed_password.nil? || !password.blank?
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement