moved google oauth stuff into a mixin and removed unnecesary serialisation to the session

This commit is contained in:
Mark Ryall
2012-11-20 00:40:16 +11:00
parent 5515df166b
commit e64f89c470
3 changed files with 39 additions and 21 deletions
+4 -17
View File
@@ -1,9 +1,11 @@
require 'persona'
require 'google_oauth'
require 'net/http'
require 'google_api_ext'
class HomeController < ApplicationController
include Persona
include GoogleOauth
skip_filter :require_login, only: [:index, :verify, :verify_g, :verify_g_callback]
@@ -30,26 +32,11 @@ class HomeController < ApplicationController
end
def verify_g
@client = Google::APIClient.build
url = @client.authorization.authorization_uri.to_s
session[:google_auth] = @client.to_yaml
redirect_to url
redirect_to google_oauth_url
end
def verify_g_callback
google_auth = YAML.load(session[:google_auth])
google_auth.authorization.code = params[:code] if params[:code]
google_auth.authorization.fetch_access_token!
http = Net::HTTP.new 'www.googleapis.com', 443
http.use_ssl = true
response = http.get "/oauth2/v1/userinfo?access_token=#{google_auth.authorization.access_token}"
response = JSON.parse response.body
session[:email] = response['email']
verify_google_oauth { |email| session[:email] = email }
redirect_to '/'
end
end
+29
View File
@@ -0,0 +1,29 @@
require 'google/api_client'
module GoogleOauth
def google_oauth_url
google_client.authorization.authorization_uri.to_s
end
def verify_google_oauth
client = Google::APIClient.build
client.authorization.code = params[:code] if params[:code]
client.authorization.fetch_access_token!
http = Net::HTTP.new 'www.googleapis.com', 443
http.use_ssl = true
response = http.get "/oauth2/v1/userinfo?access_token=#{client.authorization.access_token}"
response = JSON.parse response.body
yield response['email']
end
def google_client
Google::APIClient.new.tap do |client|
client.authorization.scope = 'https://www.googleapis.com/auth/userinfo.email'
client.authorization.client_id = ::ENV['GOOGLE_OAUTH_CLIENT_ID']
client.authorization.client_secret = ::ENV['GOOGLE_OAUTH_CLIENT_SECRET']
client.authorization.redirect_uri = ::ENV['GOOGLE_OAUTH_REDIRECT']
end
end
end
@@ -1,7 +1,9 @@
require 'spec_helper'
require 'google_oauth'
describe Google::APIClient do
describe :build do
describe GoogleOauth do
include GoogleOauth
describe '#google_client' do
let(:authorization) { stub 'authorization' }
let(:client) { stub 'client', authorization: authorization }
before { Google::APIClient.should_receive(:new).and_return client }
@@ -17,7 +19,7 @@ describe Google::APIClient do
authorization.should_receive("#{m}=").with value
end
authorization.should_receive("scope=").with 'https://www.googleapis.com/auth/userinfo.email'
Google::APIClient.build
google_client
end
end
end