Sha256: c3d463ba9c55f9a0cc1fd2b313d08065dd05aaa4c762ccea550405768e2ffe82

Contents?: true

Size: 1.24 KB

Versions: 4

Compression:

Stored size: 1.24 KB

Contents

require 'digest'
require 'securerandom'

class User < ActiveRecord::Base
  # new columns need to be added here to be writable through mass assignment
  attr_accessible :username, :email, :password, :password_confirmation

  attr_accessor :password
  before_save :prepare_password

  validates_presence_of :username
  validates_uniqueness_of :username, :email, :allow_blank => true
  validates_format_of :username, :with => /^[-\w\._@]+$/i, :allow_blank => true, :message => "should only contain letters, numbers, or .-_@"
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
  validates_presence_of :password, :on => :create
  validates_confirmation_of :password
  validates_length_of :password, :minimum => 4, :allow_blank => true

  # login can be either username or email address
  def self.authenticate(login, pass)
    user = find_by_username(login) || find_by_email(login)
    return user if user && user.password_hash == user.encrypt_password(pass)
  end

  def encrypt_password(pass)
    Digest::SHA2.hexdigest(pass + password_salt)
  end

  private

  def prepare_password
    unless password.blank?
      self.password_salt = SecureRandom.hex(16)
      self.password_hash = encrypt_password(password)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
alondra-0.1.1 test/dummy/app/models/user.rb
alondra-0.1.0 test/dummy/app/models/user.rb
alondra-0.0.4 test/dummy/app/models/user.rb
alondra-0.0.3 test/dummy/app/models/user.rb