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 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 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, }