Module: RestGraph::RailsUtil

Defined in:
lib/rest-graph/rails_util.rb

Defined Under Namespace

Modules: Helper

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(controller) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rest-graph/rails_util.rb', line 59

def self.included controller
  # skip if included already, any better way to detect this?
  return if controller.respond_to?(:rest_graph, true)

  controller.rescue_from(RestGraph::Error::AccessToken,
                         :with => :rest_graph_on_access_token_error)
  controller.helper(RestGraph::RailsUtil::Helper)
  controller.instance_methods.select{ |method|
    method.to_s =~ /^rest_graph/
  }.each{ |method| controller.send(:protected, method) }
end

.init(app = Rails) ⇒ Object



48
49
50
51
# File 'lib/rest-graph/rails_util.rb', line 48

def self.init app=Rails
  ActiveSupport::Cache::Store.send(:include, RestGraph::RailsCache)
  RestGraph::ConfigUtil.load_config_for_rails(app)
end

.rest_graph_auto_authorize?Boolean

Returns:

  • (Boolean)


354
355
356
357
358
# File 'lib/rest-graph/rails_util.rb', line 354

def rest_graph_auto_authorize?
  !rest_graph_oget(:auto_authorize_scope)  .blank? ||
  !rest_graph_oget(:auto_authorize_options).blank? ||
   rest_graph_oget(:auto_authorize)
end

.rest_graph_check_codeObject

exchange the code with access_token



241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/rest-graph/rails_util.rb', line 241

def rest_graph_check_code
  return if rest_graph.authorized? || !params[:code]

  rest_graph.authorize!(:code => params[:code],
                        :redirect_uri => rest_graph_normalized_request_uri)
  logger.debug(
    "DEBUG: RestGraph: detected code with "  \
    "#{rest_graph_normalized_request_uri}, " \
    "parsed: #{rest_graph.data.inspect}")

  rest_graph_write_rg_fbs if rest_graph.authorized?
end

if we’re not in canvas nor code passed, we could check out cookies as well.



230
231
232
233
234
235
236
237
238
# File 'lib/rest-graph/rails_util.rb', line 230

def rest_graph_check_cookie
  return if rest_graph.authorized?                 ||
            (!cookies["fbsr_#{rest_graph.app_id}"] &&
             !cookies["fbs_#{rest_graph.app_id}"])

  rest_graph.parse_cookies!(cookies)
  logger.debug("DEBUG: RestGraph: detected cookies, parsed:" \
               " #{rest_graph.data.inspect}")
end

.rest_graph_check_params_sessionObject

if the code is bad or not existed, check if there’s one in session, meanwhile, there the sig and access_token is correct, that means we’re in the context of canvas



214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/rest-graph/rails_util.rb', line 214

def rest_graph_check_params_session
  return if rest_graph.authorized? || !params[:session]

  rest_graph.parse_json!(params[:session])
  logger.debug("DEBUG: RestGraph: detected session, parsed:" \
               " #{rest_graph.data.inspect}")

  if rest_graph.authorized?
    rest_graph_write_rg_fbs
  else
    logger.warn("WARN: RestGraph: bad session: #{params[:session]}")
  end
end

.rest_graph_check_params_signed_requestObject

begin facebook check ======================


195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/rest-graph/rails_util.rb', line 195

def rest_graph_check_params_signed_request
  return if rest_graph.authorized? || !params[:signed_request]

  rest_graph.parse_signed_request!(params[:signed_request])
  logger.debug("DEBUG: RestGraph: detected signed_request, parsed:" \
               " #{rest_graph.data.inspect}")

  if rest_graph.authorized?
    rest_graph_write_rg_fbs
  else
    logger.warn(
      "WARN: RestGraph: bad signed_request: #{params[:signed_request]}")
  end
end

.rest_graph_check_rg_cookiesObject



283
284
285
286
287
288
289
# File 'lib/rest-graph/rails_util.rb', line 283

def rest_graph_check_rg_cookies
  return if rest_graph.authorized? || !rest_graph_oget(:write_cookies) ||
            !(fbs = cookies[rest_graph_storage_key])
  rest_graph.parse_fbs!(fbs)
  logger.debug("DEBUG: RestGraph: detected rest-graph cookies, parsed:" \
               " #{rest_graph.data.inspect}")
end

.rest_graph_check_rg_fbsObject



262
263
264
265
266
# File 'lib/rest-graph/rails_util.rb', line 262

def rest_graph_check_rg_fbs
  rest_graph_check_rg_handler # custom method to store fbs
  rest_graph_check_rg_session # prefered way to store fbs
  rest_graph_check_rg_cookies # in canvas, session might not work..
end

.rest_graph_check_rg_handler(handler = rest_graph_oget(:check_handler)) ⇒ Object



268
269
270
271
272
273
# File 'lib/rest-graph/rails_util.rb', line 268

def rest_graph_check_rg_handler handler=rest_graph_oget(:check_handler)
  return if rest_graph.authorized? || !handler
  rest_graph.parse_fbs!(handler.call)
  logger.debug("DEBUG: RestGraph: called check_handler, parsed:" \
               " #{rest_graph.data.inspect}")
end

.rest_graph_check_rg_sessionObject



275
276
277
278
279
280
281
# File 'lib/rest-graph/rails_util.rb', line 275

def rest_graph_check_rg_session
  return if rest_graph.authorized? || !rest_graph_oget(:write_session) ||
            !(fbs = session[rest_graph_storage_key])
  rest_graph.parse_fbs!(fbs)
  logger.debug("DEBUG: RestGraph: detected rest-graph session, parsed:" \
               " #{rest_graph.data.inspect}")
end

.rest_graph_cleanupObject

begin misc ================================


321
322
323
324
325
326
# File 'lib/rest-graph/rails_util.rb', line 321

def rest_graph_cleanup
  cookies.delete("fbs_#{rest_graph.app_id}")
  cookies.delete("fbsr_#{rest_graph.app_id}")
  cookies.delete(rest_graph_storage_key)
  session.delete(rest_graph_storage_key)
end

.rest_graph_extract_options(options, method) ⇒ Object



360
361
362
363
# File 'lib/rest-graph/rails_util.rb', line 360

def rest_graph_extract_options options, method
  # Hash[] is for ruby 1.8.7
  Hash[options.send(method){ |(k, v)| RestGraph::Attributes.member?(k) }]
end

.rest_graph_filter_uri(uri) ⇒ Object



341
342
343
344
345
346
347
348
# File 'lib/rest-graph/rails_util.rb', line 341

def rest_graph_filter_uri uri
  URI.parse(URI.encode(uri)).tap{ |uri|
    uri.query = uri.query.split('&').reject{ |q|
                  q =~ /^(code|session|signed_request)\=/
                }.join('&') if uri.query
    uri.query = nil if uri.query.blank?
  }.to_s
end

.rest_graph_in_canvas?Boolean

Returns:

  • (Boolean)


350
351
352
# File 'lib/rest-graph/rails_util.rb', line 350

def rest_graph_in_canvas?
  !rest_graph_oget(:canvas).blank?
end

.rest_graph_normalized_request_uriObject



328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/rest-graph/rails_util.rb', line 328

def rest_graph_normalized_request_uri
  uri = if rest_graph_in_canvas?
          # rails 3 uses newer rack which has fullpath
          "http://apps.facebook.com/#{rest_graph_oget(:canvas)}" +
          (request.respond_to?(:fullpath) ?
            request.fullpath : request.request_uri)
        else
          request.url
        end

  rest_graph_filter_uri(uri)
end

.rest_graph_oget(key) ⇒ Object

begin options utility =======================


175
176
177
178
179
180
181
# File 'lib/rest-graph/rails_util.rb', line 175

def rest_graph_oget key
  if rest_graph_options_ctl.has_key?(key)
    rest_graph_options_ctl[key]
  else
    RestGraph.send("default_#{key}")
  end
end

.rest_graph_options_ctlObject



183
184
185
# File 'lib/rest-graph/rails_util.rb', line 183

def rest_graph_options_ctl
  @rest_graph_options_ctl ||= {}
end

.rest_graph_options_newObject



187
188
189
# File 'lib/rest-graph/rails_util.rb', line 187

def rest_graph_options_new
  @rest_graph_options_new ||= {}
end

.rest_graph_storage_keyObject

begin check ================================


258
259
260
# File 'lib/rest-graph/rails_util.rb', line 258

def rest_graph_storage_key
  "rest_graph_fbs_#{rest_graph_oget(:app_id)}"
end

.rest_graph_write_rg_cookiesObject



311
312
313
314
315
# File 'lib/rest-graph/rails_util.rb', line 311

def rest_graph_write_rg_cookies
  return if !rest_graph_oget(:write_cookies)
  cookies[rest_graph_storage_key] = fbs = rest_graph.fbs
  logger.debug("DEBUG: RestGraph: wrote cookies: fbs => #{fbs}")
end

.rest_graph_write_rg_fbsObject

end check ================================
begin write ================================


292
293
294
295
296
297
# File 'lib/rest-graph/rails_util.rb', line 292

def rest_graph_write_rg_fbs
  cookies.delete("fbs_#{rest_graph.app_id}")
  rest_graph_write_rg_handler
  rest_graph_write_rg_session
  rest_graph_write_rg_cookies
end

.rest_graph_write_rg_handler(handler = rest_graph_oget(:write_handler)) ⇒ Object



299
300
301
302
303
# File 'lib/rest-graph/rails_util.rb', line 299

def rest_graph_write_rg_handler handler=rest_graph_oget(:write_handler)
  return if !handler
  handler.call(fbs = rest_graph.fbs)
  logger.debug("DEBUG: RestGraph: called write_handler: fbs => #{fbs}")
end

.rest_graph_write_rg_sessionObject



305
306
307
308
309
# File 'lib/rest-graph/rails_util.rb', line 305

def rest_graph_write_rg_session
  return if !rest_graph_oget(:write_session)
  session[rest_graph_storage_key] = fbs = rest_graph.fbs
  logger.debug("DEBUG: RestGraph: wrote session: fbs => #{fbs}")
end

Instance Method Details

#rest_graphObject

override this if you need different app_id and secret



104
105
106
# File 'lib/rest-graph/rails_util.rb', line 104

def rest_graph
  @rest_graph ||= RestGraph.new(rest_graph_options_new)
end

#rest_graph_authorize(error = nil, force_redirect = true) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/rest-graph/rails_util.rb', line 114

def rest_graph_authorize error=nil, force_redirect=true
  logger.warn("WARN: RestGraph: #{error.inspect}")

  if force_redirect || rest_graph_auto_authorize?
    @rest_graph_authorize_url = rest_graph.authorize_url(
      {:redirect_uri => rest_graph_normalized_request_uri,
       :scope        => rest_graph_oget(:auto_authorize_scope)}.
      merge(rest_graph_oget(:auto_authorize_options)))

    logger.debug("DEBUG: RestGraph: redirect to #{@rest_graph_authorize_url}")

    rest_graph_cleanup
    rest_graph_authorize_redirect
  end
end

#rest_graph_authorize_body(redirect_url = @rest_graph_authorize_url) ⇒ Object



162
163
164
165
166
167
168
169
170
# File 'lib/rest-graph/rails_util.rb', line 162

def rest_graph_authorize_body redirect_url=@rest_graph_authorize_url
  <<-HTML
  <div>
    Please
    <a href="#{CGI.escapeHTML(redirect_url)}" target="_top">authorize</a>
    if this page is not automatically redirected.
  </div>
  HTML
end

#rest_graph_authorize_redirectObject

override this if you want the simple redirect_to



131
132
133
134
135
136
137
138
# File 'lib/rest-graph/rails_util.rb', line 131

def rest_graph_authorize_redirect
  unless rest_graph_in_canvas?
    redirect_to @rest_graph_authorize_url
  else
    rest_graph_js_redirect(@rest_graph_authorize_url,
                            rest_graph_authorize_body)
  end
end

#rest_graph_js_redirect(redirect_url, body = '') ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/rest-graph/rails_util.rb', line 140

def rest_graph_js_redirect redirect_url, body=''
  render :inline => <<-HTML
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html>
    <head>
    <script type="text/javascript">
      window.top.location.href = '#{redirect_url}'
    </script>
    <noscript>
      <meta http-equiv="refresh" content="0;url=#{
        CGI.escapeHTML(redirect_url)}"/>
      <meta http-equiv="window-target" content="_top"/>
    </noscript>
    </head>
    <body>
      #{body}
    </bodt>
  </html>
  HTML
end

#rest_graph_on_access_token_error(error = nil) ⇒ Object Also known as: rest_graph_on_error



108
109
110
# File 'lib/rest-graph/rails_util.rb', line 108

def rest_graph_on_access_token_error error=nil
  rest_graph_authorize(error, false)
end

#rest_graph_setup(options = {}) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/rest-graph/rails_util.rb', line 71

def rest_graph_setup options={}
  rest_graph_options_ctl.merge!(rest_graph_extract_options(options, :reject))
  rest_graph_options_new.merge!(rest_graph_extract_options(options, :select))

  # we'll need to reinitialize rest_graph with the new options,
  # otherwise if you're calling rest_graph before rest_graph_setup,
  # you'll end up with default options without the ones you've passed
  # into rest_graph_setup.
  rest_graph.send(:initialize, rest_graph_options_new)

  rest_graph_check_params_signed_request # canvas
  rest_graph_check_params_session        # i think it would be deprecated
  rest_graph_check_cookie                # for js sdk (canvas or not)
  rest_graph_check_code                  # oauth api

  # there are above 4 ways to check the user identity!
  # if nor of them passed, then we can suppose the user
  # didn't authorize for us, but we can check if user has authorized
  # before, in that case, the fbs would be inside session,
  # as we just saved it there

  rest_graph_check_rg_fbs # check rest-graph storage

  if rest_graph_oget(:ensure_authorized) && !rest_graph.authorized?
    rest_graph_authorize('ensure authorized')
    false # action halt, redirect to do authorize,
          # eagerly, as opposed to auto_authorize
  else
    true  # keep going
  end
end