Created
December 27, 2010 03:11
-
-
Save haileys/755826 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'digest/sha2' | |
require 'active_support/secure_random' | |
class User < ActiveRecord::Base | |
validates_presence_of :username, :password, :salt | |
def password=(pw) | |
set_salt unless salt | |
write_attribute :password, hash(pw) | |
end | |
def salt=(h) | |
raise 'User#salt is readonly' | |
end | |
def test_password(pw) | |
password == hash(pw) | |
end | |
private | |
def set_salt | |
write_attribute :salt, SecureRandom.base64(4) | |
end | |
def hash(msg) | |
digest = Digest::SHA2.new 512 | |
digest << salt << msg << salt | |
digest.to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment