Ejemplo n.º 1
0
def profiler(check,
             log_msg: str = '',
             log: bool = True,
             kwargs: dict = None,
             sort: str = 'tottime'):
    # note: https://stackoverflow.com/questions/10326936/sort-cprofile-output-by-percall-when-profiling-a-python-script
    from cProfile import Profile
    from pstats import Stats
    from io import StringIO

    _ = Profile()
    _.enable()

    if kwargs is None:
        kwargs = {}

    check_response = check(**kwargs)

    _.disable()
    result = StringIO()
    Stats(_, stream=result).sort_stats(sort).print_stats(DEBUG_PROFILE_TOP_N)
    cleaned_result = result.getvalue().splitlines()[:-1]
    del cleaned_result[1:5]
    cleaned_result = '\n'.join(cleaned_result)

    if log:
        web_log(output=f"{log_msg}:\n{cleaned_result}", level=8)

    return check_response
Ejemplo n.º 2
0
 def denied(request):
     error_source_url = request.build_absolute_uri(
         request.META['QUERY_STRING'].split('=', 1)[1])
     web_log(
         output=
         f"{error_source_url} - Got error 403 - Access denied for user \"{request.user}\""
     )
     return logout_check(request=request, default=handler403(request))
Ejemplo n.º 3
0
def handler_log(output: dict, status: int):
    if output['request'] is None:
        web_log(output=f"Got error {status} - {output['msg']}")

    else:
        web_log(
            output=
            f"{output['request'].build_absolute_uri()} - Got error {status} - {output['msg']}"
        )
Ejemplo n.º 4
0
def api_sock(request, sock_data: dict = None):
    def _log(output: str, level: int):
        web_log(output=output, level=level)

    if sock_data is not None:
        sock_config = sock_data

    else:
        sock_config = request.POST

    mapping_key = sock_config['type']
    path_id = sock_config['id']
    data = sock_config['do']
    timeout = sock_config['timeout'] if 'timeout' in sock_config else None

    path = f'ga.core.{mapping[mapping_key]}.{path_id}'
    response = Client(path=path, logger=_log, timeout=timeout).post(data)
    web_log(output=
            f"Got socket response '{response}' by executing '{path} = {data}'",
            level=8)

    if type(response) == dict and 'data' in response:
        response = response['data']

    try:
        response = json_loads(response.lower())

    except (AttributeError, TypeError, JSONDecodeError):
        pass

    web_log(
        output=
        f"Got socket response '{response}' (parsed) by executing '{path} = {data}'",
        level=6)

    if sock_data is None and 'HTTP_REFERER' in request.META and request.META[
            'HTTP_REFERER'].find('/config/') != -1:
        result = 'Action failed!'

        if type(response) == bool and response:
            result = 'Action succeeded!'

        return redirect(
            append_to_url(url=request.META['HTTP_REFERER'],
                          append={'response': result}))

    elif sock_data is not None:
        return response

    else:
        return JsonResponse({'response': response})
Ejemplo n.º 5
0
def handler500(exc):
    output = input_check(exc)
    handler_log(output=output, status=500)

    if get_server_config(setting='security') == 0:
        web_log(output=f"{format_exc(limit=LOG_MAX_TRACEBACK_LENGTH)}",
                level=2)

    return render(output['request'],
                  '500.html',
                  context={
                      'request': output['request'],
                      'error_msg': output['msg']
                  })
Ejemplo n.º 6
0
    def api(request, typ: str):
        # no logout check needed since there is no logout button at this route
        if typ == 'data':
            return ApiData(request=request).go()

        elif typ == 'chart':
            return api_chart(request=request)

        elif typ == 'sock':
            return api_sock(request=request)

        web_log(
            output=
            f"{request.build_absolute_uri()} - Got error 404 - api not implemented"
        )
        return handler404_api()
Ejemplo n.º 7
0
    def _update(self):
        user = User.objects.get(username=self.request.POST['current_name'])
        user.username = self.request.POST['name']
        user.email = self.request.POST['email']
        privs = self.request.POST['privileges']
        pwd = self.request.POST['password']

        if pwd != ' ' and pwd != config.CENSOR_STRING:
            user.set_password(pwd)

        user.groups.add(Group.objects.get(name=config.GA_USER_GROUP))

        try:
            for grp, value in self.GA_GROUPS.items():
                grp_obj = Group.objects.get(name=grp)
                if privs.find(value['pretty']) != -1:
                    user.groups.add(grp_obj)
                    if value['staff']:
                        user.is_staff = True

                else:
                    user.groups.remove(grp_obj)

            self._log_action(action='updated')
            msg = f"User '{self.request.POST['name']}' successfully updated!"
            msg_style = 'success'

        except Exception as error:
            web_log(
                output=f"User '{self.request.POST['name']}' could not be added to a group! It could be that the group does not exist! Error: {error}",
                level=3
            )
            msg = f"User '{self.request.POST['name']}' could not be added to all groups!"
            msg_style = 'warning'

        user.save()

        if self.request.POST['name'] == str(self.request.user):
            return redirect(config.LOGOUT_URL)

        return self._list(msg=msg, msg_style=msg_style)
Ejemplo n.º 8
0
def service_action(request, service: str):
    action = request.POST['service_action']
    web_log(output=f"{action}ing service {service}")

    if action in ['start', 'stop', 'reload', 'restart']:
        web_log(
            output=
            f"{request.META['PATH_INFO']} - action \"{action} service {service}\" "
            f"was executed by user {request.user} from remote ip {get_client_ip(request)}"
        )
        web_subprocess(command=f"sudo {SYSTEMCTL} {action} {service}")
        sleep(1)

    else:
        web_log(output=f"Got unsupported service action: '{action}'")
Ejemplo n.º 9
0
 def _log(output: str, level: int):
     web_log(output=output, level=level)
Ejemplo n.º 10
0
 def api_denied(request):
     error_source_url = request.build_absolute_uri(
         request.META['QUERY_STRING'].split('=', 1)[1])
     web_log(
         output=f"{error_source_url} - Got error 403 - api access denied")
     return handler403_api()
Ejemplo n.º 11
0
 def _log_action(self, action: str, level: int = 3):
     web_log(
         output=f"User '{self.request.POST['name']}' was {action} by user '{self.request.user}' from client ip '{get_client_ip(self.request)}'",
         level=level,
     )