Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #this is the user model. I can't figure out how to make it so it wont save if the password is blank
- require 'digest/sha1'
- class User < ActiveRecord::Base
- has_many :contact_notes
- validates_presence_of:first_name, :last_name, :username
- validates_uniqueness_of :username
- attr_accessor :password_confirmation
- validates_confirmation_of :password
- def validate
- errors.add_to_base("Missing password") if hashed_password.blank?
- end
- def self.authenticate(username, password)
- user = self.find_by_username(username)
- if user
- expected_password = encrypted_password(password, user.salt)
- if user.hashed_password != expected_password
- user = nil
- end
- end
- user
- end
- def password
- @password
- end
- def password=(pwd)
- @password = pwd
- create_new_salt
- self.hashed_password = User.encrypted_password(self.password, self.salt)
- end
- def fullname
- "#{self.first_name} #{self.last_name}"
- end
- private
- def self.encrypted_password(password, salt)
- string_to_hash = password + "wibble" + salt
- Digest::SHA1.hexdigest(string_to_hash)
- end
- def create_new_salt
- self.salt = self.object_id.to_s + rand.to_s
- end
- end
- #this is the user table migration
- class CreateUsers < ActiveRecord::Migration
- def self.up
- create_table :users do |t|
- t.column :username, :string
- t.column :last_login, :datetime
- t.column :first_name, :string
- t.column :last_name, :string
- t.column :hashed_password, :string
- t.column :salt, :string
- end
- User.create(:first_name => 'First', :last_name => 'Tester', :username => 'first_tester', :hashed_password => '91aaf8d534d2d7d312d3263f814803fe02d171c8',
- :salt => '-6160383180.219591962220015')
- end
- def self.down
- drop_table :users
- end
- end
Add Comment
Please, Sign In to add comment