How to not allow access if not logged in?

How to allow access only to logged in users restricting direct entry of url?

  • in a Rubyonrails application i want only logged in users to enterinto the inner pages? how can i redirect the direct entered urls to index page? in php if(!isset($_SESSION[id]) { header("location:index.php") }, how this can be implemented in ruby on rails

  • Answer:

    here goes In application_controller.rb: Putting this code in application_controller will make it available to all your controllers. class ApplicationController < ActionController::Base protect_from_forgery protected def confirm_logged_in unless session[:id] flash[:notice] = "Please log in" redirect_to :root return false else return true end end end Then you can make use of this method in any of the controllers that require it, for eg If you need to confirm that users are logged in for the show action, then class UsersController < ApplicationController before_filter :confirm_logged_in, :only => [:show] def show #all your code end end should work, as this will confirm that users accessing this show url have logged in. For more info checkout this link to http://guides.rubyonrails.org/action_controller_overview.html#filters. There could be more efficient ways of achieving this as well. However, i would suggest using a gem like http://railscasts.com/episodes/192-authorization-with-cancan (https://github.com/ryanb/cancan) as i have used this in many apps and works well. The code presented above is basic and there are many better and advanced ways to handle this but it should do the job.Hope it helps.

SHANib at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.