[amscotti@128bit.io ~/posts]# cat linkedin-authentication-with-sinatra.md _
# LinkedIn authentication with Sinatra
- November 25, 2011 | 2 min read

To take the authentication with Sinatra a bit farther you may want to use another service to do your authentication against. This is some sample code adapted from a Rails example. This code takes use of the linkedin gem from Wynn Netherland to do the authentication and also make some calls to the LinkedIn API. There are other gems that just do authentication for many services like Facebook and Twitter but for this sample I wanted to be able to make additional calls to the LinkedIn API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
require "rubygems"
require "haml"
require "sinatra"
require "linkedin"

enable :sessions

helpers do
  def login?
    if session[:atoken].nil?
      return false
    else
      return true
    end
  end

  def profile
    unless session[:atoken].nil?
      client = LinkedIn::Client.new(settings.api, settings.secret)
      client.authorize_from_access(session[:atoken], session[:asecret])
      return client.profile
    end
  end

  def connections
    unless session[:atoken].nil?
      client = LinkedIn::Client.new(settings.api, settings.secret)
      client.authorize_from_access(session[:atoken], session[:asecret])
      return client.connections
    end
  end

end

configure do
  # get your api keys at https://www.linkedin.com/secure/developer
  set :api, "your_api_key"
  set :secret, "your_secret"
end

get "/" do
  haml :index
end

get "/auth" do
  client = LinkedIn::Client.new(settings.api, settings.secret)
  request_token = client.request_token(:oauth_callback => "http://#{request.host}:#{request.port}/auth/callback")
  session[:rtoken] = request_token.token
  session[:rsecret] = request_token.secret

  redirect client.request_token.authorize_url
end

get "/auth/logout" do
   session[:atoken] = nil
   redirect "/"
end

get "/auth/callback" do
  client = LinkedIn::Client.new(settings.api, settings.secret)
  if session[:atoken].nil?
    pin = params[:oauth_verifier]
    atoken, asecret = client.authorize_from_request(session[:rtoken], session[:rsecret], pin)
    session[:atoken] = atoken
    session[:asecret] = asecret
  end
  redirect "/"
end


__END__
@@index
-if login?
  %p Welcome #{profile.first_name}!
  %a{:href => "/auth/logout"} Logout
  %p= profile.headline
  %br
  %div= "You have #{connections.total} connections!"
  -connections.all.each do |c|
    %div= "#{c.first_name} #{c.last_name} - #{c.headline}"
-else
  %a{:href => "/auth"} Login using LinkedIn

If you know of any way to make this code better please comment or fork the Gist.