This repository has been archived by the owner on Oct 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
/
Swagger.hs
87 lines (74 loc) · 2.55 KB
/
Swagger.hs
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
module Servant.Auth.Swagger
(
-- | The purpose of this package is provide the instance for 'servant-auth'
-- combinators needed for 'servant-swagger' documentation generation.
--
-- Currently only JWT and BasicAuth are supported.
-- * Re-export
JWT
, BasicAuth
, Auth
-- * Needed to define instances of @HasSwagger@
, HasSecurity (..)
) where
import Control.Lens ((&), (<>~))
import Data.Proxy (Proxy (Proxy))
import Data.Swagger (ApiKeyLocation (..), ApiKeyParams (..),
SecurityRequirement (..), SecurityScheme (..),
#if MIN_VERSION_swagger2(2,6,0)
SecurityDefinitions(..),
#endif
SecuritySchemeType (..), allOperations, security,
securityDefinitions)
import GHC.Exts (fromList)
import Servant.API hiding (BasicAuth)
import Servant.Auth
import Servant.Swagger
import qualified Data.Text as T
instance (AllHasSecurity xs, HasSwagger api) => HasSwagger (Auth xs r :> api) where
toSwagger _
= toSwagger (Proxy :: Proxy api)
& securityDefinitions <>~ mkSec (fromList secs)
& allOperations.security <>~ secReqs
where
secs = securities (Proxy :: Proxy xs)
secReqs = [ SecurityRequirement (fromList [(s,[])]) | (s,_) <- secs]
mkSec =
#if MIN_VERSION_swagger2(2,6,0)
SecurityDefinitions
#else
id
#endif
class HasSecurity x where
securityName :: Proxy x -> T.Text
securityScheme :: Proxy x -> SecurityScheme
instance HasSecurity BasicAuth where
securityName _ = "BasicAuth"
securityScheme _ = SecurityScheme type_ (Just desc)
where
type_ = SecuritySchemeBasic
desc = "Basic access authentication"
instance HasSecurity JWT where
securityName _ = "JwtSecurity"
securityScheme _ = SecurityScheme type_ (Just desc)
where
type_ = SecuritySchemeApiKey (ApiKeyParams "Authorization" ApiKeyHeader)
desc = "JSON Web Token-based API key"
class AllHasSecurity (x :: [*]) where
securities :: Proxy x -> [(T.Text,SecurityScheme)]
instance {-# OVERLAPPABLE #-} (HasSecurity x, AllHasSecurity xs) => AllHasSecurity (x ': xs) where
securities _ = (securityName px, securityScheme px) : securities pxs
where
px :: Proxy x
px = Proxy
pxs :: Proxy xs
pxs = Proxy
instance {-# OVERLAPPING #-} AllHasSecurity xs => AllHasSecurity (Cookie ': xs) where
securities _ = securities pxs
where
pxs :: Proxy xs
pxs = Proxy
instance AllHasSecurity '[] where
securities _ = []