Skip to content

Instantly share code, notes, and snippets.

@durango
Created August 12, 2011 16:14
Show Gist options
  • Save durango/1142385 to your computer and use it in GitHub Desktop.
Save durango/1142385 to your computer and use it in GitHub Desktop.
require 'bcrypt'
require 'securerandom'
class User
include DataMapper::Resource
include BCrypt
property :id, Serial
property :email, String, :required => true, :index => :login, :unique => true, :unique_index => true, :format => :email_address
property :password_hash, Text, :required => true, :index => :login
property :password_salt, Text, :required => true, :writer => :protected
property :auth_token, Text
property :name, String, :unique => true, :required => true, :length => 3..30, :message => "Your name must not be blank and at least 3 characters.", :unique_index => true
attr_accessor :password, :password_confirmation, :password_needed,
:_csrf, :password_reset, :pid, :gender, :main_name, :char_name,
:id_base, :id_hair, :id_head, :id_torso, :id_legs, :id_weapon
validates_presence_of :password_confirmation, :password, :if => :password_needed?
validates_length_of :password, :min => 6, :max => 255, :if => :password_needed?
validates_confirmation_of :password, :if => :password_needed?
before :valid?, :make_password
def change_password(the_pass)
self.password_hash = BCrypt::Password.create(the_pass)
end
def make_password
if new? or !self.forgotten.nil?
self.email.to_s.downcase unless self.email.nil?
self.password_salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
password = [Array.new(14){rand(256).chr}.join].pack("m").chomp if password.nil?
self.password_hash = BCrypt::Password.create(password + self.password_salt)
self.char_name = name if new?
end
password
end
def crypted_pass
pass = attribute_get(:password_hash)
return nil if pass.nil?
BCrypt::Password.new(pass)
end
alias_method :crypted_password, :crypted_pass
def forgotten_token
token = SecureRandom.hex(16)
self.forgotten = token
self.forgotten_at = DateTime.now
token
end
def new_account?
new?
end
def password_needed?
new? or password_reset
end
def reset_password
token = forgotten_token
save!
Pony.mail() # snip
end
def authenticate(password)
crypted_pass == (password)
end
def self.authenticate(username, password)
u = first(:email => username.to_s.downcase)
if u && u.authenticate(password)
u
else
nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment