auth.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Auth
  3. attr_reader :user, :password, :auth_user
  4. delegate :user, to: :auth_user
  5. attr_accessor :increase_login_failed_attempts
  6. BRUTE_FORCE_SLEEP = 1.second
  7. # Initializes a Auth object for the given user.
  8. #
  9. # @param username [String] the user name for the user object which needs an authentication.
  10. #
  11. # @example
  12. # auth = Auth.new('admin@example.com', 'some+password')
  13. def initialize(username, password)
  14. @auth_user = username.present? ? Auth::User.new(username) : nil
  15. @password = password
  16. @increase_login_failed_attempts = false
  17. end
  18. # Validates the given credentials for the user to the configured auth backends which should
  19. # be performed.
  20. #
  21. # @return [Boolean] true if the user was authenticated, otherwise false.
  22. def valid?
  23. # Wrap in a lock to synchronize concurrent requests.
  24. validated = auth_user&.user&.with_lock do
  25. next false if !auth_user.can_login?
  26. next true if backends.valid?
  27. auth_user.increase_login_failed if increase_login_failed_attempts
  28. false
  29. end
  30. if validated
  31. auth_user.update_last_login
  32. return true
  33. end
  34. avoid_brute_force_attack
  35. false
  36. end
  37. private
  38. # Sleep for a second to avoid brute force attacks.
  39. def avoid_brute_force_attack
  40. sleep BRUTE_FORCE_SLEEP
  41. end
  42. def backends
  43. Auth::Backend.new(self)
  44. end
  45. end