ToddT
ToddT

Reputation: 3258

Rails Session not persisting after browser refresh

Navigating within the app and re-directs are all fine, its just when the browser refreshes the user has to log back in. I only want the session to expire when the browser closes and not on refresh..

My session_store.rb

Rails.application.config.session_store :cookie_store, key:
'_workspace_session'

My sessions controller new and create actions:

def new

end


def create
    merchant = Merchant.find_by(email: params[:email])

    if merchant && merchant.authenticate(params[:password])
        session[:merchant_id] = merchant.id
        log_in(merchant)
        flash[:success] = "You were logged in successfully"
        redirect_to merchant_path(merchant.id)
    else
        flash.now[:danger] = "Snap! either your email or password is 
        incorrect. Try again"
        render 'new'
    end

end

Upvotes: 1

Views: 1439

Answers (1)

Hristo Georgiev
Hristo Georgiev

Reputation: 2519

It's probably because you don't have a sessions helper that adds a cookie of the logged in merchant's credentials and checks them every time you reload the page: First, add your sessions_helper.rb to your main controller:

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

Here is your sessions helper:

 module SessionsHelper

  # Returns the user corresponding to the remember token cookie.
  def current_merchant
    if (merchant_id = session[:merchant_id])
      @current_merchant ||= Merchant.find_by(id: merchant_id)
    elsif (merchant_id = cookies.signed[:merchant_id])
      merchant= Merchant.find_by(id: merchant_id)
      if merchant && merchant.authenticated?(cookies[:remember_token])
        log_in merchant
        @current_user = merchant
      end
    end
  end

 #logs the merchant in.I don't know what your log_in method does there in the    question, if it does the same, you are doing it two times.

 def log_in(merchant)
    session[:merchant_id] = merchant.id
 end


end

Adapted from RailsTutorial <- I'd recommend you read this. A lot of great stuff in there.

Upvotes: 1

Related Questions