from google.appengine.api.urlfetch import fetch
import cgi
from xml.dom import minidom
import logging
from appconfig import *

class WebserviceAuthenticator:
    def authenticate(self,userId,passWd,appId):
        userId=cgi.escape(userId).encode('ascii', 'xmlcharrefreplace')
        passWd=cgi.escape(passWd).encode('ascii', 'xmlcharrefreplace')
        try:
            SoapMessage = """<?xml version="1.0" encoding="utf-8"?>
                    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                      <soap:Body>
                        <%s xmlns="%s">
                          <%s>%s</%s>
                          <%s>%s</%s>
                        </%s>
                      </soap:Body>
                    </soap:Envelope>"""  % (METHOD,NAMESPACE,USERID,userId,USERID,PASSWORD,passWd,PASSWORD,METHOD)
            header = dict()
            header['Host']=HOST
            header['Content-type']="text/xml; charset=\"UTF-8\""
            header['Content-length']=str(len(SoapMessage))
            header['SOAPAction']=SOAPACTION

            response=fetch("http://"+HOST+SERVICE_URL, payload=SoapMessage, method="POST", headers=header, allow_truncated=False, follow_redirects=True, deadline=None)
            xmldom=minidom.parseString(response.content)
            if xmldom.getElementsByTagName(RESPONSE)[0].childNodes[0].nodeValue=='true':
                return {"result":True}
            else:
                return {"result":False}
        except Exception, e:
            logging.error("Webservice Auth : " + str(e))
            return {"result":False}