如何仅允许访问限制直接输入 url 的登录用户? [英] How to allow access only to logged in users restricting direct entry of url?

查看:56
本文介绍了如何仅允许访问限制直接输入 url 的登录用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rubyonrails 应用程序中,我只想登录用户进入内页?如何将直接输入的网址重定向到索引页?

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?

在 php if(!isset($_SESSION[id]) { header("location:index.php") } 中,如何在 ruby​​ on rails 中实现这一点

in php if(!isset($_SESSION[id]) { header("location:index.php") }, how this can be implemented in ruby on rails

推荐答案

这里

在 application_controller.rb 中:

将此代码放入 application_controller 将使其可用于您的所有控制器.

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

然后你可以在任何需要它的控制器中使用这个方法,例如

如果您需要确认用户已登录以进行显示操作,则

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.

但是,我建议使用像 Cancan (Cancan="https://github.com/ryanb/cancan" rel="nofollow">Github),因为我已经在许多应用程序中使用了它并且运行良好.上面提供的代码是基本的,有许多更好和更高级的方法来处理这个问题,但它应该可以完成工作.希望它有所帮助.

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.

这篇关于如何仅允许访问限制直接输入 url 的登录用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆