-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathAuth.hs
More file actions
58 lines (48 loc) · 1.87 KB
/
Auth.hs
File metadata and controls
58 lines (48 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module GitHub.Auth (
Auth (..),
Token,
JWTToken,
AuthMethod,
endpoint,
setAuthRequest
) where
import GitHub.Internal.Prelude
import Prelude ()
import qualified Data.ByteString as BS
import qualified Data.Text.Encoding as TE
import qualified Network.HTTP.Client as HTTP
type Token = BS.ByteString
type JWTToken = Text
-- | The Github auth data type
data Auth
= BasicAuth BS.ByteString BS.ByteString -- ^ Username and password
| OAuth Token -- ^ OAuth token
| JWT JWTToken -- ^ JWT Token
| EnterpriseOAuth Text Token -- ^ Custom endpoint and OAuth token
deriving (Show, Data, Eq, Ord, Generic)
instance NFData Auth
instance Binary Auth
instance Hashable Auth
-- | A type class for different authentication methods
--
-- Note the '()' intance, which doee nothing, i.e. is unauthenticated.
class AuthMethod a where
-- | Custom API endpoint without trailing slash
endpoint :: a -> Maybe Text
-- | A function which sets authorisation on an HTTP request
setAuthRequest :: a -> HTTP.Request -> HTTP.Request
instance AuthMethod () where
endpoint _ = Nothing
setAuthRequest _ = id
instance AuthMethod Auth where
endpoint (BasicAuth _ _) = Nothing
endpoint (OAuth _) = Nothing
endpoint (JWT _) = Nothing
endpoint (EnterpriseOAuth e _) = Just e
setAuthRequest (BasicAuth u p) = HTTP.applyBasicAuth u p
setAuthRequest (OAuth t) = setAuthHeader $ "token " <> t
setAuthRequest (JWT t) = setAuthHeader $ "Bearer " <> TE.encodeUtf8 t
setAuthRequest (EnterpriseOAuth _ t) = setAuthHeader $ "token " <> t
setAuthHeader :: BS.ByteString -> HTTP.Request -> HTTP.Request
setAuthHeader auth req =
req { HTTP.requestHeaders = ("Authorization", auth) : HTTP.requestHeaders req }