Guest User

Untitled

a guest
Aug 2nd, 2018
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. User.authenticate method returning nil in Rails 3?
  2. class SessionsController < ApplicationController
  3.  
  4. def new
  5. end
  6.  
  7. def create
  8. user = User.authenticate(params[:session][:email],
  9. params[:session][:password])
  10. if user.nil?
  11. flash.now[:error] = "Invalid email/password combination"
  12. render 'new'
  13. else
  14. sign_in user
  15. redirect_to user
  16. end
  17. end
  18.  
  19. def destroy
  20. sign_out
  21. render 'pages/options'
  22. end
  23.  
  24. end
  25.  
  26. class User < ActiveRecord::Base
  27.  
  28. attr_accessor :password
  29. attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
  30. :account_type, :email_confirmed, :weight
  31.  
  32. validates :password, :presence => true,
  33. :confirmation => true,
  34. :length => { :within => 6..40 }
  35.  
  36. before_save :encrypt_password
  37.  
  38. def has_password?(submitted_password)
  39. encrypted_password == encrypt(submitted_password)
  40. end
  41.  
  42. def self.authenticate(email, submitted_password)
  43. user = find_by_email(email)
  44. return nil if user.nil?
  45. return user if user.has_password?(submitted_password)
  46. end
  47.  
  48. def self.authenticate_with_salt(id, cookie_salt)
  49. user = find_by_id(id)
  50. (user && user.salt == cookie_salt) ? user : nil
  51. end
  52.  
  53. private #################################################
  54.  
  55. def encrypt_password
  56. self.salt = make_salt if new_record?
  57. self.encrypted_password = encrypt(password)
  58. end
  59.  
  60. def encrypt(string)
  61. secure_hash("#{salt}--#{string}")
  62. end
  63.  
  64. def make_salt
  65. secure_hash("#{Time.now.utc}--#{password}")
  66. end
  67.  
  68. def secure_hash(string)
  69. Digest::SHA2.hexdigest(string)
  70. end
  71.  
  72. def generate_email_conf_code
  73. email_conf_code = secure_hash("#{Time.now.utc}")
  74. self.email_conf_code = email_conf_code
  75. end
  76.  
  77. end
  78.  
  79. Parameters: {"session"=>{"email"=>"xxx@yyy.com", "password"=>"[FILTERED]"}}
Add Comment
Please, Sign In to add comment