Merge pull request #344 from calebmer/feature/jwt-expire

Ensure JWT expires
This commit is contained in:
Joe Nelson
2015-11-11 08:31:20 -08:00
7 changed files with 64 additions and 31 deletions
+24 -17
View File
@@ -6,6 +6,7 @@ module PostgREST.Middleware where
import Data.Maybe (fromMaybe, isNothing)
import Data.Text
import Data.String.Conversions (cs)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Hasql as H
import qualified Hasql.Postgres as P
@@ -21,6 +22,8 @@ import PostgREST.App (contentTypeForAccept)
import PostgREST.Auth (setRole, jwtClaims, claimsToSQL)
import PostgREST.Config (AppConfig (..), corsPolicy)
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding(concat)
import qualified Data.Vector as V
@@ -31,23 +34,27 @@ runWithClaims :: forall s. AppConfig ->
(Request -> H.Tx P.Postgres s Response) ->
Request -> H.Tx P.Postgres s Response
runWithClaims conf app req = do
mapM_ H.unitEx $ stmt <$> env
app req
where
stmt = (flip $ flip B.Stmt V.empty) True
hdrs = requestHeaders req
jwtSecret = (cs $ configJwtSecret conf) :: Text
auth = fromMaybe "" $ lookup hAuthorization hdrs
anon = cs $ configAnonRole conf
claims =
fromMaybe (M.fromList []) $
case split (==' ') (cs auth) of
("Bearer" : jwt : _) -> jwtClaims jwtSecret jwt
_ -> Nothing
env = if M.member "role" claims
then jwtEnv
else setRole anon : jwtEnv
jwtEnv = claimsToSQL claims
_ <- H.unitEx $ stmt setAnon
let time = unsafePerformIO getPOSIXTime
case split (== ' ') (cs auth) of
("Bearer" : tokenStr : _) ->
case jwtClaims jwtSecret tokenStr time of
Just claims ->
if M.member "role" claims
then do
mapM_ H.unitEx $ stmt <$> claimsToSQL claims
app req
else invalidJWT
_ -> invalidJWT
_ -> app req
where
stmt c = B.Stmt c V.empty True
hdrs = requestHeaders req
jwtSecret = (cs $ configJwtSecret conf) :: Text
auth = fromMaybe "" $ lookup hAuthorization hdrs
anon = cs $ configAnonRole conf
setAnon = setRole anon
invalidJWT = return $ responseLBS status400 [("Content-Type","application/json")] "{\"message\":\"Invalid JWT\"}"
unsupportedAccept :: Application -> Application
unsupportedAccept app req respond = do