简体   繁体   English

要求用户登录(Rails)

[英]Require a user to be logged in (Rails)

How do I guarantee that users only access the routes on my web app if they are logged in? 如何确保用户仅在登录后才能访问我的Web应用程序上的路由? I already have Users and Session models and users are able to create accounts. 我已经有用户和会话模型,并且用户能够创建帐户。 But how do I make sure that if they are not logged in they are always redirected to the login/sign up page, but if they are they have access to all the routes? 但是,如何确保如果未登录,则始终将它们重定向到登录/注册页面,但是如果可以,则可以访问所有路由?

EDIT: So this is what my Application Controller looks like right now: 编辑:所以这就是我的应用程序控制器现在的样子:

class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception
    helper_method :current_user

    private

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

So if there isn't a current user, I want to allow access only to the my Pages controller and its actions (which are basically home, signup, login, etc.). 因此,如果没有当前用户,我只希望允许访问我的Pages控制器及其操作(基本上是主页,注册,登录等)。 If there is a user, on the other hand, I want that user to be able to access all the routes in my route file. 另一方面,如果有用户,我希望该用户能够访问我的路由文件中的所有路由。

class SomeController < ApplicationController
  def show
    if current_user.nil?
      redirect_to '/path/to/login'
    end
  end
end

could probably give a more detailed answer if you paste in some code otherwise we all are just guess what your methods are called. 如果您粘贴一些代码,可能会给出更详细的答案,否则我们都只能猜测您的方法被调用了。

If you are using devise it comes with the built in helper method authenticate_user! 如果您使用的是devise,则它带有内置的辅助方法authenticate_user! which should be placed in your application controller. 应该放在您的应用程序控制器中。

If you are not using devise you can define you own method (for this example I will copy devise) authenticate_user! 如果您不使用devise,则可以定义自己的方法(在本例中,我将复制devise) authenticate_user! in application controller and call the before action 在应用程序控制器中并调用before动作

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

    private
    def authenticate_user!
    redirect_to :root if current_user.nil?
    end

   end 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM