From a1ff864b4edf0c12bed9065e33b73c24dd7c7c09 Mon Sep 17 00:00:00 2001 From: Paul Harper Date: Sat, 20 Sep 2014 23:52:23 -0700 Subject: [PATCH] Added Spotify as a supported OAuth2 backend --- Yesod/Auth/OAuth2/Spotify.hs | 61 ++++++++++++++++++++++++++++++++++++ yesod-auth-oauth2.cabal | 1 + 2 files changed, 62 insertions(+) create mode 100644 Yesod/Auth/OAuth2/Spotify.hs diff --git a/Yesod/Auth/OAuth2/Spotify.hs b/Yesod/Auth/OAuth2/Spotify.hs new file mode 100644 index 0000000..107c740 --- /dev/null +++ b/Yesod/Auth/OAuth2/Spotify.hs @@ -0,0 +1,61 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Yesod.Auth.OAuth2.Spotify + ( oauth2Spotify + , module Yesod.Auth.OAuth2 + ) where + +import Control.Applicative ((<$>), (<*>)) +import Control.Exception.Lifted +import Control.Monad (mzero) +import Data.Aeson +import Data.Text (Text) +import Data.ByteString (ByteString) +import Data.Text.Encoding (encodeUtf8) +import Network.HTTP.Conduit(Manager) +import Yesod.Auth +import Yesod.Auth.OAuth2 + +data SpotifyUser = SpotifyUser + { spotifyUserId :: Text + , spotifyUserHref :: Text + , spotifyUserDisplayName :: Text + , spotifyProduct :: Text + } + +instance FromJSON SpotifyUser where + parseJSON (Object v) = SpotifyUser <$> + v .: "id" <*> + v .: "href" <*> + v .: "display_name" <*> + v .: "product" + parseJSON _ = mzero + +oauth2Spotify :: YesodAuth m + => Text -- ^ Client ID + -> Text -- ^ Client Secret + -> AuthPlugin m +oauth2Spotify clientId clientSecret = authOAuth2 "spotify" + (OAuth2 + { oauthClientId = encodeUtf8 clientId + , oauthClientSecret = encodeUtf8 clientSecret + , oauthOAuthorizeEndpoint = "https://accounts.spotify.com/authorize" + , oauthAccessTokenEndpoint = "https://accounts.spotify.com/api/token" + , oauthCallback = Nothing + }) + fetchSpotifyProfile + +fetchSpotifyProfile :: Manager -> AccessToken -> IO (Creds m) +fetchSpotifyProfile manager token = do + result <- authGetJSON manager token "https://api.spotify.com/v1/me" + case result of + Right user -> return $ toCreds user + Left err -> throwIO $ InvalidProfileResponse "spotify" err + +toCreds :: SpotifyUser -> Creds m +toCreds user = Creds "spotify" + (spotifyUserId user) + [ ("href" , spotifyUserHref user) + , ("display_name", spotifyUserDisplayName user) + , ("product" , spotifyProduct user) + ] diff --git a/yesod-auth-oauth2.cabal b/yesod-auth-oauth2.cabal index 744e547..65d3cf9 100644 --- a/yesod-auth-oauth2.cabal +++ b/yesod-auth-oauth2.cabal @@ -48,6 +48,7 @@ library Yesod.Auth.OAuth2.Google Yesod.Auth.OAuth2.Learn Yesod.Auth.OAuth2.Github + Yesod.Auth.OAuth2.Spotify ghc-options: -Wall