def Autenticar(self, *args, **kwargs): if 'service' in kwargs: service = kwargs['service'] else: service = 'wsfecred' wsaa = WSAA() archivo = ubicacion_sistema() + service + '-ta.xml' try: file = open(archivo, "r") ta = file.read() file.close() except: ta = '' if ta == '': #si no existe el archivo se solicita un ticket solicitar = True else: ok = wsaa.AnalizarXml(ta) expiracion = wsaa.ObtenerTagXml("expirationTime") solicitar = wsaa.Expirado( expiracion) #si el ticket esta vencido se solicita uno nuevo logging.info( "Fecha expiracion de ticket acceso {}".format(expiracion)) if solicitar: #Generar un Ticket de Requerimiento de Acceso(TRA) tra = wsaa.CreateTRA(service=service) #Generar el mensaje firmado(CMS) if LeerIni(clave='h**o') == 'S': #homologacion cms = wsaa.SignTRA( tra, LeerIni(clave="cert_homo", key="WSAA"), LeerIni(clave="privatekey_homo", key="WSAA")) ok = wsaa.Conectar("", LeerIni(clave='url_homo', key='WSAA')) # Homologación else: cms = wsaa.SignTRA( tra, LeerIni(clave="cert_prod", key="WSAA"), LeerIni(clave="privatekey_prod", key="WSAA")) ok = wsaa.Conectar("", LeerIni(clave='url_prod', key='WSAA')) #Produccion #Llamar al web service para autenticar ta = wsaa.LoginCMS(cms) #Grabo el ticket de acceso para poder reutilizarlo file = open(archivo, 'w') logging.debug('Ticket de acceso {}'.format(ta)) file.write(ta) file.close() # devuelvo el ticket de acceso #print "Ticket acceso: {}".format(ta) return ta
def test_login_cms(key_and_cert): """comprobando si LoginCMS está funcionando correctamente""" wsaa = WSAA() tra = wsaa.CreateTRA(service="wsfe", ttl=DEFAULT_TTL) cms = wsaa.SignTRA(tra, key_and_cert[1], key_and_cert[0]) chk = wsaa.Conectar(cache=None, wsdl=WSDL, cacert=CACERT, proxy=None) ta_xml = wsaa.LoginCMS(cms) ta = SimpleXMLElement(ta_xml) if not isinstance(cms, str): cms = cms.decode('utf-8') assert isinstance(cms, str) assert cms.startswith('MIIG+') assert chk == True assert ta_xml.startswith( '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>') assert ta.credentials.token assert ta.credentials.sign assert "<source>" in ta_xml assert "<destination>" in ta_xml assert "<uniqueId>" in ta_xml assert "<expirationTime>" in ta_xml assert "<generationTime>" in ta_xml assert "<credentials>" in ta_xml assert "<token>" in ta_xml assert "<sign>" in ta_xml assert ta_xml.endswith("</loginTicketResponse>\n")
def authenticate(service, certificate, private_key, force=False, cache=CACHE, wsdl=WSAA_URL, proxy=PROXY, ): "Call AFIP Authentication webservice to get token & sign or error message" # import AFIP webservice authentication helper: from pyafipws.wsaa import WSAA # create AFIP webservice authentication helper instance: wsaa = WSAA() wsaa.LanzarExcepciones = True # raise python exceptions on any failure # make md5 hash of the parameter for caching... fn = "%s.xml" % hashlib.md5(service + certificate + private_key).hexdigest() if cache: fn = os.path.join(cache, fn) else: fn = os.path.join(wsaa.InstallDir, "cache", fn) try: # read the access ticket (if already authenticated) if not os.path.exists(fn) or \ os.path.getmtime(fn)+(DEFAULT_TTL) < time.time(): # access ticket (TA) outdated, create new access request ticket (TRA) tra = wsaa.CreateTRA(service=service, ttl=DEFAULT_TTL) # cryptographically sing the access ticket cms = wsaa.SignTRA(tra, certificate, private_key) # connect to the webservice: wsaa.Conectar(cache, wsdl, proxy) # call the remote method ta = wsaa.LoginCMS(cms) if not ta: raise RuntimeError() # write the access ticket for further consumption open(fn, "w").write(ta) else: # get the access ticket from the previously written file ta = open(fn, "r").read() # analyze the access ticket xml and extract the relevant fields wsaa.AnalizarXml(xml=ta) token = wsaa.ObtenerTagXml("token") sign = wsaa.ObtenerTagXml("sign") err_msg = None except: token = sign = None if wsaa.Excepcion: # get the exception already parsed by the helper err_msg = wsaa.Excepcion else: # avoid encoding problem when reporting exceptions to the user: err_msg = traceback.format_exception_only(sys.exc_type, sys.exc_value)[0] if DEBUG: raise return {'token': token, 'sign': sign, 'err_msg': err_msg}
def test_wsaa_sign_tra(key_and_cert): wsaa = WSAA() tra = wsaa.CreateTRA("wsfe") sign = wsaa.SignTRA(tra, key_and_cert[1], key_and_cert[0]) if not isinstance(sign, str): sign = sign.decode('utf-8') assert isinstance(sign, str) assert sign.startswith("MIIG+")
def test_wsaa_sign_tra_inline(key_and_cert): wsaa = WSAA() tra = wsaa.CreateTRA("wsfe") sign = wsaa.SignTRA(tra, key_and_cert[1], key_and_cert[0]) sign_2 = wsaa.SignTRA(tra, open(key_and_cert[1]).read(), open(key_and_cert[0]).read()) if not isinstance(sign, str): sign = sign.decode('utf-8') if not isinstance(sign_2, str): sign_2 = sign_2.decode('utf-8') assert isinstance(sign, str) assert sign.startswith("MIIG+") assert isinstance(sign_2, str) assert sign_2.startswith("MIIG+")
def test_wsaa_sign(): wsaa = WSAA() tra = '<?xml version="1.0" encoding="UTF-8"?><loginTicketRequest version="1.0"/>' # TODO: use certificate and private key as fixture / PEM text (not files) cms = wsaa.SignTRA(tra, "reingart.crt", "reingart.key") # TODO: return string if not isinstance(cms, str): cms = cms.decode("utf8") # sanity checks: assert isinstance(cms, str) out = base64.b64decode(cms) assert tra.encode("utf8") in out
def authenticate(self, service, certificate, private_key, force=False, cache="", wsdl="", proxy=""): """ Call AFIP Authentication webservice to get token & sign or error message """ # import AFIP webservice authentication helper: from pyafipws.wsaa import WSAA # create AFIP webservice authentication helper instance: wsaa = WSAA() # raise python exceptions on any failure wsaa.LanzarExcepciones = True # five hours DEFAULT_TTL = 60 * 60 * 5 # make md5 hash of the parameter for caching... fn = "%s.xml" % hashlib.md5( (service + certificate + private_key).encode('utf-8')).hexdigest() if cache: fn = os.path.join(cache, fn) else: fn = os.path.join(wsaa.InstallDir, "cache", fn) try: # read the access ticket (if already authenticated) if not os.path.exists(fn) or \ os.path.getmtime(fn) + (DEFAULT_TTL) < time.time(): # access ticket (TA) outdated, create new access request # ticket (TRA) tra = wsaa.CreateTRA(service=service, ttl=DEFAULT_TTL) # cryptographically sing the access ticket cms = wsaa.SignTRA(tra, certificate, private_key) # connect to the webservice: wsaa.Conectar(cache, wsdl, proxy) # call the remote method ta = wsaa.LoginCMS(cms) if not ta: raise RuntimeError() # write the access ticket for further consumption open(fn, "w").write(ta) else: # get the access ticket from the previously written file ta = open(fn, "r").read() # analyze the access ticket xml and extract the relevant fields wsaa.AnalizarXml(xml=ta) token = wsaa.ObtenerTagXml("token") sign = wsaa.ObtenerTagXml("sign") expirationTime = wsaa.ObtenerTagXml("expirationTime") generationTime = wsaa.ObtenerTagXml("generationTime") uniqueId = wsaa.ObtenerTagXml("uniqueId") except: token = sign = None if wsaa.Excepcion: # get the exception already parsed by the helper err_msg = wsaa.Excepcion else: # avoid encoding problem when reporting exceptions to the user: err_msg = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0] raise UserError( _('Could not connect. This is the what we received: %s') % (err_msg)) return { 'uniqueid': uniqueId, 'generationtime': generationTime, 'expirationtime': expirationTime, 'token': token, 'sign': sign, }
import pysimplesoap.client print(pysimplesoap.client.__version__) #assert pysimplesoap.client.__version__ >= "1.08c" WSDL = "https://fwshomo.afip.gov.ar/wslpg/LpgService?wsdl" CUIT = 20267565393 CERT = "/home/reingart/pyafipws/reingart.crt" PRIVATEKEY = "/home/reingart/pyafipws/reingart.key" CACERT = "/home/reingart/pyafipws/afip_root_desa_ca.crt" CACHE = "/home/reingart/pyafipws/cache" # Autenticación: wsaa = WSAA() tra = wsaa.CreateTRA(service="wslpg") cms = wsaa.SignTRA(tra, CERT, PRIVATEKEY) wsaa.Conectar() wsaa.LoginCMS(cms) class TestIssues(unittest.TestCase): def setUp(self): sys.argv.append("--trace") # TODO: use logging self.wslpg = wslpg = WSLPG() wslpg.LanzarExcepciones = True wslpg.Conectar(url=WSDL, cacert=None, cache=CACHE) wslpg.Cuit = CUIT wslpg.Token = wsaa.Token wslpg.Sign = wsaa.Sign def test_liquidacion(self):
def test_call_wsaa(key_and_cert): wsaa = WSAA() tra = wsaa.CreateTRA(service="wsfe", ttl=DEFAULT_TTL) cms = wsaa.SignTRA(tra, key_and_cert[1], key_and_cert[0]) assert call_wsaa(cms, WSDL)