Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- User.authenticate method returning nil in Rails 3?
- class SessionsController < ApplicationController
- def new
- end
- def create
- user = User.authenticate(params[:session][:email],
- params[:session][:password])
- if user.nil?
- flash.now[:error] = "Invalid email/password combination"
- render 'new'
- else
- sign_in user
- redirect_to user
- end
- end
- def destroy
- sign_out
- render 'pages/options'
- end
- end
- class User < ActiveRecord::Base
- attr_accessor :password
- attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
- :account_type, :email_confirmed, :weight
- validates :password, :presence => true,
- :confirmation => true,
- :length => { :within => 6..40 }
- before_save :encrypt_password
- def has_password?(submitted_password)
- encrypted_password == encrypt(submitted_password)
- end
- def self.authenticate(email, submitted_password)
- user = find_by_email(email)
- return nil if user.nil?
- return user if user.has_password?(submitted_password)
- end
- def self.authenticate_with_salt(id, cookie_salt)
- user = find_by_id(id)
- (user && user.salt == cookie_salt) ? user : nil
- end
- private #################################################
- def encrypt_password
- self.salt = make_salt if new_record?
- self.encrypted_password = encrypt(password)
- end
- def encrypt(string)
- secure_hash("#{salt}--#{string}")
- end
- def make_salt
- secure_hash("#{Time.now.utc}--#{password}")
- end
- def secure_hash(string)
- Digest::SHA2.hexdigest(string)
- end
- def generate_email_conf_code
- email_conf_code = secure_hash("#{Time.now.utc}")
- self.email_conf_code = email_conf_code
- end
- end
- Parameters: {"session"=>{"email"=>"xxx@yyy.com", "password"=>"[FILTERED]"}}
Add Comment
Please, Sign In to add comment