How to restrict access to different pages in Rails?












0














I have controller Users:



class UsersController < ApplicationController
......
def show
@user = User.find(params[:id])
end

def index
@users = User.paginate(page: params[:page], per_page: 25)
end
......
end


Now users profiles are at /users/1, /users/2, etc. and list of users is at /users/.



I want to give special access:




  • user can see only own profile

  • admin can see the list of users and any profile


How can I restrict access this way?










share|improve this question
























  • There are many, many ways this could be done. There are libraries that do it, you could spin a drop-dead simple approach (hint: all you need to do is check the role of the current user and show the appropriate page). There are many tutorials that cover both rolling your own and using libraries. As worded now the question is quite broad.
    – Dave Newton
    Nov 22 at 20:12












  • you can use cancan or rolify and combine it with devise's current_user method. If the user is admin then allow him otherwise check whether the id of the profile he is visiting is equal to current_user.id else throw him to default page.
    – Gagan Gupta
    Nov 23 at 7:46


















0














I have controller Users:



class UsersController < ApplicationController
......
def show
@user = User.find(params[:id])
end

def index
@users = User.paginate(page: params[:page], per_page: 25)
end
......
end


Now users profiles are at /users/1, /users/2, etc. and list of users is at /users/.



I want to give special access:




  • user can see only own profile

  • admin can see the list of users and any profile


How can I restrict access this way?










share|improve this question
























  • There are many, many ways this could be done. There are libraries that do it, you could spin a drop-dead simple approach (hint: all you need to do is check the role of the current user and show the appropriate page). There are many tutorials that cover both rolling your own and using libraries. As worded now the question is quite broad.
    – Dave Newton
    Nov 22 at 20:12












  • you can use cancan or rolify and combine it with devise's current_user method. If the user is admin then allow him otherwise check whether the id of the profile he is visiting is equal to current_user.id else throw him to default page.
    – Gagan Gupta
    Nov 23 at 7:46
















0












0








0







I have controller Users:



class UsersController < ApplicationController
......
def show
@user = User.find(params[:id])
end

def index
@users = User.paginate(page: params[:page], per_page: 25)
end
......
end


Now users profiles are at /users/1, /users/2, etc. and list of users is at /users/.



I want to give special access:




  • user can see only own profile

  • admin can see the list of users and any profile


How can I restrict access this way?










share|improve this question















I have controller Users:



class UsersController < ApplicationController
......
def show
@user = User.find(params[:id])
end

def index
@users = User.paginate(page: params[:page], per_page: 25)
end
......
end


Now users profiles are at /users/1, /users/2, etc. and list of users is at /users/.



I want to give special access:




  • user can see only own profile

  • admin can see the list of users and any profile


How can I restrict access this way?







ruby-on-rails






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 20:02

























asked Nov 22 at 19:55









mechnicov

4119




4119












  • There are many, many ways this could be done. There are libraries that do it, you could spin a drop-dead simple approach (hint: all you need to do is check the role of the current user and show the appropriate page). There are many tutorials that cover both rolling your own and using libraries. As worded now the question is quite broad.
    – Dave Newton
    Nov 22 at 20:12












  • you can use cancan or rolify and combine it with devise's current_user method. If the user is admin then allow him otherwise check whether the id of the profile he is visiting is equal to current_user.id else throw him to default page.
    – Gagan Gupta
    Nov 23 at 7:46




















  • There are many, many ways this could be done. There are libraries that do it, you could spin a drop-dead simple approach (hint: all you need to do is check the role of the current user and show the appropriate page). There are many tutorials that cover both rolling your own and using libraries. As worded now the question is quite broad.
    – Dave Newton
    Nov 22 at 20:12












  • you can use cancan or rolify and combine it with devise's current_user method. If the user is admin then allow him otherwise check whether the id of the profile he is visiting is equal to current_user.id else throw him to default page.
    – Gagan Gupta
    Nov 23 at 7:46


















There are many, many ways this could be done. There are libraries that do it, you could spin a drop-dead simple approach (hint: all you need to do is check the role of the current user and show the appropriate page). There are many tutorials that cover both rolling your own and using libraries. As worded now the question is quite broad.
– Dave Newton
Nov 22 at 20:12






There are many, many ways this could be done. There are libraries that do it, you could spin a drop-dead simple approach (hint: all you need to do is check the role of the current user and show the appropriate page). There are many tutorials that cover both rolling your own and using libraries. As worded now the question is quite broad.
– Dave Newton
Nov 22 at 20:12














you can use cancan or rolify and combine it with devise's current_user method. If the user is admin then allow him otherwise check whether the id of the profile he is visiting is equal to current_user.id else throw him to default page.
– Gagan Gupta
Nov 23 at 7:46






you can use cancan or rolify and combine it with devise's current_user method. If the user is admin then allow him otherwise check whether the id of the profile he is visiting is equal to current_user.id else throw him to default page.
– Gagan Gupta
Nov 23 at 7:46














4 Answers
4






active

oldest

votes


















0














Assuming you have a current_user defined and your User class has an admin attribute you can do the following:



class UsersController < ApplicationController
......
def show
@user = User.find(params[:id])
if current_user.admin || @user == current_user
# render the show screen
else
# redirect to wherever
end
end

def index
if current_user.admin
@users = User.paginate(page: params[:page], per_page: 25)
# render the index screen
else
# redirect to wherever
end

end
......
end


Or you could just use one of the plenty of authorization gems out there, like cancancan or pundit.






share|improve this answer





























    0














    You should use ACL libraries like cancancan or pundit or from ruby-toolbox.com






    share|improve this answer





























      0














      I would probably handle this by having two different endpoints, something like /profile and /admin/users/1. Then you have different controllers for them:



      UserProfileController < ApplicationController
      def show
      @user = current_user
      end
      end


      and:



      class Admin::UsersController < AdminController
      def show
      @user = User.find(params[:id])
      render 'user_profile/show' # or another template if you like
      end
      end

      class AdminController < ApplicationController
      before_action :ensure_admin

      def ensure_admin
      if !current_user.admin?
      raise ActionController::RoutingError, 'Not Found'
      end
      end
      end





      share|improve this answer





























        0














        Considering your url user/1/ you grab the param id and compare it to the current user ID in a hook :



        before_action :auth_user

        private

        def auth_user
        unless params[:id].to_s == current_user.id.to_s
        redirect_to root_path
        end


        Regarding the admin you probably have a dedicated namespace, with even more thorough checks, where you can see user profiles.






        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%2f53437361%2fhow-to-restrict-access-to-different-pages-in-rails%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Assuming you have a current_user defined and your User class has an admin attribute you can do the following:



          class UsersController < ApplicationController
          ......
          def show
          @user = User.find(params[:id])
          if current_user.admin || @user == current_user
          # render the show screen
          else
          # redirect to wherever
          end
          end

          def index
          if current_user.admin
          @users = User.paginate(page: params[:page], per_page: 25)
          # render the index screen
          else
          # redirect to wherever
          end

          end
          ......
          end


          Or you could just use one of the plenty of authorization gems out there, like cancancan or pundit.






          share|improve this answer


























            0














            Assuming you have a current_user defined and your User class has an admin attribute you can do the following:



            class UsersController < ApplicationController
            ......
            def show
            @user = User.find(params[:id])
            if current_user.admin || @user == current_user
            # render the show screen
            else
            # redirect to wherever
            end
            end

            def index
            if current_user.admin
            @users = User.paginate(page: params[:page], per_page: 25)
            # render the index screen
            else
            # redirect to wherever
            end

            end
            ......
            end


            Or you could just use one of the plenty of authorization gems out there, like cancancan or pundit.






            share|improve this answer
























              0












              0








              0






              Assuming you have a current_user defined and your User class has an admin attribute you can do the following:



              class UsersController < ApplicationController
              ......
              def show
              @user = User.find(params[:id])
              if current_user.admin || @user == current_user
              # render the show screen
              else
              # redirect to wherever
              end
              end

              def index
              if current_user.admin
              @users = User.paginate(page: params[:page], per_page: 25)
              # render the index screen
              else
              # redirect to wherever
              end

              end
              ......
              end


              Or you could just use one of the plenty of authorization gems out there, like cancancan or pundit.






              share|improve this answer












              Assuming you have a current_user defined and your User class has an admin attribute you can do the following:



              class UsersController < ApplicationController
              ......
              def show
              @user = User.find(params[:id])
              if current_user.admin || @user == current_user
              # render the show screen
              else
              # redirect to wherever
              end
              end

              def index
              if current_user.admin
              @users = User.paginate(page: params[:page], per_page: 25)
              # render the index screen
              else
              # redirect to wherever
              end

              end
              ......
              end


              Or you could just use one of the plenty of authorization gems out there, like cancancan or pundit.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 22 at 21:09









              Yechiel K

              398411




              398411

























                  0














                  You should use ACL libraries like cancancan or pundit or from ruby-toolbox.com






                  share|improve this answer


























                    0














                    You should use ACL libraries like cancancan or pundit or from ruby-toolbox.com






                    share|improve this answer
























                      0












                      0








                      0






                      You should use ACL libraries like cancancan or pundit or from ruby-toolbox.com






                      share|improve this answer












                      You should use ACL libraries like cancancan or pundit or from ruby-toolbox.com







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 22 at 20:07









                      Neodelf

                      81112




                      81112























                          0














                          I would probably handle this by having two different endpoints, something like /profile and /admin/users/1. Then you have different controllers for them:



                          UserProfileController < ApplicationController
                          def show
                          @user = current_user
                          end
                          end


                          and:



                          class Admin::UsersController < AdminController
                          def show
                          @user = User.find(params[:id])
                          render 'user_profile/show' # or another template if you like
                          end
                          end

                          class AdminController < ApplicationController
                          before_action :ensure_admin

                          def ensure_admin
                          if !current_user.admin?
                          raise ActionController::RoutingError, 'Not Found'
                          end
                          end
                          end





                          share|improve this answer


























                            0














                            I would probably handle this by having two different endpoints, something like /profile and /admin/users/1. Then you have different controllers for them:



                            UserProfileController < ApplicationController
                            def show
                            @user = current_user
                            end
                            end


                            and:



                            class Admin::UsersController < AdminController
                            def show
                            @user = User.find(params[:id])
                            render 'user_profile/show' # or another template if you like
                            end
                            end

                            class AdminController < ApplicationController
                            before_action :ensure_admin

                            def ensure_admin
                            if !current_user.admin?
                            raise ActionController::RoutingError, 'Not Found'
                            end
                            end
                            end





                            share|improve this answer
























                              0












                              0








                              0






                              I would probably handle this by having two different endpoints, something like /profile and /admin/users/1. Then you have different controllers for them:



                              UserProfileController < ApplicationController
                              def show
                              @user = current_user
                              end
                              end


                              and:



                              class Admin::UsersController < AdminController
                              def show
                              @user = User.find(params[:id])
                              render 'user_profile/show' # or another template if you like
                              end
                              end

                              class AdminController < ApplicationController
                              before_action :ensure_admin

                              def ensure_admin
                              if !current_user.admin?
                              raise ActionController::RoutingError, 'Not Found'
                              end
                              end
                              end





                              share|improve this answer












                              I would probably handle this by having two different endpoints, something like /profile and /admin/users/1. Then you have different controllers for them:



                              UserProfileController < ApplicationController
                              def show
                              @user = current_user
                              end
                              end


                              and:



                              class Admin::UsersController < AdminController
                              def show
                              @user = User.find(params[:id])
                              render 'user_profile/show' # or another template if you like
                              end
                              end

                              class AdminController < ApplicationController
                              before_action :ensure_admin

                              def ensure_admin
                              if !current_user.admin?
                              raise ActionController::RoutingError, 'Not Found'
                              end
                              end
                              end






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 23 at 2:56









                              lobati

                              2,45532140




                              2,45532140























                                  0














                                  Considering your url user/1/ you grab the param id and compare it to the current user ID in a hook :



                                  before_action :auth_user

                                  private

                                  def auth_user
                                  unless params[:id].to_s == current_user.id.to_s
                                  redirect_to root_path
                                  end


                                  Regarding the admin you probably have a dedicated namespace, with even more thorough checks, where you can see user profiles.






                                  share|improve this answer


























                                    0














                                    Considering your url user/1/ you grab the param id and compare it to the current user ID in a hook :



                                    before_action :auth_user

                                    private

                                    def auth_user
                                    unless params[:id].to_s == current_user.id.to_s
                                    redirect_to root_path
                                    end


                                    Regarding the admin you probably have a dedicated namespace, with even more thorough checks, where you can see user profiles.






                                    share|improve this answer
























                                      0












                                      0








                                      0






                                      Considering your url user/1/ you grab the param id and compare it to the current user ID in a hook :



                                      before_action :auth_user

                                      private

                                      def auth_user
                                      unless params[:id].to_s == current_user.id.to_s
                                      redirect_to root_path
                                      end


                                      Regarding the admin you probably have a dedicated namespace, with even more thorough checks, where you can see user profiles.






                                      share|improve this answer












                                      Considering your url user/1/ you grab the param id and compare it to the current user ID in a hook :



                                      before_action :auth_user

                                      private

                                      def auth_user
                                      unless params[:id].to_s == current_user.id.to_s
                                      redirect_to root_path
                                      end


                                      Regarding the admin you probably have a dedicated namespace, with even more thorough checks, where you can see user profiles.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 24 at 2:03









                                      Maxence

                                      6401616




                                      6401616






























                                          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.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • 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%2f53437361%2fhow-to-restrict-access-to-different-pages-in-rails%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

                                          What visual should I use to simply compare current year value vs last year in Power BI desktop

                                          Alexandru Averescu

                                          Trompette piccolo