Servant Authentication

Hello, I was playing with an Auth function from this Servant Auth Tutorial.

In authHandler, the getUser function expects to get conn username password, but currently it just gets conn username. The problem is with last two lines, I am messing around about how to pass two last arguments instead of just one.

getUser :: PostgresConnection -> ByteString -> ByteString -> Handler User
getUser conn username password = ....

authHandler :: PostgresConnection -> AuthHandler Request User
authHandler conn = mkAuthHandler handler
  where
    maybeToEither e = maybe (Left e) Right
    throw401 msg = throwError $ err401 { errBody = msg }
    handler req = either throw401 (getUser conn) $ do
      cookie <- maybeToEither "Missing cookie header" $ lookup "cookie" $ requestHeaders req
      maybeToEither "Missing username key in cookie" $ lookup "username" $ parseCookies cookie
      -- maybeToEither "Missing password key in cookie" $ lookup "password" $ parseCookies cookie

Hi,

can you post the type for your routes and the error your get?


It’s not really connected to your question but I’d advice to not add a clear-text password to a cookie - usually you should only need to save a hash of a password + a random salt for this has - and I’d not use a users login as the login for your database connection either.

Like @CarstenK said, I hope you’re not storing plain-text passwords in a cookie. (You can use the password library to easily hash them)

WRT the code, you’re trying to pass two arguments as one. either has type (a -> x) -> (b -> x) -> Either a b -> x, so your getUser conn is going to get a b (one argument). To make this work, you can use uncurry $ getUser conn to make getUser conn from a ByteString -> ByteString -> Handler User into a (ByteString, ByteString) -> Handler User and then end your do block with pure (username, password)
Tuples are generally the way to pass more than one argument when you can only pass one argument. (when the tuples get bigger than 3, it’s arguably better to just make an ad-hoc data type to make it more readable)

2 Likes