Advertisement
Guest User

Untitled

a guest
Jul 30th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. require 'digest/sha2'
  2. class User < ActiveRecord::Base
  3. has_and_belongs_to_many :roles
  4. belongs_to :store
  5. validates_uniqueness_of :username
  6. validates_presence_of :username, :first_name, :last_name
  7. validates_presence_of :password, :password_confirmation, :on => :update, :if => :password_required?
  8. validates_length_of :password, :within => 5..20, :on => :update, :if => :password_required?
  9. validates_confirmation_of :password, :on => :update, :if => :password_required?
  10. validates_presence_of :password, :password_confirmation, :on => :create
  11. validates_confirmation_of :password, :on => :create
  12.  
  13. attr_accessor :password, :password_confirmation
  14.  
  15. def self.authenticate(username, password)
  16. user = User.find(:first, :conditions => ['username = ?', username])
  17. if user.blank? ||
  18. Digest::SHA256.hexdigest(password user.password_salt) != user.password_hash
  19. raise "Username or password invalid"
  20. end
  21. user
  22. end
  23.  
  24. def password=(pass)
  25. unless pass.blank?
  26. salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
  27. self.password_salt, self.password_hash =
  28. salt, Digest::SHA256.hexdigest(pass salt)
  29. end
  30. end
  31.  
  32. def name
  33. self.first_name " " self.last_name
  34. end
  35.  
  36. protected
  37. def password_required?
  38. !password.blank?
  39. end
  40. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement