我有两个型号
influencers(id, first_name, ....)
influencer_authorizations(id, provider, provider_uid, oauth_token, ....)
影响者has_many influencer_authorizations
我正在尝试登录或签署影响者
# 1. Check if the Token is Valid
# 2. Check if the influencer has the authorization for that facebook_uid
# 3. If no - then create a new influencer
# 4. If yes - Then he is loging in. so update the token and log him in
但是当OLD用户尝试登录时,OAuth令牌没有得到更新
Facebook控制器
def create
@facebook_login = FacebookClient.new(facebook_user_token)
if @facebook_login.create
render :show
else
render :error
end
end
Facebook客户
class FacebookClient
def initialize(token)
@token = token
@client = Koala::Facebook::API.new(token)
end
attr_reader :influencer
def create
@influencer = new_or_existing_influencer
save_influencer
end
def errors
{
facebook_error: @facebook_errors
}
end
private
attr_reader :client
def new_or_existing_influencer
influencer = Influencer.joins(:influencer_authorizations).where(
:influencer_authorizations => {
provider: 'facebook',
provider_uid: provider_uid
}
).first_or_initialize
influencer
end
def save_influencer
set_influencer_details if @influencer.new_record?
set_influencer_authorization_details if @influencer.new_record?
@influencer.influencer_authorizations[0].oauth_token = @token if !influencer.new_record?
@influencer.save
end
def set_influencer_details
@influencer.assign_attributes(
first_name: first_name,
last_name: last_name,
email: email,
bio: bio,
date_of_birth: birthday,
gender: gender,
location: location
)
end
def set_influencer_authorization_details
@influencer.influencer_authorizations.build(
provider: 'facebook',
provider_uid: provider_uid,
oauth_token: @token,
social_account: SocialAccount.friendly.find('facebook')
)
end
def basic_information
begin
@basic_information ||= client.get_object("me?fields=id,first_name,last_name,name,bio,about,birthday,email,timezone,gender,location,hometown,currency,locale,devices")
rescue Koala::Facebook::APIError => exc
@facebook_errors = exc.message
end
end
def provider_uid
basic_information["id"]
end
def first_name
basic_information["first_name"]
end
def last_name
basic_information["last_name"]
end
def name
basic_information["name"]
end
def email
basic_information["email"]
end
def bio
basic_information["bio"]
end
def location
basic_information["location"].present? ? basic_information["location"]["name"] : ""
end
def birthday
basic_information["birthday"].present? ? Date.strptime(basic_information["birthday"], "%m/%d/%Y") : ""
end
def gender
basic_information["gender"].present? ? basic_information["gender"] : "not_specified"
end
end
在保存检查之前,Oauth Token设置为@influencer.influencer_authorizations[0].oauth_token