Skip to content

Instantly share code, notes, and snippets.

@masterkain
Forked from lucasmazza/lastfm.rb
Created May 27, 2011 22:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masterkain/996316 to your computer and use it in GitHub Desktop.
Save masterkain/996316 to your computer and use it in GitHub Desktop.
a Last.FM Strategy for OmniAuth
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