]> Git — Sourcephile - gargantext.git/blob - bin/gargantext-client/Auth.hs
Merge remote-tracking branch 'origin/dev-merge-nix-2' into dev-merge
[gargantext.git] / bin / gargantext-client / Auth.hs
1 module Auth where
2
3 import Prelude
4 import Core
5 import Options
6
7 import Control.Monad.IO.Class
8 import Data.Text.Encoding (encodeUtf8)
9 import Options.Generic
10 import Servant.Client
11 import qualified Servant.Auth.Client as SA
12
13 import Gargantext.API.Client
14 import qualified Gargantext.API.Admin.Auth.Types as Auth
15 import qualified Gargantext.Core.Types.Individu as Auth
16 import qualified Gargantext.Database.Admin.Types.Node as Node
17
18 -- | Authenticate and use the resulting Token to perform
19 -- auth-restricted actions
20 withAuthToken
21 :: ClientOpts -- ^ source of user/pass data
22 -> (SA.Token -> Node.NodeId -> ClientM a) -- ^ do something once authenticated
23 -> ClientM a
24 withAuthToken opts act
25 -- both user and password CLI arguments passed
26 | Helpful (Just usr) <- user opts
27 , Helpful (Just pw) <- pass opts = do
28 authRes <- postAuth (Auth.AuthRequest usr (Auth.GargPassword pw))
29 case Auth._authRes_valid authRes of
30 -- authentication failed, this function critically needs it to
31 -- be able to run the action, so we abort
32 Nothing -> problem $
33 "invalid auth response: " ++
34 maybe "" (show . Auth._authInv_message)
35 (Auth._authRes_inval authRes)
36 -- authentication went through, we can run the action
37 Just (Auth.AuthValid tok tree_id _uid) -> do
38 let tok' = SA.Token (encodeUtf8 tok)
39 whenVerbose opts $ do
40 liftIO . putStrLn $ "[Debug] Authenticated: token=" ++ show tok ++
41 ", tree_id=" ++ show tree_id
42 act tok' tree_id
43 -- user and/or pass CLI arguments not passed
44 | otherwise =
45 problem "auth-protected actions require --user and --pass"