From 9aa9bf947826168e8e2f2e947678970d59fc93e9 Mon Sep 17 00:00:00 2001 From: Yuriy Syrovetskiy Date: Fri, 25 Jul 2014 19:19:41 +0400 Subject: [PATCH] 401 if API client is not authenticated Server should not HTTP-redirect API client to the auth page, error 401 is more suitable. --- yesod-auth/Yesod/Auth.hs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/yesod-auth/Yesod/Auth.hs b/yesod-auth/Yesod/Auth.hs index 535137b4..6bdccb0c 100644 --- a/yesod-auth/Yesod/Auth.hs +++ b/yesod-auth/Yesod/Auth.hs @@ -415,18 +415,23 @@ type YesodAuthPersist master = type AuthEntity master = KeyEntity (AuthId master) -- | Similar to 'maybeAuthId', but redirects to a login page if user is not --- authenticated. +-- authenticated or responds with error 401 if this is an API client (expecting JSON). -- -- Since 1.1.0 requireAuthId :: YesodAuth master => HandlerT master IO (AuthId master) -requireAuthId = maybeAuthId >>= maybe redirectLogin return +requireAuthId = maybeAuthId >>= maybe handleAuthLack return -- | Similar to 'maybeAuth', but redirects to a login page if user is not --- authenticated. +-- authenticated or responds with error 401 if this is an API client (expecting JSON). -- -- Since 1.1.0 requireAuth :: YesodAuthPersist master => HandlerT master IO (Entity (AuthEntity master)) -requireAuth = maybeAuth >>= maybe redirectLogin return +requireAuth = maybeAuth >>= maybe handleAuthLack return + +handleAuthLack :: Yesod master => HandlerT master IO a +handleAuthLack = do + aj <- acceptsJson + if aj then notAuthenticated else redirectLogin redirectLogin :: Yesod master => HandlerT master IO a redirectLogin = do