Guest User

Untitled

a guest
Mar 9th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #this is the user model. I can't figure out how to make it so it wont save if the password is blank
  2.  
  3. require 'digest/sha1'
  4.  
  5. class User < ActiveRecord::Base
  6. has_many :contact_notes
  7.  
  8. validates_presence_of:first_name, :last_name, :username
  9. validates_uniqueness_of :username
  10.  
  11. attr_accessor :password_confirmation
  12. validates_confirmation_of :password
  13.  
  14. def validate
  15. errors.add_to_base("Missing password") if hashed_password.blank?
  16. end
  17.  
  18. def self.authenticate(username, password)
  19. user = self.find_by_username(username)
  20. if user
  21. expected_password = encrypted_password(password, user.salt)
  22. if user.hashed_password != expected_password
  23. user = nil
  24. end
  25. end
  26. user
  27. end
  28.  
  29. def password
  30. @password
  31. end
  32.  
  33. def password=(pwd)
  34. @password = pwd
  35. create_new_salt
  36. self.hashed_password = User.encrypted_password(self.password, self.salt)
  37. end
  38.  
  39. def fullname
  40. "#{self.first_name} #{self.last_name}"
  41. end
  42.  
  43. private
  44.  
  45. def self.encrypted_password(password, salt)
  46. string_to_hash = password + "wibble" + salt
  47. Digest::SHA1.hexdigest(string_to_hash)
  48. end
  49.  
  50. def create_new_salt
  51. self.salt = self.object_id.to_s + rand.to_s
  52. end
  53. end
  54.  
  55. #this is the user table migration
  56.  
  57. class CreateUsers < ActiveRecord::Migration
  58. def self.up
  59. create_table :users do |t|
  60. t.column :username, :string
  61. t.column :last_login, :datetime
  62. t.column :first_name, :string
  63. t.column :last_name, :string
  64. t.column :hashed_password, :string
  65. t.column :salt, :string
  66. end
  67.  
  68. User.create(:first_name => 'First', :last_name => 'Tester', :username => 'first_tester', :hashed_password => '91aaf8d534d2d7d312d3263f814803fe02d171c8',
  69. :salt => '-6160383180.219591962220015')
  70. end
  71.  
  72. def self.down
  73. drop_table :users
  74. end
  75. end
Add Comment
Please, Sign In to add comment