Advertisement
Guest User

Untitled

a guest
Feb 28th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.85 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2.   attr_accessible :email,
  3.                   :email_confirmation,
  4.                   :password,
  5.                   :password_confirmation,
  6.                   :username
  7.  
  8.   attr_accessor :password, :password_confirmation, :email_confirmation
  9.  
  10.   belongs_to :group
  11.  
  12.   name_regex = /\A[\w+\-.]+\z/i
  13.   email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  14.  
  15.   validates :username,  :presence => true,
  16.                         :length => { :maximum => 25 },
  17.                         :format => { :with => name_regex }
  18.  
  19.   validates :password, :length => { :in => 5..20 }
  20.   validates :password, :confirmation => true
  21.   validates :password_confirmation, :presence => true
  22.  
  23.   validates :email, :confirmation => true,
  24.                     :uniqueness => { :case_sensitive => false },
  25.                     :format => { :with => email_regex }
  26.   validates :email_confirmation, :presence => true
  27.  
  28.   before_save :encrypt_password
  29.  
  30.   def self.authenticate(email, submitted_password)
  31.     user = find_by_email(email)
  32.     return nil if user.nil?
  33.     return user if user.has_password?(submitted_password)
  34.   end
  35.  
  36.   def self.authenticate_with_salt(id, cookie_salt)
  37.     user = find_by_id(id)
  38.     return nil if user.nil?
  39.     return user if user.salt == cookie_salt
  40.   end
  41.  
  42.   def has_password?(string)
  43.     password_hash == encrypt(string)
  44.   end
  45.  
  46.   def role?(s)
  47.     group.nil? || new_record? ? false : group.groupname.to_sym == s
  48.   end
  49.  
  50.   private
  51.  
  52.     def encrypt_password
  53.       self.salt = generate_salt if new_record?
  54.       self.password_hash = encrypt(password)
  55.     end
  56.  
  57.     def encrypt(string)
  58.       secure_hash("#{salt}:#{string}")
  59.     end
  60.    
  61.     def generate_salt
  62.       secure_hash("#{Time.now.utc}:#{password}")
  63.     end
  64.    
  65.     def secure_hash(string)
  66.       Digest::SHA2.hexdigest(string)
  67.     end
  68. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement