benjaminhyw
benjaminhyw

Reputation: 15

Rails 5 sessions not persisting

I'm having trouble getting my sessions to persist.

I am able to login/register a user fine, but the session disappears when my user clicks on any link in my application. I read a few other StackOverflows that said I needed protect_from_forgery with: :exception within my ApplicationController, which is there.. and also that I needed <%= csrf_meta_tags %> within my application.html.erb layout, which is also there. So, I'm a little lost.

My sessions_controller.rb:

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(username: params[:session][:username])
    if user && user.authenticate(params[:session][:password])
      #Log the user in and redirect to the user's show page (for now)
      log_in user
      redirect_to user_path(user)
    else
      flash.now[:danger] = 'Invalid username/password combination'
      render 'new'
    end
  end

  def destroy
    logout
  end
end

my sessions_helper.rb:

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Returns the current logged-in user (if there is one).
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  # Returns true if user is successfully logged in.
  def logged_in?
    !current_user.nil?
  end

  # Logs out current user.
  def logout
    session.delete(:user_id)
    @current_user = nil
  end
end

my application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper
end

and finally, my application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>RailsOnlineShop</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
  <% if logged_in?%>
    <%= link_to "HOME", items_path %> | <%= link_to "PROFILE", current_user %> | <%= link_to "LOGOUT", logout %>
  <% else %>
    <%= link_to "HOME", items_path %> | <%= link_to "REGISTER", new_user_path %> | <%= link_to "LOGIN", login_path %>
  <% end %>
    <%= yield %>
  </body>
</html>

I feel like I've checked everywhere that makes sense, but I could be missing something.

Upvotes: 0

Views: 1411

Answers (1)

benjaminhyw
benjaminhyw

Reputation: 15

I found out what my problem was. In my application.html.erb, my logout link was incorrect and was forcing my user to logout immediately after logging them in.

I had <%= link_to "LOGOUT", logout %> when it should've been <%= link_to "LOGOUT", logout_path, method: :delete %>.

Upvotes: 1

Related Questions