Commit 47ca7b04 authored by Jonathan Schaeffer's avatar Jonathan Schaeffer

Logging through Flask app

parent 78825940
......@@ -12,23 +12,20 @@ from config import Configurator
from version import __version__
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
application = Flask(__name__)
if os.getenv('RUNMODE') == 'production':
logger.setLevel(logging.INFO)
application.logger.setLevel(logging.INFO)
else:
logger.setLevel(logging.DEBUG)
application.logger.setLevel(logging.DEBUG)
# Loglevel can be overrinden by LOGLEVEL env var :
if os.getenv('DEBUG') == 'true':
logger.setLevel(logging.DEBUG)
application.logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
application = Flask(__name__)
application.logger.setLevel(logging.INFO)
application.config.from_object(Configurator)
def wsshash(login, password):
"""
Compute a hash suitable for the IRIS wss stack.
......@@ -45,10 +42,10 @@ def verify_token_signature(data, gpg_homedir):
def parse_input_data(data):
# Then we get the token :
token = re.search(r'{(?P<token>.*)}',str(data)).groupdict()['token']
logging.debug(token)
application.logger.debug(token)
d = dict([i for i in kv.split(':',1)] for kv in token.replace('"','').replace(' ','').split(','))
logging.debug("Transformed to dictionary : %s", d)
application.logger.debug("Transformed to dictionary : %s", d)
return d
def register_login(login, password):
......@@ -65,9 +62,9 @@ def register_login(login, password):
user= application.config['RESIFAUTH_PGUSER'],
password = application.config['RESIFAUTH_PGPASSWORD'])
cur = conn.cursor()
logging.debug("Connected to users database")
application.logger.debug("Connected to users database")
except Exception as e:
logging.error("Unable to connect to database %s as %s@%s:%s", application.config['RESIFAUTH_PGDATABASE'],
application.logger.error("Unable to connect to database %s as %s@%s:%s", application.config['RESIFAUTH_PGDATABASE'],
application.config['RESIFAUTH_PGUSER'],
application.config['RESIFAUTH_PGHOST'],
application.config['RESIFAUTH_PGPORT'])
......@@ -99,9 +96,9 @@ def register_privileges(login, fdsn_refs):
user= application.config['RESIFINV_PGUSER'],
password = application.config['RESIFINV_PGPASSWORD'])
cur = conn.cursor()
logging.debug("Connected to privileges database")
application.logger.debug("Connected to privileges database")
except Exception as e:
logging.error("Unable to connect to database %s as %s@%s:%s", application.config['RESIFINV_PGDATABASE'],
application.logger.error("Unable to connect to database %s as %s@%s:%s", application.config['RESIFINV_PGDATABASE'],
application.config['RESIFINV_PGUSER'],
application.config['RESIFINV_PGHOST'],
application.config['RESIFINV_PGPORT'])
......@@ -111,19 +108,19 @@ def register_privileges(login, fdsn_refs):
for ref in fdsn_refs:
ref['login'] = login
ref['expires_at'] = datetime.datetime.now()+datetime.timedelta(days=1)
logging.info(ref)
application.logger.info(ref)
sql_request = "select network_id from networks where start_year=%(startyear)s and end_year=%(endyear)s and network=%(networkcode)s"
try:
cur.execute(sql_request, ref)
except psycopg2.Error as e:
logging.error(e.pgerror)
application.logger.error(e.pgerror)
else:
if cur.rowcount != 1:
logging.info(cur.mogrify(sql_request, ref))
logging.error("%d networks found for %s", cur.rowcount, ref)
application.logger.info(cur.mogrify(sql_request, ref))
application.logger.error("%d networks found for %s", cur.rowcount, ref)
raise NameError(f"{cur.rowcount} networks found for {ref}")
ref['networkid'] = cur.fetchone()[0]
logging.info("Inserting tupple in %s.eida_temp_users: %s", application.config['PRIVILEGEDBNAME'], ref)
application.logger.info("Inserting tupple in %s.eida_temp_users: %s", application.config['RESIFINV_PGDATABASE'], ref)
cur.execute("""
insert into eida_temp_users (network_id, network, start_year, end_year, name, expires_at) values (%(networkid)s, %(networkcode)s, %(startyear)s, %(endyear)s, %(login)s, %(expires_at)s);
""", ref)
......@@ -140,7 +137,7 @@ def cleanup():
"""
Clean old temporary logins and passwords in both databases.
"""
logging.info("Cleaning up expired temporary accounts")
application.logger.info("Cleaning up expired temporary accounts")
rows_deleted = 0
try:
conn = psycopg2.connect(dbname= application.config['RESIFAUTH_PGDATABASE'],
......@@ -149,14 +146,14 @@ def cleanup():
user= application.config['RESIFAUTH_PGUSER'],
password = application.config['RESIFAUTH_PGPASSWORD'])
cur = conn.cursor()
logging.debug("Connected to users database")
application.logger.debug("Connected to users database")
cur.execute("delete from credentials where expires_at < now();")
cur.execute("delete from users where expires_at < now();")
rows_deleted = cur.rowcount
conn.commit()
conn.close()
except psycopg2.Error as e:
logging.error(e.pgerror)
application.logger.error(e.pgerror)
raise e
try:
......@@ -166,13 +163,13 @@ def cleanup():
user= application.config['RESIFINV_PGUSER'],
password = application.config['RESIFINV_PGPASSWORD'])
cur = conn.cursor()
logging.debug("Connected to privlieges database")
logging.debug("Deleting from privileges database")
application.logger.debug("Connected to privlieges database")
application.logger.debug("Deleting from privileges database")
cur.execute("delete from eida_temp_users where expires_at < now();")
conn.commit()
conn.close()
except Exception as e:
logging.error(e.pgerror)
application.logger.error(e.pgerror)
raise e
return Response("Deleted %d expired accounts."%(rows_deleted), status=200)
......@@ -180,23 +177,23 @@ def cleanup():
def auth():
login = ''
password = ''
logging.debug(request.mimetype)
application.logger.debug(request.mimetype)
data = request.get_data()
logging.debug("Data: %s", data)
application.logger.debug("Data: %s", data)
try:
verify_token_signature(data, application.config['GNUPG_HOMEDIR'])
tokendict = parse_input_data(data)
logging.info("Token signature OK: %s"%str(tokendict))
application.logger.info("Token signature OK: %s"%str(tokendict))
except ValueError as e:
logging.info("Token signature could not be checked: %s"%str(data))
application.logger.info("Token signature could not be checked: %s"%str(data))
return Response(str(e), status=415)
# Now we have a dictionary corresponding to the token's content.
# Verify validity
expiration_ts= datetime.datetime.strptime(tokendict['valid_until'], '%Y-%m-%dT%H:%M:%S.%fZ')
if (expiration_ts - datetime.datetime.now()).total_seconds() < 0:
logging.info("Token is expired")
application.logger.info("Token is expired")
return Response('Token is expired. Please generate a new one at https://geofon.gfz-potsdam.de/eas/', status=400)
logging.info("Token is valid")
application.logger.info("Token is valid")
# Compute a random login and password
login = ''.join(random.choices(string.ascii_uppercase + string.digits, k=14))
......@@ -209,13 +206,13 @@ def auth():
# Check membership and get FDSN references
fdsn_memberships = []
for em in tokendict['memberof'].split(';'):
logging.debug("EPOS membership: "+em)
application.logger.debug("EPOS membership: "+em)
if em in application.config['EPOS_FDSN_MAP']:
logging.debug(" ... is in epos fdsn map")
application.logger.debug(" ... is in epos fdsn map")
fdsn_memberships.append(application.config['EPOS_FDSN_MAP'][em])
if len(fdsn_memberships) > 0:
logging.debug("FDSN memberships: %s"%(fdsn_memberships))
application.logger.debug("FDSN memberships: %s"%(fdsn_memberships))
try:
register_privileges(login, fdsn_memberships)
except NameError as n:
......@@ -224,5 +221,5 @@ def auth():
return "%s:%s"%(login, password)
if __name__ == "__main__":
logging.info("Running in %s mode"%(application.config['ENVIRONMENT']))
application.logger.info("Running in %s mode"%(application.config['ENVIRONMENT']))
application.run(host='0.0.0.0')
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment