authorization.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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_attributes(
  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_attributes(
  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
  48. user = User.create_from_hash!(hash)
  49. end
  50. # save/update avatar
  51. if hash['info']['image']
  52. avatar = Avatar.add(
  53. object: 'User',
  54. o_id: user.id,
  55. url: hash['info']['image'],
  56. source: hash['provider'],
  57. deletable: true,
  58. updated_by_id: user.id,
  59. created_by_id: user.id,
  60. )
  61. # update user link
  62. if avatar && user.image != avatar.store_hash
  63. user.image = avatar.store_hash
  64. user.save
  65. end
  66. end
  67. Authorization.create(
  68. user: user,
  69. uid: hash['uid'],
  70. username: hash['info']['nickname'] || hash['info']['username'] || hash['info']['name'] || hash['info']['email'] || hash['username'],
  71. provider: hash['provider'],
  72. token: hash['credentials']['token'],
  73. secret: hash['credentials']['secret']
  74. )
  75. end
  76. private
  77. def delete_user_cache
  78. return if !user
  79. user.touch
  80. end
  81. end