[英]How to create `authenticate_user' method without devise in ror
我是Ruby on Rails的新手,正在使用Ruby 1.9.3版和Rails 4.0.2版。
我的查询是:-
如何在Ruby on Rails中无需设计就创建“ authenticate_user”方法。
在我的路线下方
get "admin/users/sign_in" => "admin/users#sign_in"
在我的应用程序控制器下面:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
rescue_from CanCan::AccessDenied do |exception|
flash[:alert] = "Access denied. You are not authorized to access the requested page."
redirect_to root_path and return
end
helper_method :current_user
before_filter :authenticate_user, :current_user
def current_user
# Note: we want to use "find_by_id" because it's OK to return a nil.
# If we were to use User.find, it would throw an exception if the user can't be found.
@current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]
@current_user ||= User.find_by_authentication_token(cookies[:auth_token]) if cookies[:auth_token] && @current_user.nil?
@current_user
end
def authenticate_user
if @current_user.nil?
flash[:error] = 'You must be signed in to view that page.'
redirect_to :admin_users_sign_in
end
end
protected
#derive the model name from the controller. egs UsersController will return User
def self.permission
return name = self.name.gsub('Controller','').singularize.split('::').last.constantize.name rescue nil
end
def current_ability
@current_ability ||= Ability.new(current_user)
end
#load the permissions for the current user so that UI can be manipulated
def load_permissions
@current_permissions = current_user.role.permissions.collect{|i| [i.subject_class, i.action]}
end
end
下面的代码使用我的控制器
before_filter :authenticate_user!
我的authenticate_user方法未正确重定向
redirect_to:admin_users_sign_in
admin_users_sign_in路径中的路径定义参见顶部
每次在浏览器上方的代码上方说“页面未正确重定向”
请帮忙
我怀疑问题是由于以下原因造成的:
redirect_to :admin_users_sign_in
您需要将action
和controller
或路径的友好名称传递给redirect_to
。
将路线更改为类似
get "admin/users/sign_in" => "admin/users#sign_in", :as => :admin_user_signin
然后你可以做类似的事情
redirect_to admin_user_signin_path
这看起来是一个无限循环。
您在ApplicationController级别定义了authenticate_user
。 因此,当访问者访问页面'foo'时,此方法将拒绝他,因为current_user为nil。 然后,他被重定向到管理员登录页面,但是该页面也具有before_filter,因此他再次被重定向到同一页面,并且永无休止。
要解决此问题,请将此类过滤器移至需要保护的特定控制器。 并且不要在登录/注册页面中进行设置。
旁注:
您已经使用过CanCan,它也具有“读取”权限。 没有必要再次使用authenticate_user
来实现相同的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.