Module: ThecoreAuthCommons

Defined in:
lib/thecore_auth_commons.rb,
lib/thecore_auth_commons/engine.rb,
lib/thecore_auth_commons/version.rb

Defined Under Namespace

Classes: Engine

Constant Summary collapse

VERSION =
"3.5.4".freeze

Class Method Summary collapse

Class Method Details

.align_user(email, entry, server_id) ⇒ Object

Your code goes here…



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/thecore_auth_commons.rb', line 84

def self.align_user email, entry, server_id
  user = User.find_or_initialize_by(email: email)
  user.auth_source = "ldap #{server_id}"

  # Password don't need to be changed, just created, otherwise it will invalidate the current user session if it's logged in
  user.password = user.password_confirmation = ThecoreAuthCommons.generate_secure_password if user.new_record?

  # Eventuale mapping LDAP -> campi User
  user.name = entry[:givenname]&.first if user.respond_to?(:name)

  # Recupera dala entry i gruppi di cui fa parte l'utente e crea i relativi record in Role assegnandoli all'utente corrente
  is_admin = false
  entry[:memberOf].each do |group|
    group_name = group.split(",").first.split("=").last
    # Se il gruppo è un admin, assegna il ruolo admin
    is_admin = true if [ "Administrators", "Domain Admins", "Schema Admins", "Enterprise Admins", "admins", "administrators" ].include?(group_name)
    
    role = Role.find_or_create_by(name: group_name)
    user.roles << role unless user.roles.include?(role)
  end

  user.admin = is_admin if user.respond_to?(:admin)
  # Se l'utente è nuovo o ha cambiato qualcosa, salvalo
  puts "Cannot save user #{email} with errors: #{user.errors.full_messages.join(", ")}" unless user.save # if user.new_record? || user.changed? || user.roles_changed?
  user
end

.check_user(email, name, surname, provider) ⇒ Object

Controlla se l’utente esiste, altrimenti lo crea con una password casuale e lo restituisce. Se l’utente esiste già, lo restituisce senza modificarlo.



31
32
33
34
35
36
37
38
39
40
# File 'lib/thecore_auth_commons.rb', line 31

def self.check_user email, name, surname, provider
  u = User.find_or_initialize_by(email: email)
  u.name = name
  u.surname = surname
  u.password = u.password_confirmation = generate_secure_password
  u.auth_source = provider # 'google' or 'microsoft'
  u.admin = true
  u.save if u.changed?
  u
end

.entra_id_vars?Boolean



20
21
22
# File 'lib/thecore_auth_commons.rb', line 20

def self.entra_id_vars?
  ENV['ENTRA_CLIENT_ID'].present? && ENV['ENTRA_CLIENT_SECRET'].present? && ENV['ENTRA_TENANT_ID'].present?
end

.generate_secure_password(length = 20) ⇒ Object

Raises:

  • (ArgumentError)


111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/thecore_auth_commons.rb', line 111

def self.generate_secure_password(length = 20)
  raise ArgumentError, 'Length must be at least 4' if length < 4

  # Caratteri da cui attingere
  lowercase = ('a'..'z').to_a
  uppercase = ('A'..'Z').to_a
  numbers   = ('0'..'9').to_a
  symbols   = ['!', '@', '#', '$', '%', '&', '*', '?', '-', '_', '+', '=']

  # Obbliga almeno un carattere da ogni gruppo
  password = [
    lowercase.sample,
    uppercase.sample,
    numbers.sample,
    symbols.sample
  ]

  # Caratteri restanti scelti a caso tra tutti
  all_characters = lowercase + uppercase + numbers + symbols
  (length - 4).times { password << all_characters.sample }

  # Mischia per evitare ordine prevedibile
  password.shuffle.join
end

.google_oauth2_vars?Boolean



24
25
26
# File 'lib/thecore_auth_commons.rb', line 24

def self.google_oauth2_vars?
  ENV['GOOGLE_CLIENT_ID'].present? && ENV['GOOGLE_CLIENT_SECRET'].present?
end

.import_ldap_users_taskObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/thecore_auth_commons.rb', line 42

def self.import_ldap_users_task
  puts "== Avvio sincronizzazione utenti da LDAP =="

  imported_count = 0

  LdapServer.all.each do |server|
    puts "Contatto server LDAP: #{server.host} (priorità: #{server.priority})"

    ldap = Net::LDAP.new(
      host: server.host,
      port: server.port,
      encryption: server.use_ssl ? :simple_tls : nil,
      auth: {
        method: :simple,
        username: server.admin_user,
        password: server.admin_password
      }
    )

    unless ldap.bind
      puts "❌ Connessione fallita a #{server.host}"
      next
    end

    filter = Net::LDAP::Filter.present(server.auth_field)
    treebase = server.base_dn

    ldap.search(base: treebase, filter: filter) do |entry|
      email = entry[server.auth_field]&.first
      next unless email

      puts "Importando utente: #{email}"

      # Password must contain at least one uppercase letter, one lowercase letter, one number and one special character
      ThecoreAuthCommons.align_user email, entry, server.id
      imported_count += 1
    end
  end

  puts "== Completato. Utenti importati: #{imported_count} =="
end

.oauth_vars?Boolean



16
17
18
# File 'lib/thecore_auth_commons.rb', line 16

def self.oauth_vars? 
   entra_id_vars? || google_oauth2_vars?
end