Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.81 KB | None | 0 0
  1. # == Schema Information
  2. # Schema version: 20110310145613
  3. #
  4. # Table name: users
  5. #
  6. #  id                 :integer         not null, primary key
  7. #  name               :string(255)
  8. #  email              :string(255)
  9. #  created_at         :datetime
  10. #  updated_at         :datetime
  11. #  encrypted_password :string(255)
  12. #
  13.  
  14. class User < ActiveRecord::Base
  15.   attr_accessor :password
  16.   attr_accessible :name, :email, :password, :password_confirmation
  17.  
  18.   email_regex = /\A[\w+.]+@[a-z\d\-.]+\.[a-z]+\z/i
  19.  
  20.   validates :name, :presence => true,
  21.                    :length => { :maximum => 50 }  
  22.  
  23.   validates :email, :presence => true,
  24.                     :format => { :with => email_regex },
  25.                     :uniqueness => { :case_sensitive => false }
  26.  
  27.   validates :password,  :presence => true,
  28.                         :confirmation => true,
  29.                         :length =>  { :within => 6..40 }
  30.  
  31.   before_save :encrypt_password
  32.  
  33.   # miksi attribuutti encrypted_password toimii noin? siksikö että peritään ActiveRecord ja
  34.   # se talletetaan
  35.   #
  36.   # miksi (self.)encrypted_password sitten on eri asia kun @encrypted_password
  37.  
  38.   def has_password?(submitted_password)
  39.     encrypt(submitted_password)
  40.     encrypted_password == encrypt(submitted_password)
  41.   end
  42.  
  43.   def self.authenticate(email, submitted_password)
  44.     user = find_by_email email
  45.     return nil if user.nil?
  46.     return user if user.has_password?(submitted_password)
  47.   end
  48.  
  49.   private
  50.  
  51.     def encrypt_password
  52.       self.salt = make_salt if new_record?
  53.       self.encrypted_password = encrypt(password)
  54.     end
  55.  
  56.     def encrypt(string)
  57.       secure_hash("#{salt}--#{string}")
  58.     end
  59.  
  60.     def make_salt
  61.       secure_hash("#{Time.now.utc}--@{password}")
  62.     end
  63.  
  64.   def secure_hash(string)
  65.     Digest::SHA2.hexdigest(string)
  66.   end
  67. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement