So far i have managed to login users with google plus using the omniauth-google-oauth2 gem.
As far as i am concerned you get an access token that expires at some time. How can i refresh that token from the google API lets say once a week if the user logins with google plus on my website in a week from now?
below is the code i have in my sessioncontroller.rb
def google_oauth2
auth_hash = request.env['omniauth.auth']
@identity = Identity.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])
if @identity
log_in @identity.user
flash[:success] = "Welcome, #{@identity.user.name}!"
else
random_password = SecureRandom.urlsafe_base64(n=6)
#@user = create_with_omniauth(auth_hash)
@user = User.new(
name:auth_hash['info']['name'],
email:auth_hash['info']['email'],
password:random_password,
password_confirmation:random_password,
activated:true
)
@user.identities.build(
uid: auth_hash['uid'],
provider: auth_hash['provider'],
image_url: auth_hash['info']['image'],
oauth_token: auth_hash['credentials']['token'],
oauth_refresh_token: auth_hash['credentials']['refresh_token'],
oauth_expires_at: auth_hash['credentials']['expires_at']
)
if @user.save!
log_in @user
flash[:success] = "Hello, #{@user.name}! An account has been created for you!"
else
flash[:warning] = "There was an error while trying to authenticate you..."
end
end
redirect_to root_path
end
some attributes are saved in user table and some in Identity table with a has_many identities, belongs to user model because in the future i want to add multiple providers.
Aucun commentaire:
Enregistrer un commentaire