-- Copyright (C) 2009 Diego Souza <dsouza at bitforest dot org>
-- 
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- 
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU Lesser General Public License for more details.
-- 
-- You should have received a copy of the GNU Lesser General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

-- | Implements PLAINTEXT and HMAC-SHA1 signatures of oauth spec <http://oauth.net/core/1.0a#signing_process>
module Network.Protocol.OAuth.Signature (Method(..),Signer,sign) where

import qualified Network.Protocol.OAuth.Request as R
import qualified Data.Digest.Pure.SHA  as S
import qualified Data.Char as C
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B1
import qualified Codec.Binary.Base64.String as B2

-- | The signature method which will be used to sign requests.
data Method =   
    {-| The 'PLAINTEXT' method does not provide any security protection and
        SHOULD only be used over a secure channel such as /HTTPS/. It does
        not use the Signature Base String.
    -}
    PLAINTEXT 
    {-| The 'HMAC_SHA1' signature method uses the /HMAC-SHA1/ signature
        algorithm as defined in <http://tools.ietf.org/html/rfc2104> where
        the Signature Base String is the text and the key is the
        concatenated values (each first encoded per Parameter Encoding) of
        the Consumer Secret and Token Secret, separated by an /&/ character
        (ASCII code 38) even if empty.
    -}
  | HMAC_SHA1 
  deriving (Eq)

-- | Functions to sign requests according oauth spec.
class Signer a where
  {-| For a given request, this function is able sign it using the method
      specified. The full description of this process is described in depth
      at <http://oauth.net/core/1.0a#signing_process>.
  -}
  sign :: a                -- ^ The signature method to use
          -> String        -- ^ The consumer secret
          -> Maybe String  -- ^ The token secret
          -> R.Request 
          -> String        -- ^ The signature

instance Signer Method where
  sign PLAINTEXT k (Just s) _ = k ++ "&" ++ s
  sign PLAINTEXT k Nothing  _ = k ++ "&"

  sign HMAC_SHA1 k Nothing  r = let secret = B.concat [R.encodes k, _froms "&"]
                                in (B2.encode . B1.unpack . S.bytestringDigest . S.hmacSha1 secret . _basestr) r
  sign HMAC_SHA1 k (Just s) r = let secret = B.concat [R.encodes k, _froms "&", R.encodes s]
                                in (B2.encode . B1.unpack . S.bytestringDigest . S.hmacSha1 secret . _basestr) r

instance Show Method where
  showsPrec _ PLAINTEXT = showString "PLAINTEXT"
  showsPrec _ HMAC_SHA1 = showString "HMAC-SHA1"

instance Read Method where
  readsPrec _ ('P':'L':'A':'I':'N':'T':'E':'X':'T':r) = (PLAINTEXT,r) : []
  readsPrec _ ('H':'M':'A':'C':'-':'S':'H':'A':'1':r) = (HMAC_SHA1,r) : []
  readsPrec _ _                                       = []

_basestr :: R.Request -> B.ByteString
_basestr r = let endpoint' = (R.encodes . _endpoint) r
                 params'   = (R.encodes . _params) r
                 method'   = (R.encodes . show . R.method) r
             in B.concat [method', _froms "&", endpoint', _froms "&", params']

_endpoint :: R.Request -> String
_endpoint r | R.ssl r   = ssl_endpoint'
            | otherwise = endpoint'
  where
    host' = (map C.toLower . R.host) r

    port' = ((':':) . show . R.port) r

    ssl_endpoint' | R.port r == 443 = "https://" ++ host' ++ (R.path r)
                  | otherwise       = "https://" ++ host' ++ port' ++ (R.path r)

    endpoint'     | R.port r == 80  = "http://" ++ host' ++ (R.path r)
                  | otherwise       = "http://" ++ host' ++ port' ++ (R.path r)

_params :: R.Request -> String
_params = map (C.chr . fromIntegral) . B.unpack . R.show_urlencoded . R.params

_froms :: String -> B.ByteString
_froms = B.pack . map (fromIntegral . C.ord)