gpt4 book ai didi

ruby-on-rails - CanCan 中最安全和最可靠的方式来执行访客、用户、管理员权限

转载 作者:行者123 更新时间:2023-12-04 00:29:17 25 4
gpt4 key购买 nike

我对 rails (3) 比较陌生,并且正在使用 CanCan 构建一个应用程序,其中有 3 层用户。

  • 访客 - 未注册访客用户
  • 注册并登录访客
  • 管理员 - 注册并登录
    带有管理员标志的访客

  • 我现在的能力很糟糕,从 cancan 文档中复制而来,基本上定义了访客角色和管理员角色
    class Ability

    include CanCan::Ability

    def initialize(user)
    user ||= User.new # Guest user

    if user.is_admin?
    can :manage, :all
    else
    can :read, [Asana,Image,User,Video,Sequence]
    end
    end

    end

    我正在寻找添加用户角色。由于我正在创建那个一次性用户模型,我考虑过使用 new_record?确定用户是否登录。就像是:
    class Ability

    include CanCan::Ability

    def initialize(user)
    user ||= User.new # Guest user

    if !user.new_record? and user.is_admin?
    can :manage, :all
    elsif !user.new_record? and !user.is_admin?
    can {registered user-y permissions}
    else
    can :read, [Asana,Image,User,Video,Sequence]
    end
    end

    end

    但是,就是感觉不对。似乎有点与实际登录无关,并且担心它是否真的安全。

    寻找有关更优雅的方法的建议。

    谢谢!

    最佳答案

    好问题,我使用从低到高权限的方法:

    class Ability  
    include CanCan::Ability

    def initialize(user)
    # Guest User
    unless user
    can :read, [Asana,Image,User,Video,Sequence]
    else
    # All registered users
    can {registered user-y permissions}
    # Admins
    if user.is_admin?
    can :manage, :all
    end
    end
    end
    end

    这样,如果明天你有其他角色要集成,你可以添加一个 case 语句,如下所示:
    class Ability  
    include CanCan::Ability

    def initialize(user)
    # Guest User
    unless user
    can :read, [Asana,Image,User,Video,Sequence]
    else
    # All registered users
    can {registered user-y permissions}
    # Different roles
    case user.role
    when 'admin'
    can :manage, :all
    when 'manager'
    can :manage, [Video, Image, Sequence]
    end
    end
    end
    end

    关于ruby-on-rails - CanCan 中最安全和最可靠的方式来执行访客、用户、管理员权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5158326/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com