trabajo-afectivo/app/models/authorization.rb

58 lines
1.5 KiB
Ruby
Raw Normal View History

class Authorization < ApplicationModel
2012-04-16 08:04:49 +00:00
belongs_to :user
validates_presence_of :user_id, :uid, :provider
validates_uniqueness_of :uid, :scope => :provider
2012-04-10 14:06:46 +00:00
after_create :cache_delete
after_update :cache_delete
after_destroy :cache_delete
2012-04-10 14:06:46 +00:00
def self.find_from_hash(hash)
auth = Authorization.where( :provider => hash['provider'], :uid => hash['uid'] )
if auth && auth.first then
# raise auth.first.to_yaml
# raise hash.to_yaml
# update auth tokens
auth.first.update_attributes(
:token => hash['credentials']['token'],
:secret => hash['credentials']['secret']
)
# update image if needed
if hash['info']['image']
user = User.where( :id => auth.first.user_id ).first
user.update_attributes(
2012-04-16 08:04:49 +00:00
:image => hash['info']['image']
2012-04-10 14:06:46 +00:00
)
2012-04-16 08:04:49 +00:00
# reset cache
user.cache_delete
2012-04-10 14:06:46 +00:00
end
end
return auth.first
end
def self.create_from_hash(hash, user = nil)
if user then
user.update_attributes(
:username => hash['username'],
:image => hash['info']['image']
)
else
user = User.create_from_hash!(hash)
end
Authorization.create(
:user => user,
:uid => hash['uid'],
:username => hash['username'],
:provider => hash['provider'],
:token => hash['credentials']['token'],
:secret => hash['credentials']['secret']
)
2012-04-16 08:04:49 +00:00
# reset cache
user.cache_delete
end
2012-04-10 14:06:46 +00:00
end