我对基于学校的应用程序存在严重问题,我想设置像管理员,学生和教师的基于角色的系统。我使用了devise进行身份验证,并且可以使用cancan进行授权。问题是我不能从哪里开始。我添加了设计用户模型并添加了一个字段角色。我按照this进行了基于角色的授权。它可以工作,但是当我尝试通过在下拉列表中选择教师角色来登录学生凭证时,它永远不会验证角色(永远不会为您提供拒绝访问权限)。它以学生身份登录。我想在登录表单中验证所选角色。
到目前为止,我正在使用User模型作为设计模型。和 有学生模型,教师模型和管理模型。并且所有学生,教师和管理员都属于用户。
在用户模型中
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :admins
has_many :students
has_many :teachers
ROLES = %i[admin teacher student]
end
在我的设计注册视图中
<%= f.collection_select(:role, User::ROLES, :to_s, lambda{|i| i.to_s.humanize}) %>
或者,我是否要为所有学生,教师和管理员使用设计模型?如果是,我该如何完成。任何帮助或建议都很有帮助。提前谢谢。
答案 0 :(得分:0)
如果要验证特定角色用户使用在表单下拉列表中选择的角色登录,则必须自定义登录方法SessionsController#为登录表单中选择的角色创建,其中包含来自表单的用户凭据和发送错误警告并避免用户登录。
示例会话#create方法将是:
def create
self.resource = warden.authenticate!(auth_options)
if resource.role == params[:role]
set_flash_message!(:notice, :signed_in)
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, location: after_sign_in_path_for(resource)
else
set_flash_message!(:error, "UnAuthorized Access!")
redirect_to root_path
end
end