vendredi 31 juillet 2015

Oauth with sinatra.

So I have been learning how to program over the last couple of months. Prior to 2 months ago I didn't know anything. So that you know where I am at I feel comfortable with JS/ruby, ajax, sinatra, and building a full CRUD application and I've mainly used bootstrap for front end. I feel that I understand the process of oauth from (client_id, client_secret, callback, tokens, etc). I was wondering if someone could give me a breakdown of what is happening here in this code. From the view, controller (routes), and the before helper method. I'm not too sure how net/http is working. Any help would be appreciated.

require "rubygems"
require "sinatra"

require "net/http"
require "net/https"
require "cgi"

require "json"

enable :sessions

before do
  @client_id = "YOUR-CLIENT-ID-HERE"
  @client_secret = "YOUR-CLIENT-SECRET-HERE"

  session[:oauth] ||= {}
end

get "/" do
  if session[:oauth][:access_token].nil?
    erb :start
  else
    http = Net::HTTP.new "graph.facebook.com", 443
    request = Net::HTTP::Get.new "/me?access_token=#{session[:oauth][:access_token]}"
    http.use_ssl = true
    response = http.request request
    @json = JSON.parse(response.body)

    erb :ready
  end
end

get "/request" do
  redirect "http://ift.tt/1DXil2B"
end

get "/callback" do
  session[:oauth][:code] = params[:code]

  http = Net::HTTP.new "graph.facebook.com", 443
  request = Net::HTTP::Get.new "/oauth/access_token?client_id=#{@client_id}&redirect_uri=http://localhost:4567/callback&client_secret=#{@client_secret}&code=#{session[:oauth][:code]}"
  http.use_ssl = true
  response = http.request request

  session[:oauth][:access_token] = CGI.parse(response.body)["access_token"][0]
  redirect "/"
end

get "/logout" do
  session[:oauth] = {}
  redirect "/"
end

enable :inline_templates

__END__

@@ start
<a href="/request">Let's see who you are</a>.

@@ ready
<img style="padding: 20px" src="http://ift.tt/1DXiinb @json["id"] %>/picture" />
<br />
Hello, <%= @json["name"] %>! <a href="/logout">Logout</a>.

Aucun commentaire:

Enregistrer un commentaire