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

£可爱£侵袭症+ 提交于 2019-12-25 06:46:07

问题


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


回答1:


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 rails guides on filters. There could be more efficient ways of achieving this as well.

However, i would suggest using a gem like Cancan (Github) 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.



来源:https://stackoverflow.com/questions/8500350/how-to-allow-access-only-to-logged-in-users-restricting-direct-entry-of-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!