-
-
Save masterkain/996316 to your computer and use it in GitHub Desktop.
a Last.FM Strategy for OmniAuth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'omniauth/core' | |
require 'digest/md5' | |
require 'rest-client' | |
require 'multi_json' | |
module OmniAuth | |
module Strategies | |
class Lastfm | |
include OmniAuth::Strategy | |
attr_accessor :api_key, :secret_key, :options | |
def initialize(app, api_key, secret_key, options = {}) | |
super(app, :lastfm) | |
@api_key = api_key | |
@secret_key = secret_key | |
@options = options | |
end | |
def request_phase | |
params = { :api_key => api_key } | |
query_string = params.map{ |key,value| "#{key}=#{Rack::Utils.escape(value)}" }.join('&') | |
redirect "http://www.last.fm/api/auth/?#{query_string}" | |
end | |
def callback_phase | |
token = request.params['token'] | |
params = { :api_key => api_key } | |
params[:token] = token | |
params[:api_sig] = signature(token) | |
params[:method] = "auth.getSession" | |
params[:format] = "json" | |
response = RestClient.get('http://ws.audioscrobbler.com/2.0/', { :params => params }) | |
@json = MultiJson.decode(response.to_s) | |
extra_params = { :method => "user.getInfo", :user => @json['session']['name'], :api_key => api_key, :format => "json" } | |
extra_response = RestClient.get('http://ws.audioscrobbler.com/2.0/', { :params => extra_params }) | |
@extra_json = MultiJson.decode(extra_response.to_s) | |
super | |
end | |
def user_info | |
{ | |
'name' => @extra_json['user']['realname'], | |
'nickname' => @extra_json['user']['name'], | |
'location' => @extra_json['user']['country'], | |
'image' => @extra_json['user']['image'], | |
'urls' => { | |
'Profile' => @extra_json['user']['url'] | |
} | |
} | |
end | |
def auth_hash | |
OmniAuth::Utils.deep_merge(super, { | |
'uid' => @extra_json['user']['id'], | |
'user_info' => user_info, | |
'extra' => { | |
'user_hash' => @extra_json['user'] | |
}, | |
'credentials' => { | |
'token' => @json['session']['key'] | |
} | |
}) | |
end | |
protected | |
def signature(token) | |
sign = "api_key#{api_key}methodauth.getSessiontoken#{token}#{secret_key}" | |
Digest::MD5.hexdigest(sign) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment