Rails Active Record Query (testing user logged into a given session)

134 views Asked by At

Apologies, but I have been a little stuck on what I believe to be an easy fix. I am building a rails app and simply want to test if the user currently logged into my app has the name 'Tom'. I have a user named Tom and when I log in with him I get redirected to the new_thing_url, indicating that the session name is not Tom.

I have tried user.name="Tom" as well and it doesnt seem to work.

Also, I am using Bcrypt for authentication

My create session method in the sessions_controller.rb

          def create
      user=User.find_by(name: session[:name])
      if session[:name] == 'Tom' and user.try(:authenticate,(params[:password]))
        session[:user_id] = user.id
        session[:name] = user.name
        redirect_to admin_url  
      else if user and user.authenticate(params[:password])
      redirect_to new_thing_url
      else
      redirect_to login_url, alert: "Invalid user/password combo"
      end 
      end

      end


\

<% if flash[:alert] %>

<p id="notice"><%= flash[:alert] %></p> 
<% end %>
<%= form_tag do %>
<fieldset>
<legend>Please Log In</legend> <div>
<%= label_tag :name, 'Name:' %>
        <%= text_field_tag :name, params[:name] %>
</div>
        <div>
        <%= label_tag :password, 'Password:' %>
        <%= password_field_tag :password, params[:password] %>
</div> <div>
<%= submit_tag "Login" %> </div>
</fieldset> 
<% end %>
1

There are 1 answers

0
jb_314 On BEST ANSWER

At this point:

user=User.find_by(name: session[:name])
if session[:name] == 'Tom' and user.try(:authenticate,(params[:password]))

You have not set session[:name] yet. You probably want:

user=User.find_by(name: params[:name])
if params[:name] == 'Tom' and user.try(:authenticate,(params[:password]))