Skip to content

Instantly share code, notes, and snippets.

@chap
Created February 20, 2013 15:44
Show Gist options
  • Save chap/4996478 to your computer and use it in GitHub Desktop.
Save chap/4996478 to your computer and use it in GitHub Desktop.
Simple module for doing Oauth with google.
module Authable
extend ActiveSupport::Concern
OAUTH_CLIENT_ID = '123.apps.googleusercontent.com'
OAUTH_CLIENT_SECRET = '456'
OAUTH_BASE_URL = 'https://www.googleapis.com/oauth2/'
OAUTH_SCOPE = ['https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile']
module ClassMethods
def google_oauth_url(callback_url)
params = {
response_type: 'code',
client_id: OAUTH_CLIENT_ID,
scope: OAUTH_SCOPE.join('+'),
redirect_uri: callback_url
}
'https://accounts.google.com/o/oauth2/auth?' +
params.to_query.gsub('%2B','+') # google expects the + unescaped
end
def get_users_details(code, callback_url)
access_token = get_access_token(code,callback_url)
uri = URI.parse "#{OAUTH_BASE_URL}v1/userinfo?access_token=#{access_token}"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
JSON.parse(response.body)
end
private
def get_access_token(code, callback_url)
uri = URI.parse "#{OAUTH_BASE_URL}/token"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri, {'Content-Type' => 'application/x-www-form-urlencoded'})
request.body = {
code: code,
grant_type: 'authorization_code',
client_id: OAUTH_CLIENT_ID,
client_secret: OAUTH_CLIENT_SECRET,
redirect_uri: callback_url
}.to_query
response = http.request(request)
JSON.parse(response.body)['access_token']
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment