trabajo-afectivo/app/models/authorization.rb

97 lines
2.4 KiB
Ruby
Raw Normal View History

2016-10-19 03:11:36 +00:00
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
class Authorization < ApplicationModel
belongs_to :user
after_create :delete_user_cache
after_update :delete_user_cache
after_destroy :delete_user_cache
validates :user_id, presence: true
validates :uid, presence: true, uniqueness: { scope: :provider }
validates :provider, presence: true
2012-04-10 14:06:46 +00:00
def self.find_from_hash(hash)
2016-03-08 06:32:58 +00:00
auth = Authorization.find_by(provider: hash['provider'], uid: hash['uid'])
if auth
2012-04-10 14:06:46 +00:00
# update auth tokens
auth.update!(
token: hash['credentials']['token'],
secret: hash['credentials']['secret']
2012-04-10 14:06:46 +00:00
)
# update username of auth entry if empty
if !auth.username && hash['info']['nickname']
auth.update!(
username: hash['info']['nickname'],
)
end
2012-04-10 14:06:46 +00:00
# update image if needed
if hash['info']['image']
2016-03-08 06:32:58 +00:00
user = User.find(auth.user_id)
2014-12-01 07:32:35 +00:00
# save/update avatar
avatar = Avatar.add(
object: 'User',
o_id: user.id,
url: hash['info']['image'],
source: hash['provider'],
deletable: true,
updated_by_id: user.id,
created_by_id: user.id,
2012-04-10 14:06:46 +00:00
)
2014-12-01 07:32:35 +00:00
# update user link
if avatar && user.image != avatar.store_hash
user.image = avatar.store_hash
user.save
2014-12-01 07:32:35 +00:00
end
2012-04-10 14:06:46 +00:00
end
end
2014-12-01 07:32:35 +00:00
auth
2012-04-10 14:06:46 +00:00
end
2012-04-10 14:06:46 +00:00
def self.create_from_hash(hash, user = nil)
2014-12-01 07:32:35 +00:00
if !user
user = User.create_from_hash!(hash)
end
# save/update avatar
2017-10-20 13:32:01 +00:00
if hash['info'].present? && hash['info']['image'].present?
2014-12-01 07:32:35 +00:00
avatar = Avatar.add(
object: 'User',
o_id: user.id,
url: hash['info']['image'],
source: hash['provider'],
deletable: true,
updated_by_id: user.id,
created_by_id: user.id,
2012-04-10 14:06:46 +00:00
)
2014-12-01 07:32:35 +00:00
# update user link
if avatar && user.image != avatar.store_hash
user.image = avatar.store_hash
user.save
2014-12-01 07:32:35 +00:00
end
2012-04-10 14:06:46 +00:00
end
2014-12-01 07:32:35 +00:00
Authorization.create(
user: user,
uid: hash['uid'],
2015-07-06 11:48:07 +00:00
username: hash['info']['nickname'] || hash['info']['username'] || hash['info']['name'] || hash['info']['email'] || hash['username'],
provider: hash['provider'],
token: hash['credentials']['token'],
secret: hash['credentials']['secret']
2012-04-10 14:06:46 +00:00
)
2012-04-16 08:04:49 +00:00
end
private
def delete_user_cache
return if !user
2015-07-06 11:48:07 +00:00
user.touch
end
2014-12-01 07:32:35 +00:00
end