Sha256: 0177552ffdf6767ce6e27b3c699f72c8ed6a200dd34599bb844c604698f00f8e

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

module FbGraph
  # = Parse & verify facebook auth cookie
  # 
  # Used with Facebook JavaScript SDK
  # 
  #   app = FbGraph::Auth.new(APP_ID, APP_SECRET)
  #   app.from_cookie(cookie_hash)
  #   auth.access_token
  #   # => OAuth2::AccessToken (not String!)
  #   auth.user # only initialized
  #   auth.user.fetch # fetch whole profile
  # 
  # This method is called automatically if cookie is given when initializing
  # 
  #   auth = FbGraph::Auth.new(APP_ID, APP_SECRET, :cookie => {..})
  #   auth.access_token # already parsed
  class Auth
    class VerificationFailed < Exception; end

    attr_accessor :client, :access_token, :user, :data

    def initialize(client_id, client_secret, options = {})
      @client = OAuth2::Client.new(client_id, client_secret, options.merge(
        :site => ROOT_URL
      ))
      if options[:cookie]
        from_cookie options[:cookie]
      elsif options[:signed_request]
        from_signed_request options[:signed_request]
      end
    end

    def authorized?
      self.access_token.present?
    end

    def from_cookie(cookie)
      data = Cookie.parse(self.client, cookie)
      self.access_token = build_access_token(data)
      self.user = User.new(data[:uid], :access_token => self.access_token)
      self.data = data
      self
    end

    def from_signed_request(signed_request)
      data = SignedRequest.verify(self.client, signed_request)
      if data[:oauth_token]
        self.access_token = build_access_token(data)
        self.user = User.new(data[:user_id], data[:user].merge(:access_token => self.access_token))
      end
      self.data = data
      self
    end

    private

    def build_access_token(data)
      expires_in = unless data[:expires].zero?
        data[:expires] - Time.now.to_i
      end
      OAuth2::AccessToken.new(
        self.client,
        data[:oauth_token] || data[:access_token],
        nil,
        expires_in
      )
    end
  end
end

require 'fb_graph/auth/cookie'
require 'fb_graph/auth/signed_request'

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fb_graph-1.5.2 lib/fb_graph/auth.rb