def api_error(api_name, message, request=None): if request is not None: client = get_ip(request) log_error("API", "%s (%s): %s" % (api_name.upper(), client, message)) del client else: log_error("API", "%s (NO-IP): %s" % (api_name.upper(), message))
def api_event(game_id, event_message): try: from scorebot_game.models import game_event_create game_event_create(game_id, event_message) except Exception as eventError: log_error("EVENT", str(eventError))
def run(self): self.running = True print('Starting Daemon "%s".' % self.entry.name) log_info('DAEMON', 'Starting Daemon "%s"..' % self.entry.name) try: self.entry.method() except Exception as threadError: log_error( 'DAEMON', 'Daemon "%s" encountered an error when running! Exception: "%s"' % (self.entry.name, str(threadError))) log_info('DAEMON', 'Daemon "%s" finished running.' % self.entry.name) self.running = False self.entry.del_stop()
def load_daemons(self, daemon_dir): if not os.path.isdir(daemon_dir): return daemon_list = os.listdir(daemon_dir) if len(daemon_list) > 0: for daemon_file in daemon_list: if ".py" in daemon_file and not ( " " in daemon_file or "-" in daemon_file or "-" in daemon_file ): try: daemon_loader = importlib.util.spec_from_file_location( daemon_file.replace(".py", ""), os.path.join(daemon_dir, daemon_file), ) if daemon_loader is None: continue daemon_class = importlib.util.module_from_spec(daemon_loader) if daemon_class is None: continue daemon_loader.loader.exec_module(daemon_class) try: daemon_class_def = getattr(daemon_class, "init_daemon") if daemon_class_def is not None and callable( daemon_class_def ): daemon_entry = daemon_class_def() if daemon_entry is not None: self.daemons.append(daemon_entry) log_debug( "DAEMON", 'Loaded Daemon "%s"!' % daemon_class.__name__, ) del daemon_class del daemon_loader except AttributeError: log_warning( "DAEMON", 'Daemon class for "%s" does not have the "init_daemon" method, ignoring!' % daemon_class.__name__, ) except Exception as loadError: log_error( "DAEMON", 'An error ocured when attempting to load Daemon "%s"! Exception: "%s' % (daemon_file, str(loadError)), ) del daemon_list
def _authenticate_wrapped(*args, **kwargs): http_request = None for argument in args: if isinstance(argument, WSGIRequest): http_request = argument break if http_request is None: for value in kwargs.values(): if isinstance(value, WSGIRequest): http_request = value break if http_request is None: log_error( 'API', 'AUTH (NO-IP): Connected but no HTTP headers were found!') return HttpResponseBadRequest( content='{"message": "SBE API: Invalid HTTP connection!"}') http_ip = get_ip(http_request) if 'HTTP_SBE_AUTH' not in http_request.META: log_error( 'API', 'AUTH (%s): Attempted to connect without a proper authentication header!' % http_ip) return HttpResponseForbidden( content= '{"message": "SBE API: Missing authentication header!"}') try: http_request.authentication = AccessToken.objects.get( token__uuid=uuid.UUID(http_request.META['HTTP_SBE_AUTH'])) except ValueError: log_error( 'API', 'AUTH (%s): Attempted to connect with an invalid authentication token format "%s"!' % (http_ip, http_request.META['HTTP_SBE_AUTH'])) return HttpResponseForbidden( content= '{"message": "SBE API: Invalid authentication token format!"}' ) except AccessToken.DoesNotExist: log_error( 'API', 'AUTH (%s): Attempted to connect with an non-existent authentication token "%s"!' % (http_ip, http_request.META['HTTP_SBE_AUTH'])) return HttpResponseForbidden( content= '{"message": "SBE API: Invalid authentication token!"}') except AccessToken.MultipleObjectsReturned: log_error( 'API', 'AUTH (%s): Submitted token returned multiple entries, token "%s" must be invalid!' % (http_ip, http_request.META['HTTP_SBE_AUTH'])) return HttpResponseForbidden( content= '{"message": "SBE API: Invalid authentication token!"}') if not http_request.authentication: log_error( 'API', 'AUTH (%s): Attempted to use an expired authentication token "%s"!' % (http_ip, http_request.authentication.token.uuid)) return HttpResponseForbidden( content= '{"message": "SBE API: Authentication token is expired!"}') if requires is not None: if isinstance(requires, list): for requires_item in requires: if not http_request.authentication[requires_item]: log_error( 'API', 'AUTH (%s): Attempted to access the API without the proper ' 'permissions! (%s)' % (http_ip, str(requires_item))) return HttpResponseForbidden( content= '{"message": "SBE API: Authentication Token missing "%s" permission!"}' % str(requires_item)) elif isinstance(requires, str) or isinstance(requires, int): if not http_request.authentication[requires]: log_error( 'API', 'AUTH (%s): Attempted to access the API without the proper ' 'permissions! (%s)' % (http_ip, str(requires))) return HttpResponseForbidden( content= '{"message": "SBE API: Authentication Token missing "%s" permission!"}' % str(requires)) log_debug( 'API', 'AUTH (%s): Successfully authenticated to the SBE API. Passing control to function "%s".' % (http_ip, auth_function.__qualname__)) return auth_function(*args, **kwargs)
def game_team_from_token(request, api_name, json_field, offense=True, beacon=False, fields=None): client = get_ip(request) try: decoded_data = request.body.decode('UTF-8') except UnicodeDecodeError: log_error( 'API', '%s (%s): Data submitted by is not encoded properly!' % (api_name.upper(), client)) return None, None, None, HttpResponseBadRequest( content= '{"message": "SBE API: Incorrect encoding, please use UTF-8!"}') try: json_data = json.loads(decoded_data) except json.decoder.JSONDecodeError: log_error( 'API', '%s (%s): Data submitted is not in a valid JSON format!' % (api_name.upper(), client)) return None, None, None, HttpResponseBadRequest( content='{"message": "SBE API: Not in a valid JSON format!"}') if json_field not in json_data: log_error( 'API', '%s (%s): Data submitted is missing field "%s"!' % (api_name.upper(), client, json_field)) return None, None, None, HttpResponseBadRequest( content='{"message": "SBE API: Missing JSON field \'%s\'!"}' % json_field) if fields is not None and isinstance(fields, list): for field in fields: if field not in json_data: log_error( 'API', '%s (%s): Data submitted is missing field "%s"!' % (api_name.upper(), client, field)) return None, None, None, HttpResponseBadRequest( content='{"message": "SBE API: Missing JSON field \'%s\'!"}' % field) log_debug( 'API', '%s (%s): Team Token submitted is "%s"!' % (api_name.upper(), client, json_data[json_field])) try: token = Token.objects.get(uuid=uuid.UUID(json_data[json_field])) except ValueError: log_error( 'API', '%s (%s): Team Token submitted is not a valid format!' % (api_name.upper(), client)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Team Token is not a valid format!"}' ) except Token.DoesNotExist: log_error( 'API', '%s (%s): Team Token submitted does not exist!' % (api_name.upper(), client)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Team Token is not valid!"}') except Token.MultipleObjectsReturned: log_error( 'API', '%s (%s): Team Token submitted returns multiple objects, must be invalid!' % (api_name.upper(), client)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Team Token is not valid!"}') if token is None: log_error( 'API', '%s (%s): Team Token submitted does not exist!' % (api_name.upper(), client)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Team Token is not valid!"}') if not token.__bool__(): log_error( 'API', '%s (%s): Team Token submitted is expired!' % (api_name.upper(), client)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Team Token is expired!"}') try: if beacon: team = GameTeam.objects.get(beacons__in=[token]) else: team = GameTeam.objects.get(token=token) except GameTeam.DoesNotExist: log_error( 'API', '%s (%s): Token submitted is not linked to a Team!' % (api_name.upper(), client)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Not a Team Token!"}') except GameTeam.MultipleObjectsReturned: log_error( 'API', '%s (%s): Token submitted by matched multiple Teams, must be invalid!' % (api_name.upper(), client)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Team Token is not valid!"}') log_debug( 'API', '%s (%s): Team "%s" was authenticated to the API!' % (api_name.upper(), client, team.get_canonical_name())) if offense: if not team.offensive: log_error( 'API', '%s (%s): Attempted to authenticate a non Offensive team "%s" to an Offensive service!' % (api_name.upper(), client, team.get_canonical_name())) return None, None, None, HttpResponseForbidden( content= '{"message": "SBE API: Team is not authorized for this type of request!"}' ) if team.game.status != CONST_GAME_GAME_RUNNING: log_error( 'API', '%s (%s): Game "%s" submitted is not Running!' % (api_name.upper(), client, team.game.name)) return None, None, None, HttpResponseForbidden( content='{"message": "SBE API: Team Game "%s" is not Running!"}' % team.game.name) del decoded_data return team, token, json_data, None
from django.conf import settings from django.contrib import admin from django.utils import timezone from scorebot_game.models import GameTeam from scorebot_api import admin as sbe_admin from django.core.handlers.wsgi import WSGIRequest from scorebot_core.models import AccessToken, Token from scorebot.utils.logger import log_debug, log_error from scorebot.utils.constants import CONST_GAME_GAME_RUNNING from django.http import HttpResponseBadRequest, HttpResponseForbidden try: from ipware.ip import get_ip except ImportError: log_error( 'BACKEND', 'Django IPware is missing, all IP address lookups will return fake data. ' 'Please use "pip install django-ipware" to install the plugin.') def get_ip(request): return 'ERR-DJANGO-IPWARE-MISSING' _MODELS_REGISTERED = [] scorebot.utils.get_ip = get_ip def get_client_ip(request): return get_ip(request) def authenticate(requires=None):