-
Notifications
You must be signed in to change notification settings - Fork 606
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #28 from rafaelsq/lastfm
Add provider for LastFM
- Loading branch information
Showing
6 changed files
with
365 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -26,6 +26,7 @@ $ go get github.com/markbates/goth | |
* Google+ | ||
* Spotify | ||
* Lastfm | ||
|
||
## Examples | ||
|
||
|
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,211 @@ | ||
// Package lastfm implements the OAuth protocol for authenticating users through LastFM. | ||
// This package can be used as a reference impleentation of an OAuth provider for Goth. | ||
package lastfm | ||
|
||
import ( | ||
"crypto/md5" | ||
"encoding/hex" | ||
"encoding/json" | ||
"encoding/xml" | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
"net/url" | ||
"errors" | ||
"sort" | ||
"strings" | ||
|
||
"github.com/markbates/goth" | ||
) | ||
|
||
|
||
var ( | ||
authURL = "http://www.lastfm.com.br/api/auth" | ||
endpointProfile = "http://ws.audioscrobbler.com/2.0/" | ||
) | ||
|
||
|
||
// New creates a new LastFM provider, and sets up important connection details. | ||
// You should always call `lastfm.New` to get a new Provider. Never try to craete | ||
// one manullay. | ||
func New(clientKey string, secret string, callbackURL string) *Provider { | ||
p := &Provider{ | ||
ClientKey: clientKey, | ||
Secret: secret, | ||
CallbackURL: callbackURL, | ||
} | ||
return p | ||
} | ||
|
||
|
||
// Provider is the implementation of `goth.Provider` for accessing LastFM | ||
type Provider struct { | ||
ClientKey string | ||
Secret string | ||
CallbackURL string | ||
UserAgent string | ||
} | ||
|
||
// Name is the name used to retrive this provider later. | ||
func (p *Provider) Name() string { | ||
return "lastfm" | ||
} | ||
|
||
// | ||
func (p *Provider) Debug(debug bool) {} | ||
|
||
// BeginAuth asks LastFm for an authentication end-point | ||
func (p *Provider) BeginAuth(state string) (goth.Session, error) { | ||
urlParams := url.Values{} | ||
urlParams.Add("api_key", p.ClientKey) | ||
urlParams.Add("callback", p.CallbackURL) | ||
|
||
session := &Session{ | ||
AuthURL: authURL + "?" + urlParams.Encode(), | ||
} | ||
|
||
return session, nil | ||
} | ||
|
||
|
||
// FetchUser will go to LastFM and access basic information about the user. | ||
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { | ||
user := goth.User{} | ||
|
||
u := struct { | ||
XMLName xml.Name `xml:"user"` | ||
Id string `xml:"id"` | ||
Name string `xml:"name"` | ||
RealName string `xml:"realname"` | ||
Url string `xml:"url"` | ||
Country string `xml:"country"` | ||
Age string `xml:"age"` | ||
Gender string `xml:"gender"` | ||
Subscriber string `xml:"subscriber"` | ||
PlayCount string `xml:"playcount"` | ||
Playlists string `xml:"playlists"` | ||
Bootstrap string `xml:"bootstrap"` | ||
Registered struct { | ||
Unixtime string `xml:"unixtime,attr"` | ||
Time string `xml:",chardata"` | ||
} `xml:"registered"` | ||
Images []struct { | ||
Size string `xml:"size,attr"` | ||
Url string `xml:",chardata"` | ||
} `xml:"image"` | ||
}{} | ||
|
||
login := session.(*Session).Login | ||
err := p.request(false, map[string]string{"method": "user.getinfo", "user": login}, &u) | ||
|
||
if err == nil { | ||
user.Name = u.RealName | ||
user.NickName = u.Name | ||
user.AvatarURL = u.Images[3].Url | ||
user.UserID = u.Id | ||
user.Location = u.Country | ||
} | ||
|
||
return user, err | ||
} | ||
|
||
// UnmarshalSession will unmarshal a JSON string into a session. | ||
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { | ||
sess := &Session{} | ||
err := json.NewDecoder(strings.NewReader(data)).Decode(sess) | ||
return sess, err | ||
} | ||
|
||
// GetSession token from LastFM | ||
func (p *Provider) GetSession(token string) (map[string]string, error) { | ||
sess := struct { | ||
Name string `xml:"name"` | ||
Key string `xml:"key"` | ||
Subscriber bool `xml:"subscriber"` | ||
}{} | ||
|
||
err := p.request(true, map[string]string{"method": "auth.getSession", "token": token}, &sess) | ||
return map[string]string{"login": sess.Name, "token": sess.Key}, err | ||
} | ||
|
||
func (p *Provider) request(sign bool, params map[string]string, result interface{}) error { | ||
urlParams := url.Values{} | ||
urlParams.Add("method", params["method"]) | ||
|
||
params["api_key"] = p.ClientKey | ||
for k, v := range params { | ||
urlParams.Add(k, v) | ||
} | ||
|
||
if sign { | ||
urlParams.Add("api_sig", signRequest(p.Secret, params)) | ||
} | ||
|
||
uri := endpointProfile + "?"+ urlParams.Encode() | ||
|
||
client := &http.Client{} | ||
req, err := http.NewRequest("GET", uri, nil) | ||
if err != nil { | ||
return err | ||
} | ||
req.Header.Set("User-Agent", p.UserAgent) | ||
|
||
res, err := client.Do(req) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if res.StatusCode/100 == 5 { // only 5xx class errros | ||
err = errors.New(fmt.Sprintf("Request error(%v) %v", res.StatusCode, res.Status)) | ||
return err | ||
} | ||
body, err := ioutil.ReadAll(res.Body) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
base := struct{ | ||
XMLName xml.Name `xml:"lfm"` | ||
Status string `xml:"status,attr"` | ||
Inner []byte `xml:",innerxml"` | ||
}{} | ||
|
||
err = xml.Unmarshal(body, &base) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if base.Status != "ok" { | ||
errorDetail := struct { | ||
Code int `xml:"code,attr"` | ||
Message string `xml:",chardata"` | ||
}{} | ||
|
||
err = xml.Unmarshal(base.Inner, &errorDetail) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return errors.New(fmt.Sprintf("Request Error(%v): %v", errorDetail.Code, errorDetail.Message)) | ||
} | ||
|
||
return xml.Unmarshal(base.Inner, result) | ||
} | ||
|
||
func signRequest(secret string, params map[string]string) string { | ||
var keys []string | ||
for k := range params { | ||
keys = append(keys, k) | ||
} | ||
sort.Strings(keys) | ||
|
||
var sigPlain string | ||
for _, k := range keys { | ||
sigPlain += k + params[k] | ||
} | ||
sigPlain += secret | ||
|
||
hasher := md5.New() | ||
hasher.Write([]byte(sigPlain)) | ||
return hex.EncodeToString(hasher.Sum(nil)) | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
package lastfm | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"testing" | ||
"net/url" | ||
|
||
"github.com/markbates/goth" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func Test_New(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
|
||
provider := lastfmProvider() | ||
a.Equal(provider.ClientKey, os.Getenv("LASTFM_KEY")) | ||
a.Equal(provider.Secret, os.Getenv("LASTFM_SECRET")) | ||
a.Equal(provider.CallbackURL, "/foo") | ||
} | ||
|
||
func Test_Implements_Provider(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
|
||
a.Implements((*goth.Provider)(nil), lastfmProvider()) | ||
} | ||
|
||
func Test_BeginAuth(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
|
||
provider := lastfmProvider() | ||
session, err := provider.BeginAuth("") | ||
s := session.(*Session) | ||
a.NoError(err) | ||
a.Contains(s.AuthURL, "www.lastfm.com.br/api/auth") | ||
a.Contains(s.AuthURL, fmt.Sprintf("api_key=%s", os.Getenv("LASTFM_KEY"))) | ||
a.Contains(s.AuthURL, fmt.Sprintf("callback=%s", url.QueryEscape("/foo"))) | ||
} | ||
|
||
func Test_SessionFromJSON(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
|
||
provider := lastfmProvider() | ||
|
||
s, err := provider.UnmarshalSession(`{"AuthURL":"http://com/auth_url","AccessToken":"123456", "Login":"Quin"}`) | ||
a.NoError(err) | ||
session := s.(*Session) | ||
a.Equal(session.AuthURL, "http://com/auth_url") | ||
a.Equal(session.AccessToken, "123456") | ||
a.Equal(session.Login, "Quin") | ||
} | ||
|
||
func lastfmProvider() *Provider { | ||
return New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "/foo") | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package lastfm | ||
|
||
import ( | ||
"encoding/json" | ||
"errors" | ||
|
||
"github.com/markbates/goth" | ||
) | ||
|
||
// Session stores data during the auth process with Lastfm. | ||
type Session struct { | ||
AuthURL string | ||
AccessToken string | ||
Login string | ||
} | ||
|
||
// GetAuthURL will return the URL set by calling the `BeginAuth` function on the LastFM provider. | ||
func (s Session) GetAuthURL() (string, error) { | ||
if s.AuthURL == "" { | ||
return "", errors.New("an AuthURL has not be set") | ||
} | ||
return s.AuthURL, nil | ||
} | ||
|
||
// Authorize the session with LastFM and return the access token to be stored for future use. | ||
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { | ||
p := provider.(*Provider) | ||
sess, err := p.GetSession(params.Get("token")) | ||
if err != nil { | ||
return "", err | ||
} | ||
s.Login = sess["login"] | ||
return sess["token"], err | ||
} | ||
|
||
// Marshal the session into a string | ||
func (s Session) Marshal() string { | ||
b, _ := json.Marshal(s) | ||
return string(b) | ||
} | ||
|
||
func (s Session) String() string { | ||
return s.Marshal() | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package lastfm | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/markbates/goth" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func Test_Implements_Session(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &Session{} | ||
|
||
a.Implements((*goth.Session)(nil), s) | ||
} | ||
|
||
func Test_GetAuthURL(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &Session{} | ||
|
||
_, err := s.GetAuthURL() | ||
a.Error(err) | ||
|
||
s.AuthURL = "/foo" | ||
|
||
url, _ := s.GetAuthURL() | ||
a.Equal(url, "/foo") | ||
} | ||
|
||
func Test_ToJSON(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &Session{} | ||
|
||
data := s.Marshal() | ||
a.Equal(data, `{"AuthURL":"","AccessToken":"","Login":""}`) | ||
} | ||
|
||
func Test_String(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &Session{} | ||
|
||
a.Equal(s.String(), s.Marshal()) | ||
} |