1 | 1 |
require 'sinatra/base'
|
2 | 2 |
require 'omniauth-facebook'
|
3 | 3 |
|
|
4 |
SCOPE = 'email,read_stream'
|
|
5 |
|
4 | 6 |
class App < Sinatra::Base
|
|
7 |
# server-side flow
|
5 | 8 |
get '/' do
|
|
9 |
# NOTE: you would just hit this endpoint directly from the browser
|
|
10 |
# in a real app. the redirect is just here to setup the root
|
|
11 |
# path in this example sinatra app.
|
6 | 12 |
redirect '/auth/facebook'
|
|
13 |
end
|
|
14 |
|
|
15 |
# client-side flow
|
|
16 |
get '/client-side' do
|
|
17 |
content_type 'text/html'
|
|
18 |
# NOTE: when you enable cookie below in the FB.init call
|
|
19 |
# the GET request in the FB.login callback will send
|
|
20 |
# a signed request in a cookie back the OmniAuth callback
|
|
21 |
# which will parse out the authorization code and obtain
|
|
22 |
# the access_token. This will be the exact same access_token
|
|
23 |
# returned to the client in response.authResponse.accessToken.
|
|
24 |
<<-END
|
|
25 |
<html>
|
|
26 |
<head>
|
|
27 |
<title>Client-side Flow Example</title>
|
|
28 |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
|
|
29 |
</head>
|
|
30 |
<body>
|
|
31 |
<div id="fb-root"></div>
|
|
32 |
|
|
33 |
<script type="text/javascript">
|
|
34 |
window.fbAsyncInit = function() {
|
|
35 |
FB.init({
|
|
36 |
appId : '#{ENV['APP_ID']}',
|
|
37 |
status : true, // check login status
|
|
38 |
cookie : true, // enable cookies to allow the server to access the session
|
|
39 |
oauth : true, // enable OAuth 2.0
|
|
40 |
xfbml : true // parse XFBML
|
|
41 |
});
|
|
42 |
};
|
|
43 |
|
|
44 |
(function(d) {
|
|
45 |
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
|
|
46 |
js = d.createElement('script'); js.id = id; js.async = true;
|
|
47 |
js.src = "//connect.facebook.net/en_US/all.js";
|
|
48 |
d.getElementsByTagName('head')[0].appendChild(js);
|
|
49 |
}(document));
|
|
50 |
|
|
51 |
$(function() {
|
|
52 |
$('a').click(function(e) {
|
|
53 |
e.preventDefault();
|
|
54 |
|
|
55 |
FB.login(function(response) {
|
|
56 |
if (response.authResponse) {
|
|
57 |
$.get('/auth/facebook/callback');
|
|
58 |
}
|
|
59 |
}, { scope: '#{SCOPE}' });
|
|
60 |
});
|
|
61 |
});
|
|
62 |
</script>
|
|
63 |
|
|
64 |
<p>
|
|
65 |
<a href="#">Connect to FB</a>
|
|
66 |
</p>
|
|
67 |
</body>
|
|
68 |
</html>
|
|
69 |
END
|
7 | 70 |
end
|
8 | 71 |
|
9 | 72 |
get '/auth/:provider/callback' do
|
|
20 | 83 |
use Rack::Session::Cookie
|
21 | 84 |
|
22 | 85 |
use OmniAuth::Builder do
|
23 | |
provider :facebook, ENV['APP_ID'], ENV['APP_SECRET'], :scope => 'email,read_stream', :display => 'popup'
|
|
86 |
provider :facebook, ENV['APP_ID'], ENV['APP_SECRET'], :scope => SCOPE
|
24 | 87 |
end
|
25 | 88 |
|
26 | 89 |
run App.new
|