Challenges 45.1 Solution Found


#1



To redirect the a logged in user to the articles when they attempt to type in the login/signup url I have found a simple solution

application-controller

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  helper_method :current_user
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  def require_user 
    redirect_to '/login' unless current_user 
  end
  **def loggedin_user**
**    redirect_to '/' if current_user**
**  end**
end

users-controller

class UsersController < ApplicationController  
  **before_action :loggedin_user**
  def new
    @user = User.new
  end
  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      redirect_to '/'
    else
      redirect_to '/signup'
    end
  end
  
  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password)
  end
end

sessions-controller

class SessionsController < ApplicationController
  **before_action :loggedin_user, except: [:destroy]**
  def new

  end
  def create
    @user = User.find_by_email(params[:session][:email])
    if @user && @user.authenticate(params[:session][:password])
      session[:user_id] = @user.id
      redirect_to '/'
    else
      redirect_to 'login'
    end 
  end
  def destroy
    session[:user_id] = nil
    redirect_to "/"
  end
end

The except: [:destroy] in the sessions-controller is necessary, without it the logout function won't work.


#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.