Search code examples
formsauthenticationruby-on-rails-5

Authenticate users when login


I'm a beginner and I'm doing a Rails Tuturial https://www.learnenough.com/ruby-on-rails-6th-edition-tutorial/basic_login#sec-finding_and_authenticating_a_user>

Last lesson i create a new user and I'm verifying in the rails``console using booleans to prove if users email and password match to login session.

This is my code in the session controller file:

class SessionsController < ApplicationController

  def new
  end

  def create
     user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
    else
      render 'new'
    end
  end

  def destroy
  end
end

And to verify in the rails console:

user = User.first
=> User id: 1, name: "Rails Tutorial", email: "[email protected]", created_at: "2020-02-13 01:04:12", updated_at: "2020-02-13 01:04:12", password_digest: [FILTERED]

!!(user && user.authenticate('railst1234'))
=> false

The question here is why returns FALSE if the email and password info. suppose to be right?


Solution

  • I think that's because you are trying to authenticate an encrypted password but creating without given password_confirmation to user model. Here is a good link for understanding passwords on user.

    This could also help you if you don't want encrypted passwords for user.