Rails 7 + devise + devise_ldap_authenticatable:before_save 问题

问题描述 投票:0回答:1

我用 Rails 7 + devise + devise_ldap_authenticatable 编写了一个应用程序

我的用户模型看起来像这样。

class User < ApplicationRecord

  devise :ldap_authenticatable

  before_save :get_from_ldap

  def get_from_ldap
    puts '1 ##########################################'
    self.username = Devise::LDAP::Adapter.get_ldap_param(self.email,'userPrincipalName')
    puts '2 ##########################################'
  end
end

这工作完美,但只有一次。第一次,当用户第一次登录后被创建到数据库中时。

我不确定,但我认为这与一些 devise_ldap_authenticatable 指令有关,因为 before_save 通常总是正确调用?

config.ldap_create_user = true

我做错了什么?

我想要某种方法或技术来在每次用户登录时执行此操作,以确保我从 Active Directory 中获取所有更改。

谢谢。

更新###:

我尝试使用 before_validationafter_validation,所有这些回调仅被调用一次。用户第一次登录并被创建到数据库中。这不是正常的吧?有什么想法吗?

我的设计.rb

  # ==> LDAP Configuration
  config.ldap_logger = true
  config.ldap_create_user = true
  config.ldap_update_password = false
  config.ldap_config = "#{Rails.root}/config/ldap.yml"
  config.ldap_use_admin_to_bind = true
  # config.ldap_ad_group_check = false

  # Sin esta linea trata de buscar por mail en vez de por el atributo definido en
  # config.ldap_config = "#{Rails.root}/config/ldap.yml"
  # 
  # https://stackoverflow.com/questions/44121543/rails-devise-ldap-authentication-cannot-find-user
  #
  config.ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| login}

我的ldap,yml

## Authorizations
authorizations: &AUTHORIZATIONS
  allow_unauthenticated_bind: false

development:
  host: 13.0.0.1
  port: 389
  attribute: userPrincipalName
  group_membership_attribute: member
  base: dc=mydomain,dc=net
  admin_user: cn=Admin,ou=Users,ou=first,dc=mydomain,dc=net
  admin_password: ***********
  ssl: false
  # <<: *AUTHORIZATIONS
ruby-on-rails devise ldap ruby-on-rails-7
1个回答
0
投票

嗯。当然,回调仅在 save 时调用。在我的用例中,仅在创建每个用户时第一次登录。接下来的登录永远不会更新数据库,因此永远不会调用保存。

为了解决这个问题,我想了一种强制更新的方法。

设计可追踪模块是我的解决方案。感谢如何将可跟踪添加到现有的 Devise 设置?

如果我将 :trackable 添加到我的用户模型中,则每次登录都会调用回调。

class User < ApplicationRecord

  devise :ldap_authenticatable, :trackable

  before_save :get_from_ldap


  def get_from_ldap

    self.username = self.email.split('@')[0]

    # Se recuperan todos los grupos a los que pertenece el usuario
    groups = self.ldap_groups


    <MY CODE>    


  end
end
© www.soinside.com 2019 - 2024. All rights reserved.