Sha256: 2be0a20dd44605e3bf14c24bad7c707a7de382dcfc694da4171b2fc8ede74d34

Contents?: true

Size: 1.47 KB

Versions: 2

Compression:

Stored size: 1.47 KB

Contents

# frozen_string_literal: true

module ApiUserAuth
  module Providers
    # Get info from Facebook token
    class Facebook
      API_PATH = 'https://graph.facebook.com/v3.0/me'.freeze
      FIELDS = %w[id name email birthday hometown gender picture].freeze

      def initialize(token)
        @token = token
        @data = {}
      end

      def api_info_url
        params = {
          access_token: @token,
          fields: FIELDS.join(','),
          format: 'json'
        }
        URI("#{API_PATH}?#{params.to_query}")
      end

      def get_user_data
        api_get_request
        user_data
      end

      def user_data
        {
          id: @data[:id], name: @data[:name], email: @data[:email],
          img_url: (@data[:picture] || {}).try(:[], :data).try(:[], :url),
          info: {
            birthday: @data[:birthday],
            city: (@data[:hometown] || {}).try(:[], :name),
            gender: @data[:gender]
          }
        }
      end

      def self.get_user(token)
        fb = Facebook.new(token)
        fb.get_user_data
      end

      private

      def api_get_request
        response = ::Net::HTTP.get_response(api_info_url)
        case response.code.to_i
        when 200
          @data = JSON.parse(response.body, symbolize_names: true)
        when 400
          raise ApiUserAuth::Exceptions::InvalidToken, 'Invalid Token'
        else
          raise ApiUserAuth::Exceptions::ProviderError, 'Provider Error'
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
api_user_auth-0.0.14 lib/api_user_auth/providers/facebook.rb
api_user_auth-0.0.12 lib/api_user_auth/providers/facebook.rb