Issue http 401 for expired jwt

Fixes #512
This commit is contained in:
Joe Nelson
2016-09-24 21:28:08 -07:00
parent 35da4809d4
commit fb5fce026d
3 changed files with 34 additions and 27 deletions
+19 -11
View File
@@ -16,6 +16,7 @@ module PostgREST.Auth (
, containsRole
, jwtClaims
, tokenJWT
, JWTAttempt(..)
) where
import Protolude
@@ -47,17 +48,24 @@ claimsToSQL claims = roleStmts <> varStmts
valueToVariable = pgFmtLit . unquoted
{-|
Receives the JWT secret (from config) and a JWT and
returns a map of JWT claims
In case there is any problem decoding the JWT it returns an error Text
Possible situations encountered with client JWTs
-}
jwtClaims :: JWT.Secret -> Text -> NominalDiffTime -> Either Text (M.HashMap Text Value)
jwtClaims _ "" _ = Right M.empty
data JWTAttempt = JWTExpired
| JWTInvalid
| JWTClaims (M.HashMap Text Value)
deriving Eq
{-|
Receives the JWT secret (from config) and a JWT and returns a map
of JWT claims.
-}
jwtClaims :: JWT.Secret -> Text -> NominalDiffTime -> JWTAttempt
jwtClaims _ "" _ = JWTClaims M.empty
jwtClaims secret jwt time =
case isExpired <$> mClaims of
Just True -> Left "JWT expired"
Nothing -> Left "Invalid JWT"
Just False -> Right $ value2map $ fromJust mClaims
Just True -> JWTExpired
Nothing -> JWTInvalid
Just False -> JWTClaims $ value2map $ fromJust mClaims
where
isExpired claims =
let mExp = claims ^? key "exp" . _Integer
@@ -80,6 +88,6 @@ tokenJWT secret _ = tokenJWT secret emptyArray
{-|
Whether a response from jwtClaims contains a role claim
-}
containsRole :: Either Text (M.HashMap Text Value) -> Bool
containsRole (Left _) = False
containsRole (Right claims) = M.member "role" claims
containsRole :: JWTAttempt -> Bool
containsRole (JWTClaims claims) = M.member "role" claims
containsRole _ = False