Ruby on rails Rails只允许在注册后访问两个页面
我遇到了这样一种情况,用户在成功注册过程(我使用的是Desive gem)后,在通过所有验证过程之前,只能访问两个控制器。为了检查验证过程是否正在进行,我使用了Ruby on rails Rails只允许在注册后访问两个页面,ruby-on-rails,Ruby On Rails,我遇到了这样一种情况,用户在成功注册过程(我使用的是Desive gem)后,在通过所有验证过程之前,只能访问两个控制器。为了检查验证过程是否正在进行,我使用了status列。如果状态==''表示验证未完成 我想知道如何实现这种只访问两个页面的访问?我的第一个想法是Pundit gem,但如果我有50个控制器,我将需要实现50个策略,其中我将有许多与控制器操作相对应的方法。有没有更好的办法 [编辑] 这就是我到目前为止所做的: class BaseController < Applicat
status
列。如果状态==''
表示验证未完成
我想知道如何实现这种只访问两个页面的访问?我的第一个想法是Pundit gem,但如果我有50个控制器,我将需要实现50个策略,其中我将有许多与控制器操作相对应的方法。有没有更好的办法
[编辑]
这就是我到目前为止所做的:
class BaseController < ApplicationController
before_action :authorized_user
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def authorized_user
policy_scope(current_user)
end
private
def user_not_authorized
flash[:alert] = 'You are not authorized to perform this action.'
redirect_to(request.referrer || root_path)
end
end
class BaseController
用户策略:
class UserPolicy < ApplicationPolicy
class Scope < Scope
def resolve
return raise(Pundit::NotAuthorizedError) unless user.status == 'active'
scope.all
end
end
end
class UserPolicy
仅当控制器从ApplicationController继承时,此答案才有效
在动作之前添加一个,
到您的应用程序控制器,当用户未经验证时,该控制器会执行某些操作。这将触发所有控制器操作
class ApplicationController
除特定控制器外,您可以在操作之前跳过
class SomeController
多亏@tadam评论中的建议,我最终得到了以下代码:
#intermediate controller class
class BaseController < ApplicationController
before_action :authorized_user
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def authorized_user
authorize :global, :only_active?
end
private
def user_not_authorized
flash[:alert] = 'You are not authorized to perform this action.'
redirect_to root_path
end
end
#中间控制器类
类BaseController<应用程序控制器
行动前:授权用户
从权威人士处拯救用户::未授权用户::未授权
def授权用户
授权:全局,:仅\u活动?
结束
私有的
def用户未经授权
flash[:alert]=“您无权执行此操作。”
将\重定向到根\路径
结束
结束
BaseController中使用的全局策略
class GlobalPolicy < ApplicationPolicy
def only_active?
active?
end
end
类全局策略
提示:在通常转换为记录.status?
的Rails中,它不仅测试nil
,还测试空字符串和完全由空白字符组成的字符串。您可以使用Pundit等工具来制定ACL(访问控制列表)策略。您可以根据需要制定尽可能少或尽可能多的策略。也许制定一个“有效”的政策,然后更广泛地应用?一个技巧是从执行验证检查的中间控制器类继承所有“Required validation”控制器。@tadman但是这个“中间控制器类”在执行操作之前应该有某种类型的?接受来自这些控制器的所有方法的策略是什么样子的?是的,通常就是这样。“这取决于专家希望你做什么。”塔德曼,你能看看我现在有什么吗?应该是这样还是我错过了什么?