app/models/user.rb
# generate an access token based on user's refresh token
generate an access token based on user's refresh token
generate an access token based on user ' s refresh token
def generate_access_token
    if self.refresh_token.present?
      begin
        client = Signet::OAuth2::Client.new(
            token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
            grant_type:'refresh_token',
            refresh_token: self.refresh_token,
            client_id: ENV['OAUTH_CLIENT_ID'],
            client_secret: ENV['OAUTH_CLIENT_SECRET'],
            expires_in: 3600
        )
        token_vals = client.fetch_access_token
        expires_at = DateTime.now + token_vals['expires_in'].to_i.seconds
        user_access_token = {'access_token' => token_vals['access_token'], 'expires_in' => token_vals['expires_in'], 'expires_at' => expires_at}
        self.update!(access_token: user_access_token)
        user_access_token
      rescue RestClient::BadRequest => e
        Rails.logger.error "Unable to generate access token for user #{self.email}; refresh token is invalid."
        nil
      rescue => e
        Rails.logger.error "Unable to generate access token for user #{self.email} due to unknown error; #{e.message}"
      end
    else
      nil
    end
  end
def generate_access_token if self . refresh_token . present? begin client = Signet :: OAuth2 :: Client . new ( token_credential_uri : 'https://accounts.google.com/o/oauth2/token' , grant_type : 'refresh_token' , refresh_token : self . refresh_token , client_id : ENV [ 'OAUTH_CLIENT_ID' ] , client_secret : ENV [ 'OAUTH_CLIENT_SECRET' ] , expires_in : 3600 ) token_vals = client . fetch_access_token expires_at = DateTime . now + token_vals [ 'expires_in' ] . to_i . seconds user_access_token = { 'access_token' => token_vals [ 'access_token' ] , 'expires_in' => token_vals [ 'expires_in' ] , 'expires_at' => expires_at } self . update! ( access_token : user_access_token ) user_access_token rescue RestClient :: BadRequest => e Rails . logger . error "Unable to generate access token for user #{self.email}; refresh token is invalid." nil rescue => e Rails . logger . error "Unable to generate access token for user #{self.email} due to unknown error; #{e.message}" end else nil end end
generate an access token based on user's refresh token
generate an access token based on user ' s refresh token