authorization.rb 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Authorization < ApplicationModel
  3. belongs_to :user
  4. after_create :delete_user_cache
  5. after_update :delete_user_cache
  6. after_destroy :delete_user_cache
  7. validates :user_id, presence: true
  8. validates :uid, presence: true, uniqueness: { scope: :provider }
  9. validates :provider, presence: true
  10. def self.find_from_hash(hash)
  11. auth = Authorization.find_by(provider: hash['provider'], uid: hash['uid'])
  12. if auth
  13. # update auth tokens
  14. auth.update!(
  15. token: hash['credentials']['token'],
  16. secret: hash['credentials']['secret']
  17. )
  18. # update username of auth entry if empty
  19. if !auth.username && hash['info']['nickname']
  20. auth.update!(
  21. username: hash['info']['nickname'],
  22. )
  23. end
  24. # update image if needed
  25. if hash['info']['image']
  26. user = User.find(auth.user_id)
  27. # save/update avatar
  28. avatar = Avatar.add(
  29. object: 'User',
  30. o_id: user.id,
  31. url: hash['info']['image'],
  32. source: hash['provider'],
  33. deletable: true,
  34. updated_by_id: user.id,
  35. created_by_id: user.id,
  36. )
  37. # update user link
  38. if avatar && user.image != avatar.store_hash
  39. user.image = avatar.store_hash
  40. user.save
  41. end
  42. end
  43. end
  44. auth
  45. end
  46. def self.create_from_hash(hash, user = nil)
  47. if !user && Setting.get('auth_third_party_auto_link_at_inital_login')
  48. if hash['info'] && hash['info']['email'].present?
  49. user = User.find_by(email: hash['info']['email'].downcase)
  50. end
  51. end
  52. if !user
  53. user = User.create_from_hash!(hash)
  54. end
  55. # save/update avatar
  56. if hash['info'].present? && hash['info']['image'].present?
  57. avatar = Avatar.add(
  58. object: 'User',
  59. o_id: user.id,
  60. url: hash['info']['image'],
  61. source: hash['provider'],
  62. deletable: true,
  63. updated_by_id: user.id,
  64. created_by_id: user.id,
  65. )
  66. # update user link
  67. if avatar && user.image != avatar.store_hash
  68. user.image = avatar.store_hash
  69. user.save
  70. end
  71. end
  72. Authorization.create!(
  73. user: user,
  74. uid: hash['uid'],
  75. username: hash['info']['nickname'] || hash['info']['username'] || hash['info']['name'] || hash['info']['email'] || hash['username'],
  76. provider: hash['provider'],
  77. token: hash['credentials']['token'],
  78. secret: hash['credentials']['secret']
  79. )
  80. end
  81. private
  82. def delete_user_cache
  83. return if !user
  84. user.touch # rubocop:disable Rails/SkipsModelValidations
  85. end
  86. end