Reputation: 33
I am going through the second tutorial in the No Nonsense Guide To Rails and after setting up user authentication (manually without Devise), I keep getting a redirect loop error once I had successfully logged in and out (started after hitting log out). Now I can't get any page on LocalHost to load anymore. Here is the Application Controller, Sessions Controller, and my routes.rb code:
Rails.application.routes.draw do
resources :comments
resources :image_posts
resources :text_posts
resources :posts
resources :users
get 'signup', to: 'users#new', as: 'signup'
get 'login', to: 'sessions#new', as: 'login'
post 'login', to: 'sessions#create'
get 'logout', to: 'sessions#destroy', as: 'logout'
root 'posts#index'
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, notice: "Log in Successful!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Log out successful!"
end
end
application_controller.rb
class ApplicationController < ActionController::Base
before_action :authenticate_user!
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def current_user
if session[:user_id]
@current_user ||= User.find(session[:user_id])
end
end
helper_method :current_user
def authenticate_user!
redirect_to login_path unless current_user
end
Thanks for reading!
Upvotes: 0
Views: 274
Reputation: 3542
Looks like you auth user even on login_path
page...
Try
class SessionsController < ApplicationController
skip_before_action :authenticate_user!
#...
end
Upvotes: 1