authorization.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright (C) 2012-2013 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_presence_of :user_id, :uid, :provider
  8. validates_uniqueness_of :uid, :scope => :provider
  9. def self.find_from_hash(hash)
  10. auth = Authorization.where( :provider => hash['provider'], :uid => hash['uid'] ).first
  11. if auth
  12. # update auth tokens
  13. auth.update_attributes(
  14. :token => hash['credentials']['token'],
  15. :secret => hash['credentials']['secret']
  16. )
  17. # update username of auth entry if empty
  18. if !auth.username && hash['info']['nickname']
  19. auth.update_attributes(
  20. :username => hash['info']['nickname'],
  21. )
  22. end
  23. # update image if needed
  24. if hash['info']['image']
  25. user = User.find( auth.user_id )
  26. user.update_attributes(
  27. :image => hash['info']['image']
  28. )
  29. end
  30. end
  31. return auth
  32. end
  33. def self.create_from_hash(hash, user = nil)
  34. if user then
  35. user.update_attributes(
  36. # :username => hash['username'],
  37. :image => hash['info']['image']
  38. )
  39. # fillup empty attributes
  40. # TODO
  41. else
  42. user = User.create_from_hash!(hash)
  43. end
  44. auth = Authorization.create(
  45. :user => user,
  46. :uid => hash['uid'],
  47. :username => hash['info']['nickname'] || hash['username'],
  48. :provider => hash['provider'],
  49. :token => hash['credentials']['token'],
  50. :secret => hash['credentials']['secret']
  51. )
  52. return auth
  53. end
  54. private
  55. def delete_user_cache
  56. self.user.cache_delete
  57. end
  58. end