class User < ApplicationRecord has_many :authentications, dependent: :destroy has_many :forms, dependent: :destroy def self.find_by_oauth_info(auth_client) oauth = Google::Apis::Oauth2V2::Oauth2Service.new oauth.authorization = auth_client user_info = oauth.get_userinfo if user = User.find_by(google_id: user_info.id) authentication = user.authentications.last authentication.access_token = auth_client.access_token if auth_client.access_token.present? authentication.refresh_token = auth_client.refresh_token if auth_client.refresh_token.present? authentication.expires_at = Time.at(auth_client.expires_at) if auth_client.expires_at.present? authentication.save return user, authentication else user = User.create(name: user_info.name, email: user_info.email, google_id: user_info.id) authentication = user.authentications.create( access_token: auth_client.access_token, refresh_token: auth_client.refresh_token, expires_at: Time.at(auth_client.expires_at) ) return user, authentication end end def deactivate!(reason = nil) # currently we only use deactivate if we get an authentication exception appending data to a spreadsheet authentications.last&.update(expires_at: Time.current) end def active? authentications.last.present? && !authentications.last.expired? end def google_authorization authentications.last.google_authorization end end