auth.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2012-2022 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. @lookup_backend_instance = {}
  15. @auth_user = username.present? ? Auth::User.new(username) : nil
  16. @password = password
  17. @increase_login_failed_attempts = false
  18. end
  19. # Validates the given credentials for the user to the configured auth backends which should
  20. # be performed.
  21. #
  22. # @return [Boolean] true if the user was authenticated, otherwise false.
  23. def valid?
  24. # Wrap in a lock to synchronize concurrent requests.
  25. validated = auth_user&.user&.with_lock do
  26. next false if !auth_user.can_login?
  27. next true if backends.valid?
  28. auth_user.increase_login_failed if increase_login_failed_attempts
  29. false
  30. end
  31. if validated
  32. auth_user.update_last_login
  33. return true
  34. end
  35. avoid_brute_force_attack
  36. false
  37. end
  38. private
  39. # Sleep for a second to avoid brute force attacks.
  40. def avoid_brute_force_attack
  41. sleep BRUTE_FORCE_SLEEP
  42. end
  43. def backends
  44. Auth::Backend.new(self)
  45. end
  46. end