-- Copyright (c) 2009, Diego Souza
-- All rights reserved.
-- 
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- 
--   * Redistributions of source code must retain the above copyright notice,
--     this list of conditions and the following disclaimer.
--   * Redistributions in binary form must reproduce the above copyright notice,
--     this list of conditions and the following disclaimer in the documentation
--     and/or other materials provided with the distribution.
--   * Neither the name of the <ORGANIZATION> nor the names of its contributors
--     may be used to endorse or promote products derived from this software
--     without specific prior written permission.
-- 
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-- | 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)