Skip to content

Instantly share code, notes, and snippets.

@peterkappus
Created June 21, 2016 21:39
Show Gist options
  • Save peterkappus/49f492dd6481db33a71db92fbebf75ef to your computer and use it in GitHub Desktop.
Save peterkappus/49f492dd6481db33a71db92fbebf75ef to your computer and use it in GitHub Desktop.
A demo WeekDone omniauth strategy and REST client in a sinatra app.
require 'sinatra'
#require 'pry'
require 'omniauth-oauth2'
require 'omniauth'
module OmniAuth
module Strategies
class WeekDone < OmniAuth::Strategies::OAuth2
# Give your strategy a name.
option :name, "weekdone"
# This is where you pass the options you would pass when
# initializing your consumer from the OAuth gem.
option :client_options, {
:site => "https://weekdone.com/",
:redirect_uri =>"http://localhost:9393/auth/weekdone/callback",
:authorize_url => "https://weekdone.com/oauth_authorize",
:token_url => "https://weekdone.com/oauth_token"}
#strip out any query params
def callback_url
full_host + script_name + callback_path
end
# These are called after authentication has succeeded. If
# possible, you should try to set the UID without making
# additional calls (if the user id is returned with the token
# or as a URI parameter). This may not be possible with all
# providers.
uid{ raw_info['id'] }
info do
{
:name => raw_info['name'],
:email => raw_info['email']
}
end
extra do
{
'raw_info' => raw_info
}
end
def raw_info
@raw_info ||= access_token.params['user']
end
end
end
end
class WeekDoneClient
require 'rest-client'
# Initializes a new client object
#
# @param token [String] The auth token
# @return WeekDoneClient
def initialize(token)
@token = token
end
# Get all tags
#
# @return [Hash] Tag names mapped to IDs (for easy scanning)
def tags
tag_hash = {}
JSON.parse(RestClient.get "https://api.weekdone.com/1/tag", {:params => {:token=>@token}})['tags'].map{|tag| tag_hash[tag['tag']] = tag['id']}
tag_hash
end
# Get all users
#
# @return [Array]
def users
JSON.parse(RestClient.get "https://api.weekdone.com/1/users", {:params => {:token=>@token}})['users']
end
end
use Rack::Session::Cookie
#use OmniAuth::Strategies::Developer
#use OmniAuth::Strategies::WeekDone
use OmniAuth::Builder do
provider :WeekDone, "<YOUR_CLIENT_ID>","<YOUR_CLIENT_SECRET>"
end
use Rack::Session::Cookie, secret: 'abcdefg-Peter-Kappus'
enable :sessions
get '/auth/weekdone/callback' do
session['token'] = request.env['omniauth.auth']['credentials']['token'].to_s
"<h1>Hello! " + request.env['omniauth.auth']['info']['name'] + "</h1>" + "<h2>Tags:</h2> <h3> " + WeekDoneClient.new(session['token']).tags.keys.to_s + "</h3> <h2> Users: </h2> <h3> " + WeekDoneClient.new(session['token']).users.map{|u| u['name']}.to_s + "</h3>"
end
get '/tags' do
WeekDoneClient.new(session['token']).tags.keys.to_s
end
get '/' do
redirect to('/auth/weekdone')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment