Commit e0b7a116 authored by sebastien letort's avatar sebastien letort

New class in helpers to prefix log message. I used it in api views and jwt views.

parent 86092459
......@@ -7,7 +7,7 @@ from django.http import JsonResponse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from main.helpers import upload_data, get_base_url, lookup_job_file, get_request_user
from main.helpers import upload_data, get_base_url, lookup_job_file, get_request_user, LoggerAdapter
from main.mixins import JobAuthMixin
from main.models import Job, Webapp, JobQueue
......@@ -51,10 +51,14 @@ class APIJobView(JobAuthMixin, View):
@csrf_exempt
def jobs(request):
o_log = new LoggerAdapter(log, {'prefix': "API-jobs"})
o_log.info("request received")
user = get_request_user(request)
if not user:
log.info("API request without http authorisation %s %s %s", request.META['HTTP_USER_AGENT'],
request.META['REMOTE_ADDR'], request.META['QUERY_STRING'])
o_log.info("%s request without http authorisation %s %s %s",
request.META['HTTP_USER_AGENT'],
request.META['REMOTE_ADDR'],
request.META['QUERY_STRING'])
return JsonResponse({'error': 'API request without http authorisation'}, status=401)
if request.POST['job[webapp_id]'].isdigit():
......@@ -72,10 +76,10 @@ def jobs(request):
except JobQueue.DoesNotExist:
return JsonResponse({'error': 'Unknown queue'}, status=400)
log.info("Job submit by user %s", user)
o_log.info("Job submit by user %s", user)
job = Job.objects.create(param=request.POST.get('job[param]', ''), queue=queue, webapp=app, user=user)
if app.get_webapp_version() is None:
log.debug('No usable versions')
o_log.debug('No usable versions')
return JsonResponse({'error': "This app is not yet published"}, status=404)
job.version = app.get_webapp_version().number # TODO: add version selection in the api
upload_data(request.FILES.values(), job)
......@@ -89,6 +93,7 @@ def jobs(request):
# start the job
job.state = Job.WAITING
job.save()
o_log.info("request successfully submitted.")
return JsonResponse(job_response(job, request))
......
......@@ -36,6 +36,15 @@ REDIS_MESSAGE_WEBAPP_UPDATED = "webapp:%d"
##################################################
class LoggerAdapter(logging.LoggerAdapter):
"""This class makes all log message prefixed.
Usage: log = LoggerAdapter("your prefix", logging.getLogger('allgo'))
cf: https://docs.python.org/3/howto/logging-cookbook.html
https://stackoverflow.com/questions/30002070/create-logger-that-prefixes-log-messages"""
def process(self, msg, kwargs):
return '[%s] %s' % (self.extra['prefix'], msg), kwargs
# global redis connection pool
_redis_connection_pool = None
......
......@@ -7,7 +7,9 @@ from urllib.parse import urlencode
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.shortcuts import redirect
from main.models import User, AllgoUser, Runner
from main.helpers import LoggerAdapter
from .tokens import Token
......@@ -41,26 +43,35 @@ def jwt_auth(request):
:param request:
:return:
"""
o_log = new LoggerAdapter(log, {'prefix': "jwt_auth"})
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
if not auth_header:
log.info("Token request without http authorisation %s %s %s", request.META['HTTP_USER_AGENT'],
request.META['REMOTE_ADDR'], request.META['QUERY_STRING'])
o_log.info("Token request without http authorisation %s %s %s",
request.META['HTTP_USER_AGENT'],
request.META['REMOTE_ADDR'],
request.META['QUERY_STRING'])
return HttpResponse(status=401)
token_type, credentials = auth_header.split(' ')
username, password = base64.b64decode(credentials).decode('utf-8').split(':')
log.debug('HTTP_AUTHORIZATION %s username %s', auth_header, username)
o_log.debug('HTTP_AUTHORIZATION %s', auth_header)
o_log.debug('username %s', username)
o_log.debug('password %s', password)
o_log.debug('runners : %s', Runner.objects.all())
user = Runner.objects.get(token=password)
o_log.debug('user : %s', user)
if username == "$token" and Runner.objects.get(token=password):
log.info("Token for runner called")
o_log.info("Token for runner called")
user = Runner.objects.get(token=password)
else:
o_log.info("No $token user or no Runner defined.")
try:
user = User.objects.get(email=username)
except User.DoesNotExist:
log.warning("Token request but user doest not exist")
o_log.warning("Token request but user doest not exist")
return HttpResponse(status=401)
password_valid = user.check_password(password)
if token_type != 'Basic' or not password_valid:
log.info("Token request but user password mismatch")
o_log.info("Token request but user password mismatch")
return HttpResponse(status=401)
service = request.GET['service']
......@@ -78,7 +89,7 @@ def jwt_auth(request):
actions = params[2].split(',')
authorized_actions = get_allowed_actions(user, scope, actions, request) if scope else []
log.info("Token authorized actions %s %s %s", authorized_actions, user, scope)
o_log.info("Token authorized actions %s %s %s", authorized_actions, user, scope)
token = Token(service, typ, name, authorized_actions)
encoded_token = token.encode_token()
......
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