Guest User

Untitled

a guest
Jun 20th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. ## user model
  2. require "digest/sha1"
  3. class User < ActiveRecord::Base
  4. # Virtual attribute for storing the plain-text password in memory
  5. attr_accessor :password
  6.  
  7. validates_format_of :email, :with => /^[^@]+@[^@]+\..+$/i
  8. validates_length_of :password, :minimum => 4, :if => :handle_password?
  9. validates_confirmation_of :password, :if => :handle_password?
  10.  
  11. before_save :salt_and_hash_password, :if => :handle_password?
  12.  
  13. def self.authenticate(email, password)
  14. user = find_by_email(email)
  15. user && user.valid_password?(password) && user
  16. end
  17.  
  18. def valid_password?(password)
  19. self.password_hash == hash_password(password)
  20. end
  21.  
  22. private
  23.  
  24. def hash_password(password)
  25. Digest::SHA1.hexdigest("!--#{password_salt}-ZOMG-#{password}--!")
  26. end
  27.  
  28. def salt_and_hash_password
  29. self.password_salt = ActiveSupport::SecureRandom.hex(20)
  30. self.password_hash = hash_password(password)
  31. self.password = nil
  32. end
  33.  
  34. def handle_password?
  35. new_record? || !password.blank?
  36. end
  37. end
  38.  
  39. ## lib/authentication.rb (included in app controller)
  40. module Worklog
  41. module Authentication
  42. private
  43.  
  44. def current_user
  45. @current_user ||= session[:user_id] && User.find(session[:user_id])
  46. end
  47.  
  48. def current_user=(user_or_nil)
  49. @current_user = user_or_nil
  50. session[:user_id] = user_or_nil.is_a?(User) ? user_or_nil.id : nil
  51. end
  52.  
  53. def login_required
  54. restrict_access unless logged_in?
  55. end
  56.  
  57. def logged_in?
  58. current_user.is_a?(User)
  59. end
  60.  
  61. def restrict_access
  62. redirect_to root_path
  63. end
  64. end
  65. end
Add Comment
Please, Sign In to add comment