module Network.XMPP.Auth where

import Network.XMPP.XMLParse
import Network.XMPP.XMPPMonad
import Network.XMPP.Stanzas
import Network.XMPP.MyDebug

-- |Non-SASL authentication, following XEP-0078.
startAuth :: String             -- ^Username (part before \@ in JID)
          -> String             -- ^Server (part after \@ in JID)
          -> String             -- ^Password
          -> String             -- ^Resource (unique identifier for this connection)
          -> Integer            -- ^Resource priority
          -> XMPP Integer       -- ^Error number. Zero if authentication succeeded.
startAuth username server password resource priority = do
  response <- sendIqWait server "get" [XML "query"
                                       [XML "username"
                                        [CData username]]]
  case xmlPath ["query","password"] response of
    Nothing -> return 1 -- plaintext authentication not supported by server
                        -- "If there is no such username, the server SHOULD NOT return an error"
                        -- So server can return error here, if username is wrong.
    Just _ -> do
      response' <- sendIqWait server "set" [XML "query"
                                            [XML "username" []
                                                     [CData username],
                                             XML "password" []
                                                     [CData password],
                                             XML "resource" []
                                                     [CData resource]]]
      return $ getErrorCode response'