Login/signup function not working, @current_user not working, sessions not working





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-2















I'm new to Rails, and am working on a practice app that involves a simple login function. I've been following a tutorial from CodeAcademy by the books, however the code is not working in quite a few ways. First of all, the sessions do not set, even though Rails is executing the rest of the code inside the "if" block shared with the session declaration (btw, no errors are returned).



The session controller:



class SessionsController < ApplicationController
def new

end

def create
@user = User.find_by_username(params[:session][:name])
if @user && @user.authenticate(params[:session][:password])
session[:user_id] = @user.id
redirect_to '/posts'
else
session[:user_id] = nil
flash[:warning] = "Failed login- try again"
redirect_to '/login'
end
end

def destroy
session[:session_id] = nil
redirect_to login_path
end
end


Extrapolating from that issue, my "current_user" function is not working, which is most likely because the session is not being set.



The application controller:



class ApplicationController < ActionController::Base
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end

def require_user
redirect_to '/login' unless current_user
end

end


Any help is much appreciated. Let me know if you need to see anything else.



NOTE: I know I should use Devise, and I am planning to in my future, more serious projects. However, like I said, this is a practice/test app to help develop my coding skills, and before using a "magical" gem like Devise I want to get hands-on experience with making a login system myself.










share|improve this question

























  • @moveson Tried that, still doesn't work

    – yhtr
    Jan 4 at 3:01











  • Setting it to session[:user_id]

    – yhtr
    Jan 4 at 3:07











  • Will do........

    – yhtr
    Jan 4 at 3:17











  • At what point do you call the current_user method?

    – moveson
    Jan 4 at 4:32











  • I can post the view

    – yhtr
    Jan 4 at 4:44


















-2















I'm new to Rails, and am working on a practice app that involves a simple login function. I've been following a tutorial from CodeAcademy by the books, however the code is not working in quite a few ways. First of all, the sessions do not set, even though Rails is executing the rest of the code inside the "if" block shared with the session declaration (btw, no errors are returned).



The session controller:



class SessionsController < ApplicationController
def new

end

def create
@user = User.find_by_username(params[:session][:name])
if @user && @user.authenticate(params[:session][:password])
session[:user_id] = @user.id
redirect_to '/posts'
else
session[:user_id] = nil
flash[:warning] = "Failed login- try again"
redirect_to '/login'
end
end

def destroy
session[:session_id] = nil
redirect_to login_path
end
end


Extrapolating from that issue, my "current_user" function is not working, which is most likely because the session is not being set.



The application controller:



class ApplicationController < ActionController::Base
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end

def require_user
redirect_to '/login' unless current_user
end

end


Any help is much appreciated. Let me know if you need to see anything else.



NOTE: I know I should use Devise, and I am planning to in my future, more serious projects. However, like I said, this is a practice/test app to help develop my coding skills, and before using a "magical" gem like Devise I want to get hands-on experience with making a login system myself.










share|improve this question

























  • @moveson Tried that, still doesn't work

    – yhtr
    Jan 4 at 3:01











  • Setting it to session[:user_id]

    – yhtr
    Jan 4 at 3:07











  • Will do........

    – yhtr
    Jan 4 at 3:17











  • At what point do you call the current_user method?

    – moveson
    Jan 4 at 4:32











  • I can post the view

    – yhtr
    Jan 4 at 4:44














-2












-2








-2








I'm new to Rails, and am working on a practice app that involves a simple login function. I've been following a tutorial from CodeAcademy by the books, however the code is not working in quite a few ways. First of all, the sessions do not set, even though Rails is executing the rest of the code inside the "if" block shared with the session declaration (btw, no errors are returned).



The session controller:



class SessionsController < ApplicationController
def new

end

def create
@user = User.find_by_username(params[:session][:name])
if @user && @user.authenticate(params[:session][:password])
session[:user_id] = @user.id
redirect_to '/posts'
else
session[:user_id] = nil
flash[:warning] = "Failed login- try again"
redirect_to '/login'
end
end

def destroy
session[:session_id] = nil
redirect_to login_path
end
end


Extrapolating from that issue, my "current_user" function is not working, which is most likely because the session is not being set.



The application controller:



class ApplicationController < ActionController::Base
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end

def require_user
redirect_to '/login' unless current_user
end

end


Any help is much appreciated. Let me know if you need to see anything else.



NOTE: I know I should use Devise, and I am planning to in my future, more serious projects. However, like I said, this is a practice/test app to help develop my coding skills, and before using a "magical" gem like Devise I want to get hands-on experience with making a login system myself.










share|improve this question
















I'm new to Rails, and am working on a practice app that involves a simple login function. I've been following a tutorial from CodeAcademy by the books, however the code is not working in quite a few ways. First of all, the sessions do not set, even though Rails is executing the rest of the code inside the "if" block shared with the session declaration (btw, no errors are returned).



The session controller:



class SessionsController < ApplicationController
def new

end

def create
@user = User.find_by_username(params[:session][:name])
if @user && @user.authenticate(params[:session][:password])
session[:user_id] = @user.id
redirect_to '/posts'
else
session[:user_id] = nil
flash[:warning] = "Failed login- try again"
redirect_to '/login'
end
end

def destroy
session[:session_id] = nil
redirect_to login_path
end
end


Extrapolating from that issue, my "current_user" function is not working, which is most likely because the session is not being set.



The application controller:



class ApplicationController < ActionController::Base
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end

def require_user
redirect_to '/login' unless current_user
end

end


Any help is much appreciated. Let me know if you need to see anything else.



NOTE: I know I should use Devise, and I am planning to in my future, more serious projects. However, like I said, this is a practice/test app to help develop my coding skills, and before using a "magical" gem like Devise I want to get hands-on experience with making a login system myself.







ruby-on-rails ruby session login session-cookies






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 3:17







yhtr

















asked Jan 4 at 2:30









yhtryhtr

63




63













  • @moveson Tried that, still doesn't work

    – yhtr
    Jan 4 at 3:01











  • Setting it to session[:user_id]

    – yhtr
    Jan 4 at 3:07











  • Will do........

    – yhtr
    Jan 4 at 3:17











  • At what point do you call the current_user method?

    – moveson
    Jan 4 at 4:32











  • I can post the view

    – yhtr
    Jan 4 at 4:44



















  • @moveson Tried that, still doesn't work

    – yhtr
    Jan 4 at 3:01











  • Setting it to session[:user_id]

    – yhtr
    Jan 4 at 3:07











  • Will do........

    – yhtr
    Jan 4 at 3:17











  • At what point do you call the current_user method?

    – moveson
    Jan 4 at 4:32











  • I can post the view

    – yhtr
    Jan 4 at 4:44

















@moveson Tried that, still doesn't work

– yhtr
Jan 4 at 3:01





@moveson Tried that, still doesn't work

– yhtr
Jan 4 at 3:01













Setting it to session[:user_id]

– yhtr
Jan 4 at 3:07





Setting it to session[:user_id]

– yhtr
Jan 4 at 3:07













Will do........

– yhtr
Jan 4 at 3:17





Will do........

– yhtr
Jan 4 at 3:17













At what point do you call the current_user method?

– moveson
Jan 4 at 4:32





At what point do you call the current_user method?

– moveson
Jan 4 at 4:32













I can post the view

– yhtr
Jan 4 at 4:44





I can post the view

– yhtr
Jan 4 at 4:44












2 Answers
2






active

oldest

votes


















0














I think the error is that session_controller is not able to find the current_user.



Write the following code in application_controller:



class ApplicationController < ActionController::Base

helper_method :current_user

def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end

def require_user
redirect_to '/login' unless current_user
end

end


Letme know if it works






share|improve this answer































    0














    There are a few possible problems.



    First, @current_user is not set until the current_user method is called. And as @Neha pointed out, you'll need to add a helper method to your ApplicationController so that all your views will have access to the current_user method. Add this line to your ApplicationController:



    helper_method :current_user


    Now, to diagnose the problem, let's set something up that lets you get some visibility into your session and current_user.



    First, in views/layouts/application.html.erb, just after the line that says <= yield %>, add this:



    <%= render 'layouts/footer' %>


    Then add a new file views/layouts/_footer.html.erb:



    <hr/>
    Session:<br/>
    <% session.keys.each do |key| %>
    <%= "#{key}: #{session[key]}" %><br/>
    <% end %>
    <br/>
    User:<br/>
    <%= current_user&.username || '[None]' %>


    Now at the bottom of every view you can see the details of your session.



    In your sessions#create action, you have a potential problem with finding your User. You are using params[:session][:name] where you probably should be using params[:session][:username].



    Also, tangentially, the proper way to destroy a session is not by setting session[:id] to nil, but instead to use reset_session. So your SessionsController should look like this:



    class SessionsController < ApplicationController
    def new
    end

    def create
    @user = User.find_by_username(params[:session][:username])
    if @user && @user.authenticate(params[:session][:password])
    session[:user_id] = @user.id
    redirect_to '/posts'
    else
    session[:user_id] = nil
    flash[:warning] = "Failed login- try again"
    redirect_to '/login'
    end
    end

    def destroy
    reset_session
    redirect_to login_path
    end
    end





    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54032439%2flogin-signup-function-not-working-current-user-not-working-sessions-not-worki%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      I think the error is that session_controller is not able to find the current_user.



      Write the following code in application_controller:



      class ApplicationController < ActionController::Base

      helper_method :current_user

      def current_user
      return unless session[:user_id]
      @current_user ||= User.find(session[:user_id])
      end

      def require_user
      redirect_to '/login' unless current_user
      end

      end


      Letme know if it works






      share|improve this answer




























        0














        I think the error is that session_controller is not able to find the current_user.



        Write the following code in application_controller:



        class ApplicationController < ActionController::Base

        helper_method :current_user

        def current_user
        return unless session[:user_id]
        @current_user ||= User.find(session[:user_id])
        end

        def require_user
        redirect_to '/login' unless current_user
        end

        end


        Letme know if it works






        share|improve this answer


























          0












          0








          0







          I think the error is that session_controller is not able to find the current_user.



          Write the following code in application_controller:



          class ApplicationController < ActionController::Base

          helper_method :current_user

          def current_user
          return unless session[:user_id]
          @current_user ||= User.find(session[:user_id])
          end

          def require_user
          redirect_to '/login' unless current_user
          end

          end


          Letme know if it works






          share|improve this answer













          I think the error is that session_controller is not able to find the current_user.



          Write the following code in application_controller:



          class ApplicationController < ActionController::Base

          helper_method :current_user

          def current_user
          return unless session[:user_id]
          @current_user ||= User.find(session[:user_id])
          end

          def require_user
          redirect_to '/login' unless current_user
          end

          end


          Letme know if it works







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 4 at 5:41









          MoriartyMoriarty

          507




          507

























              0














              There are a few possible problems.



              First, @current_user is not set until the current_user method is called. And as @Neha pointed out, you'll need to add a helper method to your ApplicationController so that all your views will have access to the current_user method. Add this line to your ApplicationController:



              helper_method :current_user


              Now, to diagnose the problem, let's set something up that lets you get some visibility into your session and current_user.



              First, in views/layouts/application.html.erb, just after the line that says <= yield %>, add this:



              <%= render 'layouts/footer' %>


              Then add a new file views/layouts/_footer.html.erb:



              <hr/>
              Session:<br/>
              <% session.keys.each do |key| %>
              <%= "#{key}: #{session[key]}" %><br/>
              <% end %>
              <br/>
              User:<br/>
              <%= current_user&.username || '[None]' %>


              Now at the bottom of every view you can see the details of your session.



              In your sessions#create action, you have a potential problem with finding your User. You are using params[:session][:name] where you probably should be using params[:session][:username].



              Also, tangentially, the proper way to destroy a session is not by setting session[:id] to nil, but instead to use reset_session. So your SessionsController should look like this:



              class SessionsController < ApplicationController
              def new
              end

              def create
              @user = User.find_by_username(params[:session][:username])
              if @user && @user.authenticate(params[:session][:password])
              session[:user_id] = @user.id
              redirect_to '/posts'
              else
              session[:user_id] = nil
              flash[:warning] = "Failed login- try again"
              redirect_to '/login'
              end
              end

              def destroy
              reset_session
              redirect_to login_path
              end
              end





              share|improve this answer




























                0














                There are a few possible problems.



                First, @current_user is not set until the current_user method is called. And as @Neha pointed out, you'll need to add a helper method to your ApplicationController so that all your views will have access to the current_user method. Add this line to your ApplicationController:



                helper_method :current_user


                Now, to diagnose the problem, let's set something up that lets you get some visibility into your session and current_user.



                First, in views/layouts/application.html.erb, just after the line that says <= yield %>, add this:



                <%= render 'layouts/footer' %>


                Then add a new file views/layouts/_footer.html.erb:



                <hr/>
                Session:<br/>
                <% session.keys.each do |key| %>
                <%= "#{key}: #{session[key]}" %><br/>
                <% end %>
                <br/>
                User:<br/>
                <%= current_user&.username || '[None]' %>


                Now at the bottom of every view you can see the details of your session.



                In your sessions#create action, you have a potential problem with finding your User. You are using params[:session][:name] where you probably should be using params[:session][:username].



                Also, tangentially, the proper way to destroy a session is not by setting session[:id] to nil, but instead to use reset_session. So your SessionsController should look like this:



                class SessionsController < ApplicationController
                def new
                end

                def create
                @user = User.find_by_username(params[:session][:username])
                if @user && @user.authenticate(params[:session][:password])
                session[:user_id] = @user.id
                redirect_to '/posts'
                else
                session[:user_id] = nil
                flash[:warning] = "Failed login- try again"
                redirect_to '/login'
                end
                end

                def destroy
                reset_session
                redirect_to login_path
                end
                end





                share|improve this answer


























                  0












                  0








                  0







                  There are a few possible problems.



                  First, @current_user is not set until the current_user method is called. And as @Neha pointed out, you'll need to add a helper method to your ApplicationController so that all your views will have access to the current_user method. Add this line to your ApplicationController:



                  helper_method :current_user


                  Now, to diagnose the problem, let's set something up that lets you get some visibility into your session and current_user.



                  First, in views/layouts/application.html.erb, just after the line that says <= yield %>, add this:



                  <%= render 'layouts/footer' %>


                  Then add a new file views/layouts/_footer.html.erb:



                  <hr/>
                  Session:<br/>
                  <% session.keys.each do |key| %>
                  <%= "#{key}: #{session[key]}" %><br/>
                  <% end %>
                  <br/>
                  User:<br/>
                  <%= current_user&.username || '[None]' %>


                  Now at the bottom of every view you can see the details of your session.



                  In your sessions#create action, you have a potential problem with finding your User. You are using params[:session][:name] where you probably should be using params[:session][:username].



                  Also, tangentially, the proper way to destroy a session is not by setting session[:id] to nil, but instead to use reset_session. So your SessionsController should look like this:



                  class SessionsController < ApplicationController
                  def new
                  end

                  def create
                  @user = User.find_by_username(params[:session][:username])
                  if @user && @user.authenticate(params[:session][:password])
                  session[:user_id] = @user.id
                  redirect_to '/posts'
                  else
                  session[:user_id] = nil
                  flash[:warning] = "Failed login- try again"
                  redirect_to '/login'
                  end
                  end

                  def destroy
                  reset_session
                  redirect_to login_path
                  end
                  end





                  share|improve this answer













                  There are a few possible problems.



                  First, @current_user is not set until the current_user method is called. And as @Neha pointed out, you'll need to add a helper method to your ApplicationController so that all your views will have access to the current_user method. Add this line to your ApplicationController:



                  helper_method :current_user


                  Now, to diagnose the problem, let's set something up that lets you get some visibility into your session and current_user.



                  First, in views/layouts/application.html.erb, just after the line that says <= yield %>, add this:



                  <%= render 'layouts/footer' %>


                  Then add a new file views/layouts/_footer.html.erb:



                  <hr/>
                  Session:<br/>
                  <% session.keys.each do |key| %>
                  <%= "#{key}: #{session[key]}" %><br/>
                  <% end %>
                  <br/>
                  User:<br/>
                  <%= current_user&.username || '[None]' %>


                  Now at the bottom of every view you can see the details of your session.



                  In your sessions#create action, you have a potential problem with finding your User. You are using params[:session][:name] where you probably should be using params[:session][:username].



                  Also, tangentially, the proper way to destroy a session is not by setting session[:id] to nil, but instead to use reset_session. So your SessionsController should look like this:



                  class SessionsController < ApplicationController
                  def new
                  end

                  def create
                  @user = User.find_by_username(params[:session][:username])
                  if @user && @user.authenticate(params[:session][:password])
                  session[:user_id] = @user.id
                  redirect_to '/posts'
                  else
                  session[:user_id] = nil
                  flash[:warning] = "Failed login- try again"
                  redirect_to '/login'
                  end
                  end

                  def destroy
                  reset_session
                  redirect_to login_path
                  end
                  end






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 4 at 6:57









                  movesonmoveson

                  3,8121630




                  3,8121630






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54032439%2flogin-signup-function-not-working-current-user-not-working-sessions-not-worki%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Mossoró

                      Error while reading .h5 file using the rhdf5 package in R

                      Pushsharp Apns notification error: 'InvalidToken'