module Facebook.Auth
( getAppAccessToken
, getUserAccessTokenStep1
, getUserAccessTokenStep2
, getUserLogoutUrl
, extendUserAccessToken
, RedirectUrl
, Permission
, hasExpired
, isValid
) where
import Control.Applicative
import Control.Monad (join)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.Aeson ((.:))
import Data.Aeson.Types (parseEither)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Time (getCurrentTime, addUTCTime, UTCTime)
import Data.String (IsString(..))
import qualified Control.Exception.Lifted as E
import qualified Data.Attoparsec.Char8 as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.Conduit as C
import qualified Data.Conduit.Attoparsec as C
import qualified Data.List as L
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Encoding.Error as TE
import qualified Network.HTTP.Conduit as H
import qualified Network.HTTP.Types as HT
import Facebook.Types
import Facebook.Base
import Facebook.Monad
getAppAccessToken :: C.ResourceIO m =>
FacebookT Auth m AppAccessToken
getAppAccessToken =
runResourceInFb $ do
creds <- getCreds
let req = fbreq "/oauth/access_token" Nothing $
tsq creds [("grant_type", "client_credentials")]
response <- fbhttp req
lift $
H.responseBody response C.$$
C.sinkParser (AppAccessToken <$ A.string "access_token="
<*> A.takeByteString)
getUserAccessTokenStep1 :: Credentials
-> RedirectUrl
-> [Permission]
-> Text
getUserAccessTokenStep1 creds redirectUrl perms =
T.concat $ "https://www.facebook.com/dialog/oauth?client_id="
: TE.decodeUtf8 (appId creds)
: "&redirect_uri="
: redirectUrl
: (case perms of
[] -> []
_ -> "&scope=" : L.intersperse "," (map unPermission perms)
)
getUserAccessTokenStep2 :: C.ResourceIO m =>
RedirectUrl
-> [Argument]
-> FacebookT Auth m UserAccessToken
getUserAccessTokenStep2 redirectUrl query =
case query of
[code@("code", _)] -> runResourceInFb $ do
now <- liftIO getCurrentTime
creds <- getCreds
let req = fbreq "/oauth/access_token" Nothing $
tsq creds [code, ("redirect_uri", TE.encodeUtf8 redirectUrl)]
preToken <- fmap (userAccessTokenParser now) . asBS =<< fbhttp req
userInfo <- asJson =<< fbhttp (fbreq "/me" (Just preToken) [("fields", "id")])
case (parseEither (.: "id") userInfo, preToken) of
(Left str, _) ->
E.throw $ FbLibraryException $ T.concat
[ "getUserAccessTokenStep2: failed to get the UserId ("
, T.pack str, ")" ]
(Right (userId :: UserId), UserAccessToken _ d e) ->
return (UserAccessToken userId d e)
_ -> let [error_, errorReason, errorDescr] =
map (fromMaybe "" . flip lookup query)
["error", "error_reason", "error_description"]
errorType = T.concat [t error_, " (", t errorReason, ")"]
t = TE.decodeUtf8With TE.lenientDecode
in E.throw $ FacebookException errorType (t errorDescr)
userAccessTokenParser :: UTCTime
-> B.ByteString
-> UserAccessToken
userAccessTokenParser now bs =
let q = HT.parseQuery bs; lookup' a = join (lookup a q)
in case (,) <$> lookup' "access_token" <*> lookup' "expires" of
(Just (tok, expt)) -> UserAccessToken userId tok (toExpire expt)
_ -> error $ "userAccessTokenParser: failed to parse " ++ show bs
where toExpire expt = let i = read (B8.unpack expt) :: Int
in addUTCTime (fromIntegral i) now
userId = error "userAccessTokenParser: never here"
getUserLogoutUrl :: UserAccessToken
-> RedirectUrl
-> Text
getUserLogoutUrl (UserAccessToken _ data_ _) next =
TE.decodeUtf8 $
"https://www.facebook.com/logout.php?" <>
HT.renderQuery False [ ("next", Just (TE.encodeUtf8 next))
, ("access_token", Just data_) ]
type RedirectUrl = Text
newtype Permission = Permission { unPermission :: Text }
instance Show Permission where
show = show . unPermission
instance IsString Permission where
fromString = Permission . fromString
hasExpired :: (Functor m, MonadIO m) => AccessToken anyKind -> m Bool
hasExpired token =
case accessTokenExpires token of
Nothing -> return False
Just expTime -> (>= expTime) <$> liftIO getCurrentTime
isValid :: C.ResourceIO m =>
AccessToken anyKind
-> FacebookT anyAuth m Bool
isValid token = do
expired <- hasExpired token
if expired
then return False
else
let page = case token of
UserAccessToken _ _ _ -> "/me"
AppAccessToken _ -> "/19292868552"
in httpCheck (fbreq page (Just token) [])
extendUserAccessToken ::
C.ResourceIO m =>
UserAccessToken
-> FacebookT Auth m (Either FacebookException UserAccessToken)
extendUserAccessToken token@(UserAccessToken _ data_ _)
= do expired <- hasExpired token
if expired then return (Left hasExpiredExc) else tryToExtend
where
tryToExtend = runResourceInFb $ do
creds <- getCreds
let req = fbreq "/oauth/access_token" Nothing $
tsq creds [ ("grant_type", "fb_exchange_token")
, ("fb_exchange_token", data_) ]
eresponse <- E.try (asBS =<< fbhttp req)
case eresponse of
Right response -> do
now <- liftIO getCurrentTime
return (Right $ userAccessTokenParser now response)
Left exc -> return (Left exc)
hasExpiredExc =
mkExc [ "the user access token has already expired, "
, "so I'll not try to extend it." ]
mkExc = FbLibraryException . T.concat . ("extendUserAccessToken: ":)