Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## user model
- require "digest/sha1"
- class User < ActiveRecord::Base
- # Virtual attribute for storing the plain-text password in memory
- attr_accessor :password
- validates_format_of :email, :with => /^[^@]+@[^@]+\..+$/i
- validates_length_of :password, :minimum => 4, :if => :handle_password?
- validates_confirmation_of :password, :if => :handle_password?
- before_save :salt_and_hash_password, :if => :handle_password?
- def self.authenticate(email, password)
- user = find_by_email(email)
- user && user.valid_password?(password) && user
- end
- def valid_password?(password)
- self.password_hash == hash_password(password)
- end
- private
- def hash_password(password)
- Digest::SHA1.hexdigest("!--#{password_salt}-ZOMG-#{password}--!")
- end
- def salt_and_hash_password
- self.password_salt = ActiveSupport::SecureRandom.hex(20)
- self.password_hash = hash_password(password)
- self.password = nil
- end
- def handle_password?
- new_record? || !password.blank?
- end
- end
- ## lib/authentication.rb (included in app controller)
- module Worklog
- module Authentication
- private
- def current_user
- @current_user ||= session[:user_id] && User.find(session[:user_id])
- end
- def current_user=(user_or_nil)
- @current_user = user_or_nil
- session[:user_id] = user_or_nil.is_a?(User) ? user_or_nil.id : nil
- end
- def login_required
- restrict_access unless logged_in?
- end
- def logged_in?
- current_user.is_a?(User)
- end
- def restrict_access
- redirect_to root_path
- end
- end
- end
Add Comment
Please, Sign In to add comment