auth.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Auth
  3. include ApplicationLib
  4. =begin
  5. checks if a given user can login. Checks for
  6. - valid user
  7. - active state
  8. - max failed logins
  9. result = Auth.can_login?(user)
  10. returns
  11. result = true | false
  12. =end
  13. def self.can_login?(user)
  14. return false if !user.is_a?(User)
  15. return false if !user.active?
  16. return true if !user.max_login_failed?
  17. Rails.logger.info "Max login failed reached for user #{user.login}."
  18. false
  19. end
  20. =begin
  21. checks if a given user and password match against multiple auth backends
  22. - valid user
  23. - active state
  24. - max failed logins
  25. result = Auth.valid?(user, password)
  26. returns
  27. result = true | false
  28. =end
  29. def self.valid?(user, password)
  30. # try to login against configure auth backends
  31. backends.any? do |config|
  32. next if !backend_validates?(
  33. config: config,
  34. user: user,
  35. password: password,
  36. )
  37. Rails.logger.info "Authentication against #{config[:adapter]} for user #{user.login} ok."
  38. # remember last login date
  39. user.update_last_login
  40. true
  41. end
  42. end
  43. =begin
  44. returns a list of all Auth backend configurations
  45. result = Auth.backends
  46. returns
  47. result = [
  48. {
  49. adapter: 'Auth::Internal',
  50. },
  51. {
  52. adapter: 'Auth::Developer',
  53. },
  54. ...
  55. ]
  56. =end
  57. def self.backends
  58. # use std. auth backends
  59. config = [
  60. {
  61. adapter: 'Auth::Internal',
  62. },
  63. {
  64. adapter: 'Auth::Developer',
  65. },
  66. ]
  67. # added configured backends
  68. Setting.where(area: 'Security::Authentication').each do |setting|
  69. next if setting.state_current[:value].blank?
  70. config.push setting.state_current[:value]
  71. end
  72. config
  73. end
  74. def self.backend_validates?(config:, user:, password:)
  75. return false if !config[:adapter]
  76. # load backend
  77. backend = load_adapter(config[:adapter])
  78. return false if !backend
  79. instance = backend.new(config)
  80. instance.valid?(user, password)
  81. end
  82. private_class_method :backend_validates?
  83. end