Crear middleware para conexiones
This commit is contained in:
parent
a8133a15e4
commit
009c6de608
|
@ -21,6 +21,7 @@ class AppLogin(object):
|
||||||
if result['login']:
|
if result['login']:
|
||||||
session.save()
|
session.save()
|
||||||
session['user'] = result['user']
|
session['user'] = result['user']
|
||||||
|
session['rfc'] = values['rfc']
|
||||||
req.context['result'] = result
|
req.context['result'] = result
|
||||||
resp.status = falcon.HTTP_200
|
resp.status = falcon.HTTP_200
|
||||||
|
|
||||||
|
|
|
@ -5,11 +5,12 @@ import getpass
|
||||||
import json
|
import json
|
||||||
import mimetypes
|
import mimetypes
|
||||||
import os
|
import os
|
||||||
|
import sqlite3
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
import bcrypt
|
import bcrypt
|
||||||
|
|
||||||
from settings import template_lookup, PATH_CP
|
from settings import log, template_lookup, PATH_CP, COMPANIES
|
||||||
|
|
||||||
|
|
||||||
def _get_hash(password):
|
def _get_hash(password):
|
||||||
|
@ -32,7 +33,55 @@ def get_pass():
|
||||||
msg = 'La contraseña es necesaria'
|
msg = 'La contraseña es necesaria'
|
||||||
return False, msg
|
return False, msg
|
||||||
|
|
||||||
return True, _get_hash(password)
|
return True, password
|
||||||
|
|
||||||
|
|
||||||
|
def get_value(arg):
|
||||||
|
value = input('Introduce el {}: '.format(arg)).strip()
|
||||||
|
if not value:
|
||||||
|
msg = 'El {} es requerido'.format(arg)
|
||||||
|
log.error(msg)
|
||||||
|
return ''
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _get_args(rfc):
|
||||||
|
con = sqlite3.connect(COMPANIES)
|
||||||
|
cursor = con.cursor()
|
||||||
|
sql = "SELECT con FROM names WHERE rfc=?"
|
||||||
|
cursor.execute(sql, (rfc,))
|
||||||
|
values = cursor.fetchone()
|
||||||
|
if values is None:
|
||||||
|
msg = 'No se encontró el RFC'
|
||||||
|
log.error(msg)
|
||||||
|
return ''
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
con.close()
|
||||||
|
return values[0]
|
||||||
|
|
||||||
|
|
||||||
|
def get_con(rfc=''):
|
||||||
|
if not rfc:
|
||||||
|
rfc = get_value('RFC').upper()
|
||||||
|
if not rfc:
|
||||||
|
return False
|
||||||
|
|
||||||
|
args = _get_args(rfc.upper())
|
||||||
|
if not args:
|
||||||
|
return False
|
||||||
|
return loads(args)
|
||||||
|
|
||||||
|
|
||||||
|
def get_rfcs():
|
||||||
|
con = sqlite3.connect(COMPANIES)
|
||||||
|
cursor = con.cursor()
|
||||||
|
sql = "SELECT * FROM names"
|
||||||
|
cursor.execute(sql)
|
||||||
|
values = cursor.fetchall()
|
||||||
|
cursor.close()
|
||||||
|
con.close()
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
def now():
|
def now():
|
||||||
|
@ -74,6 +123,10 @@ def dumps(data):
|
||||||
return json.dumps(data, default=str)
|
return json.dumps(data, default=str)
|
||||||
|
|
||||||
|
|
||||||
|
def loads(data):
|
||||||
|
return json.loads(data)
|
||||||
|
|
||||||
|
|
||||||
def clean(values):
|
def clean(values):
|
||||||
for k, v in values.items():
|
for k, v in values.items():
|
||||||
if isinstance(v, str):
|
if isinstance(v, str):
|
||||||
|
|
|
@ -3,7 +3,13 @@
|
||||||
import falcon
|
import falcon
|
||||||
from beaker.middleware import SessionMiddleware
|
from beaker.middleware import SessionMiddleware
|
||||||
|
|
||||||
from middleware import AuthMiddleware, JSONTranslator, static, handle_404
|
from middleware import (
|
||||||
|
AuthMiddleware,
|
||||||
|
JSONTranslator,
|
||||||
|
ConnectionMiddleware,
|
||||||
|
static,
|
||||||
|
handle_404
|
||||||
|
)
|
||||||
from models.db import StorageEngine
|
from models.db import StorageEngine
|
||||||
from controllers.main import (
|
from controllers.main import (
|
||||||
AppLogin, AppLogout, AppAdmin, AppMain,
|
AppLogin, AppLogout, AppAdmin, AppMain,
|
||||||
|
@ -14,7 +20,8 @@ from settings import DEBUG
|
||||||
db = StorageEngine()
|
db = StorageEngine()
|
||||||
#~ partners = AppPartners(db)
|
#~ partners = AppPartners(db)
|
||||||
|
|
||||||
api = falcon.API(middleware=[AuthMiddleware(), JSONTranslator()])
|
api = falcon.API(
|
||||||
|
middleware=[AuthMiddleware(), JSONTranslator(), ConnectionMiddleware()])
|
||||||
api.req_options.auto_parse_form_urlencoded = True
|
api.req_options.auto_parse_form_urlencoded = True
|
||||||
api.add_sink(handle_404, '')
|
api.add_sink(handle_404, '')
|
||||||
|
|
||||||
|
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
import falcon
|
import falcon
|
||||||
from controllers import util
|
from controllers import util
|
||||||
|
from models import main
|
||||||
from settings import PATH_STATIC
|
from settings import PATH_STATIC
|
||||||
|
|
||||||
|
|
||||||
|
@ -43,3 +44,19 @@ class JSONTranslator(object):
|
||||||
if 'result' not in req.context:
|
if 'result' not in req.context:
|
||||||
return
|
return
|
||||||
resp.body = util.dumps(req.context['result'])
|
resp.body = util.dumps(req.context['result'])
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionMiddleware(object):
|
||||||
|
|
||||||
|
#~ def process_request(self, req, resp):
|
||||||
|
def process_resource(self, req, resp, resource, params):
|
||||||
|
id_session = req.cookies.get('beaker.session.id', '')
|
||||||
|
session = req.env['beaker.session']
|
||||||
|
rfc = session.get('rfc', '')
|
||||||
|
if id_session and rfc:
|
||||||
|
opt = util.get_con(rfc)
|
||||||
|
main.conectar(opt)
|
||||||
|
|
||||||
|
def process_response(self, req, resp, resource):
|
||||||
|
main.desconectar()
|
||||||
|
|
||||||
|
|
|
@ -6,10 +6,12 @@ from . import main
|
||||||
class StorageEngine(object):
|
class StorageEngine(object):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
main.conectar()
|
#~ main.conectar()
|
||||||
|
pass
|
||||||
|
|
||||||
def authenticate(self, args):
|
def authenticate(self, args):
|
||||||
return main.authenticate(args['usuario'], args['contra'])
|
#~ return main.authenticate(args['usuario'], args['contra'])
|
||||||
|
return main.authenticate(args)
|
||||||
|
|
||||||
def get_partners(self, values):
|
def get_partners(self, values):
|
||||||
return main.get_partners(values)
|
return main.get_partners(values)
|
||||||
|
|
|
@ -33,7 +33,7 @@ def conectar(opt):
|
||||||
if not db_type in db:
|
if not db_type in db:
|
||||||
log.error('Tipo de base de datos no soportado')
|
log.error('Tipo de base de datos no soportado')
|
||||||
return False
|
return False
|
||||||
|
#~ print ('DB NAME', db_name)
|
||||||
database = db[db_type](db_name, **opt)
|
database = db[db_type](db_name, **opt)
|
||||||
try:
|
try:
|
||||||
database_proxy.initialize(database)
|
database_proxy.initialize(database)
|
||||||
|
@ -46,6 +46,15 @@ def conectar(opt):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def desconectar():
|
||||||
|
if database_proxy.obj is None:
|
||||||
|
return
|
||||||
|
if not database_proxy.is_closed():
|
||||||
|
database_proxy.close()
|
||||||
|
log.info('Desconectado a la BD...')
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
class Configuracion(BaseModel):
|
class Configuracion(BaseModel):
|
||||||
clave = TextField()
|
clave = TextField()
|
||||||
valor = TextField(default='')
|
valor = TextField(default='')
|
||||||
|
@ -407,14 +416,19 @@ class FacturasImpuestos(BaseModel):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def authenticate(usuario, contraseña):
|
def authenticate(args):
|
||||||
respuesta = {'login': False, 'msg': 'No Autorizado', 'user': ''}
|
respuesta = {'login': False, 'msg': 'No Autorizado', 'user': ''}
|
||||||
|
values = util.get_con(args['rfc'])
|
||||||
|
if not values:
|
||||||
|
return respuesta
|
||||||
|
|
||||||
|
conectar(values)
|
||||||
try:
|
try:
|
||||||
obj = Usuarios.get(usuario=usuario, es_activo=True)
|
obj = Usuarios.get(usuario=args['usuario'], es_activo=True)
|
||||||
except Usuarios.DoesNotExist:
|
except Usuarios.DoesNotExist:
|
||||||
return respuesta
|
return respuesta
|
||||||
|
|
||||||
if not obj.contraseña.check_password(contraseña):
|
if not obj.contraseña.check_password(args['contra']):
|
||||||
return respuesta
|
return respuesta
|
||||||
|
|
||||||
obj.ultimo_ingreso = util.now()
|
obj.ultimo_ingreso = util.now()
|
||||||
|
@ -423,6 +437,7 @@ def authenticate(usuario, contraseña):
|
||||||
respuesta['login'] = True
|
respuesta['login'] = True
|
||||||
respuesta['user'] = str(obj)
|
respuesta['user'] = str(obj)
|
||||||
respuesta['super'] = obj.es_superusuario
|
respuesta['super'] = obj.es_superusuario
|
||||||
|
#~ desconectar()
|
||||||
return respuesta
|
return respuesta
|
||||||
|
|
||||||
|
|
||||||
|
@ -494,16 +509,6 @@ def _init_values():
|
||||||
|
|
||||||
|
|
||||||
def _crear_tablas():
|
def _crear_tablas():
|
||||||
rfc = input('Introduce el RFC: ').strip().upper()
|
|
||||||
if not rfc:
|
|
||||||
msg = 'El RFC es requerido'
|
|
||||||
log.error(msg)
|
|
||||||
return
|
|
||||||
|
|
||||||
opt = _get_con(rfc)
|
|
||||||
if not conectar(opt):
|
|
||||||
return
|
|
||||||
|
|
||||||
tablas = [Addendas, Categorias, Certificado, CondicionesPago, Configuracion,
|
tablas = [Addendas, Categorias, Certificado, CondicionesPago, Configuracion,
|
||||||
Emisor, Facturas, FacturasDetalle, FacturasImpuestos, Folios, Productos,
|
Emisor, Facturas, FacturasDetalle, FacturasImpuestos, Folios, Productos,
|
||||||
SATAduanas, SATFormaPago, SATImpuestos, SATMonedas, SATRegimenes,
|
SATAduanas, SATFormaPago, SATImpuestos, SATMonedas, SATRegimenes,
|
||||||
|
@ -515,7 +520,7 @@ def _crear_tablas():
|
||||||
]
|
]
|
||||||
database_proxy.create_tables(tablas, True)
|
database_proxy.create_tables(tablas, True)
|
||||||
log.info('Tablas creadas correctamente...')
|
log.info('Tablas creadas correctamente...')
|
||||||
return
|
return True
|
||||||
|
|
||||||
|
|
||||||
def migrate_tables():
|
def migrate_tables():
|
||||||
|
@ -525,7 +530,11 @@ def migrate_tables():
|
||||||
|
|
||||||
|
|
||||||
def _agregar_superusuario():
|
def _agregar_superusuario():
|
||||||
conectar()
|
args = util.get_con()
|
||||||
|
if not args:
|
||||||
|
return
|
||||||
|
|
||||||
|
conectar(args)
|
||||||
usuario = input('Introduce el nuevo nombre para el superusuario: ').strip()
|
usuario = input('Introduce el nuevo nombre para el superusuario: ').strip()
|
||||||
if not usuario:
|
if not usuario:
|
||||||
msg = 'El nombre de usuario es requerido'
|
msg = 'El nombre de usuario es requerido'
|
||||||
|
@ -548,7 +557,11 @@ def _agregar_superusuario():
|
||||||
|
|
||||||
|
|
||||||
def _cambiar_contraseña():
|
def _cambiar_contraseña():
|
||||||
conectar()
|
args = util.get_con()
|
||||||
|
if not args:
|
||||||
|
return
|
||||||
|
|
||||||
|
conectar(args)
|
||||||
usuario = input('Introduce el nombre de usuario: ').strip()
|
usuario = input('Introduce el nombre de usuario: ').strip()
|
||||||
if not usuario:
|
if not usuario:
|
||||||
msg = 'El nombre de usuario es requerido'
|
msg = 'El nombre de usuario es requerido'
|
||||||
|
@ -574,6 +587,24 @@ def _cambiar_contraseña():
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
|
def _add_emisor(rfc, args):
|
||||||
|
con = sqlite3.connect(COMPANIES)
|
||||||
|
cursor = con.cursor()
|
||||||
|
sql = """
|
||||||
|
INSERT INTO names
|
||||||
|
VALUES (?, ?)"""
|
||||||
|
try:
|
||||||
|
cursor.execute(sql, (rfc, args))
|
||||||
|
except sqlite3.IntegrityError as e:
|
||||||
|
log.error(e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
con.commit()
|
||||||
|
cursor.close()
|
||||||
|
con.close()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _agregar_rfc():
|
def _agregar_rfc():
|
||||||
rfc = input('Introduce el nuevo RFC: ').strip().upper()
|
rfc = input('Introduce el nuevo RFC: ').strip().upper()
|
||||||
if not rfc:
|
if not rfc:
|
||||||
|
@ -592,10 +623,21 @@ def _agregar_rfc():
|
||||||
log.error('Datos de conexión incompletos')
|
log.error('Datos de conexión incompletos')
|
||||||
return
|
return
|
||||||
|
|
||||||
if conectar(opt):
|
args = opt.copy()
|
||||||
log.info('RFC agregado correctamente...')
|
if conectar(args):
|
||||||
else:
|
if _add_emisor(rfc, util.dumps(opt)) and _crear_tablas():
|
||||||
log.error('No se pudo agregar el RFC')
|
log.info('RFC agregado correctamente...')
|
||||||
|
return
|
||||||
|
|
||||||
|
log.error('No se pudo agregar el RFC')
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
def _listar_rfc():
|
||||||
|
data = util.get_rfcs()
|
||||||
|
for row in data:
|
||||||
|
msg = 'RFC: {}\n\t{}'.format(row[0], row[1])
|
||||||
|
log.info(msg)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
|
@ -605,10 +647,12 @@ help_migrate_db = 'Migra las tablas en la base de datos'
|
||||||
help_superuser = 'Crea un nuevo super usuario'
|
help_superuser = 'Crea un nuevo super usuario'
|
||||||
help_change_pass = 'Cambia la contraseña a un usuario'
|
help_change_pass = 'Cambia la contraseña a un usuario'
|
||||||
help_rfc = 'Agrega un nuevo RFC'
|
help_rfc = 'Agrega un nuevo RFC'
|
||||||
|
help_br = 'Elimina un RFC'
|
||||||
|
help_lr = 'Listar RFCs'
|
||||||
|
|
||||||
@click.command(context_settings=CONTEXT_SETTINGS)
|
@click.command(context_settings=CONTEXT_SETTINGS)
|
||||||
@click.option('-bd', '--iniciar-bd',help=help_create_tables,
|
#~ @click.option('-bd', '--iniciar-bd',help=help_create_tables,
|
||||||
is_flag=True, default=False)
|
#~ is_flag=True, default=False)
|
||||||
@click.option('-m', '--migrar-bd', help=help_migrate_db,
|
@click.option('-m', '--migrar-bd', help=help_migrate_db,
|
||||||
is_flag=True, default=False)
|
is_flag=True, default=False)
|
||||||
@click.option('-ns', '--nuevo-superusuario', help=help_superuser,
|
@click.option('-ns', '--nuevo-superusuario', help=help_superuser,
|
||||||
|
@ -616,12 +660,15 @@ help_rfc = 'Agrega un nuevo RFC'
|
||||||
@click.option('-cc', '--cambiar-contraseña', help=help_change_pass,
|
@click.option('-cc', '--cambiar-contraseña', help=help_change_pass,
|
||||||
is_flag=True, default=False)
|
is_flag=True, default=False)
|
||||||
@click.option('-rfc', '--rfc', help=help_rfc, is_flag=True, default=False)
|
@click.option('-rfc', '--rfc', help=help_rfc, is_flag=True, default=False)
|
||||||
def main(iniciar_bd, migrar_bd, nuevo_superusuario, cambiar_contraseña, rfc):
|
@click.option('-br', '--borrar-rfc', help=help_br, is_flag=True, default=False)
|
||||||
|
@click.option('-lr', '--listar-rfc', help=help_lr, is_flag=True, default=False)
|
||||||
|
def main(migrar_bd, nuevo_superusuario, cambiar_contraseña, rfc, borrar_rfc,
|
||||||
|
listar_rfc):
|
||||||
opt = locals()
|
opt = locals()
|
||||||
|
|
||||||
if opt['iniciar_bd']:
|
#~ if opt['iniciar_bd']:
|
||||||
_crear_tablas()
|
#~ _crear_tablas()
|
||||||
sys.exit(0)
|
#~ sys.exit(0)
|
||||||
|
|
||||||
if opt['migrar_bd']:
|
if opt['migrar_bd']:
|
||||||
migrate_tables()
|
migrate_tables()
|
||||||
|
@ -639,6 +686,14 @@ def main(iniciar_bd, migrar_bd, nuevo_superusuario, cambiar_contraseña, rfc):
|
||||||
_agregar_rfc()
|
_agregar_rfc()
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
|
if opt['borrar_rfc']:
|
||||||
|
_borrar_rfc()
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
if opt['listar_rfc']:
|
||||||
|
_listar_rfc()
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
|
|
BIN
source/db/rfc.db
BIN
source/db/rfc.db
Binary file not shown.
|
@ -1,7 +1,11 @@
|
||||||
|
|
||||||
|
var msg_rfc = 'El RFC es requerido'
|
||||||
var msg_user = 'El usuario es requerido'
|
var msg_user = 'El usuario es requerido'
|
||||||
var msg_pass = 'La contraseña es requerida'
|
var msg_pass = 'La contraseña es requerida'
|
||||||
|
|
||||||
var form_controls = [
|
var form_controls = [
|
||||||
|
{view: 'text', label: 'RFC', id: 'txt_rfc', name: 'rfc',
|
||||||
|
labelPosition: 'top', required: true, invalidMessage: msg_rfc},
|
||||||
{view: 'text', label: 'Usuario', id: 'txt_usuario', name: 'usuario',
|
{view: 'text', label: 'Usuario', id: 'txt_usuario', name: 'usuario',
|
||||||
labelPosition: 'top', required: true, invalidMessage: msg_user},
|
labelPosition: 'top', required: true, invalidMessage: msg_user},
|
||||||
{view: 'text', label: 'Contraseña', id: 'txt_contra', name: 'contra',
|
{view: 'text', label: 'Contraseña', id: 'txt_contra', name: 'contra',
|
||||||
|
@ -13,6 +17,7 @@ var form_controls = [
|
||||||
|
|
||||||
|
|
||||||
var msg_header = 'Bienvenido a Empresa Libre'
|
var msg_header = 'Bienvenido a Empresa Libre'
|
||||||
|
|
||||||
var ui_login = {
|
var ui_login = {
|
||||||
rows: [
|
rows: [
|
||||||
{maxHeight: 50},
|
{maxHeight: 50},
|
||||||
|
@ -28,6 +33,7 @@ var ui_login = {
|
||||||
width: 400,
|
width: 400,
|
||||||
elements: form_controls,
|
elements: form_controls,
|
||||||
rules:{
|
rules:{
|
||||||
|
rfc:function(value){ return value.trim() != '';},
|
||||||
usuario:function(value){ return value.trim() != '';},
|
usuario:function(value){ return value.trim() != '';},
|
||||||
contra:function(value){ return value.trim() != '';},
|
contra:function(value){ return value.trim() != '';},
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue