前面的底线:当用户登录时,如何立即从 ldap 分配角色。
我正在使用 devise/cancan/deviseldap/rolify 对用户进行身份验证,然后希望分配一个角色。我很接近我认为让这个工作。我所拥有的是一个自定义初始化程序,只有当他们的 ldap 条目中有某个 memberOf 时,它才允许用户进入应用程序。
这要归功于该线程中人员的慷慨帮助:
在运行时使用 devise 和 devise_ldap_authenticable 检查组
所以现在是我分配角色的时候了,在网上搜索之后,我认为最好的方法可能是来自 devise 的 user.rb 中的 after_create。我在 config/initializer 中有这些 memberOf,但以后无法访问它们,就像user.rb
我在以下尝试中描述的那样user.rb
:
class User < ActiveRecord::Base
after_create :assign_role
...
...
private
def assign_role
puts "Assigning role!"
member_of = self.ldap_param_value("memberOf") #get array #i know self here is wrong
member_of.each do |str|
if str.include? 'Help Desk Admin'
self.roles << "admin"
end
if str.include? 'Password Manager'
self.roles << "password_manager"
end
if str.include? 'Security'
self.roles << "security"
end
if str.include? 'Help Desk'
self.roles << "help_desk"
end
end
puts "roles assigned!"
self.update
end
最大的问题(有很多我仍然是一个 ruby noobie)是我调用了一个方法 ldap_param_value 并且我知道在 self 上调用它是不正确的,我让这段代码在 config/initializer/customdevise 中工作在同一行。 rb(这是为了我的前门全部检查):(我知道我需要实例化正确的对象才能访问上面的 ldap_param_value,但不确定它是什么)。我以为 self 是:Devise::LdapAdapter,但我在上面尝试过,它仍然没有工作:
Devise::LdapAdapter.ldap_param_value(...)
为了完整起见config/initializer/customedevise.rb
Devise::LdapAdapter::LdapConnect.class_eval do
def user_group_test
member_of = self.ldap_param_value("memberOf") #self works here...
checkgroups member_of # your group test method end
def checkgroups(members)
retVal = false
members.each do |str|
if str.include? 'Help Desk Admin' or str.include? 'Password Manager' or str.include? 'Security' or str.include? 'Help Desk'
retVal = true;
end
end
return retVal
end
# 'CN=Password Manager'
# 'CN=Help Desk'
# 'CN=Help Desk Admin'
# 'CN=Security'
def authorized?
DeviseLdapAuthenticatable::Logger.send("Authorizing user #{dn}")
if !user_group_test
DeviseLdapAuthenticatable::Logger.send("Not authorized because custom authentication failed.")
return false
elsif !authenticated?
DeviseLdapAuthenticatable::Logger.send("Not authorized because not authenticated.")
return false
elsif !in_required_groups?
DeviseLdapAuthenticatable::Logger.send("Not authorized because not in required groups.")
return false
elsif !has_required_attribute?
DeviseLdapAuthenticatable::Logger.send("Not authorized because does not have required attribute.")
return false
else
return true
end
end
end
注意:上面的另一个缺陷是设计不知道身份验证失败的确切原因......我为此受苦并更改了devise.en.yml
文件invalid:
以包含更多信息:
en:
devise:
confirmations:
confirmed: "Your account was successfully confirmed. You are now signed in."
send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
failure:
already_authenticated: "You are already signed in."
inactive: "Your account was not activated yet."
invalid: "Invalid email or password. Or not a member of the correct group"
..etc...