Exemple #1
0
def get_token():
    '''
    Returns an authentication token to interact with the service. 
    A non-admin client needs to provide a valid sessionid to get a token. 
    An admin client can request a token without a valid "sessionid" 
    and will be given access to all running sessions.
    
    :<json string clientid: human-readable id of the client
    :<json string apikey: client's apikey
    :<json string sessionid: UUID of the session. Optional for admins 
    :status 200: Successful request, returns the token
    :status 400: Not JSON object or missing parameters
    :status 401: Wrong credentials
    '''

    #Check if request is json and contains all the required fields
    required_fields = ["clientid", "apikey"]
    error = {}
            
    if not request.json or not (set(required_fields).issubset(request.json)):
        error["message"] = "Invalid request. Please try again."
        error["code"] = 400 
        return jsonify(error = error), status.HTTP_400_BAD_REQUEST
    
    else:
        clientid = request.json['clientid']
        apikey = request.json['apikey']
        
        try:
            sessionid = request.json['sessionid']            
        except KeyError:
            sessionid = False
      
        if ( sessionid and ( not controller.is_uuid_valid(sessionid) ) ):
            error["message"] = "Invalid sessionid"
            error["code"] = 400 
            return jsonify(error=error), status.HTTP_400_BAD_REQUEST
            
        try:
            #######################################
            # Success
            #######################################
            
            token = controller.client_authenticate(clientid, apikey, sessionid)
            
            return jsonify(token=token.decode('ascii')), status.HTTP_200_OK


        except (AuthenticationFailed, NotAuthenticated) as e:
            error["message"] = "Could not authenticate. Please check your credentials and try again" 
            error["code"] = 401 
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED 
        
        except TokenExpiredException as e:
            error["message"] = "Your token expired. Please generate another one." 
            error["code"] = 401 
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED
        
        except InvalidGamingSessionException as e:
            error["message"] = "Invalid gaming session. Did the player authorize the use of their data?" 
            error["code"] = 401 
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED
        
        except Exception as e:
            LOG.error(e, exc_info=True)
            error["message"] = "Unexpected error. The developers have been informed." 
            error["code"] = 500
            return jsonify(error=error), status.HTTP_500_INTERNAL_SERVER_ERROR
Exemple #2
0
def get_token():
    '''
    Returns an authentication token to interact with the service. 
    A non-admin client needs to provide a valid sessionid to get a token. 
    An admin client can request a token without a valid "sessionid" 
    and will be given access to all running sessions.
    
    :<json string clientid: human-readable id of the client
    :<json string apikey: client's apikey
    :<json string sessionid: UUID of the session. Optional for admins 
    :status 200: Successful request, returns the token
    :status 400: Not JSON object or missing parameters
    :status 401: Wrong credentials
    '''

    #Check if request is json and contains all the required fields
    required_fields = ["clientid", "apikey"]
    error = {}

    if not request.json or not (set(required_fields).issubset(request.json)):
        error["message"] = "Invalid request. Please try again."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST

    else:
        clientid = request.json['clientid']
        apikey = request.json['apikey']

        try:
            sessionid = request.json['sessionid']
        except KeyError:
            sessionid = False

        if (sessionid and (not controller.is_uuid_valid(sessionid))):
            error["message"] = "Invalid sessionid"
            error["code"] = 400
            return jsonify(error=error), status.HTTP_400_BAD_REQUEST

        try:
            #######################################
            # Success
            #######################################

            token = controller.client_authenticate(clientid, apikey, sessionid)

            return jsonify(token=token.decode('ascii')), status.HTTP_200_OK

        except (AuthenticationFailed, NotAuthenticated) as e:
            error[
                "message"] = "Could not authenticate. Please check your credentials and try again"
            error["code"] = 401
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

        except TokenExpiredException as e:
            error[
                "message"] = "Your token expired. Please generate another one."
            error["code"] = 401
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

        except InvalidGamingSessionException as e:
            error[
                "message"] = "Invalid gaming session. Did the player authorize the use of their data?"
            error["code"] = 401
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

        except Exception as e:
            LOG.error(e, exc_info=True)
            error[
                "message"] = "Unexpected error. The developers have been informed."
            error["code"] = 500
            return jsonify(error=error), status.HTTP_500_INTERNAL_SERVER_ERROR
Exemple #3
0
def commit_event(sessionid):
    '''
    Submits a new event related to the given sessionid. Client must be authorized
    to write to the session.
    
    :param string sessionid: 
    :reqheader X-AUTH-TOKEN: A valid token obtained from :http:get:`/token`
    :<jsonarr string events: list of JSON game events
    :status 201: Event created successfully
    :status 400: Not JSON object or missing parameters
    :status 401: Token not authorized to write to session
    :status 404: Sessionid not found
    :responseheader Content-Type: application/json
    :responseheader X-Total-Count: the total number of results created
    :>jsonarr string id: Internal id of the created client
    :>jsonarr string gameevent: JSON representation of the event
    :>jsonarr string _links: Link to the resource and related entities (if any)
    '''

 
    json_package = False
    error={}
    try:
        json_package = request.json
    except JSONDecodeError as e:
        error["message"] = "Invalid request, not valid JSON. Please try again." 
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST
    
    auth_token = request.headers.get('X-AUTH-TOKEN', None)

    if not auth_token:
        error["message"] = "Missing header ['X-AUTH-TOKEN']." 
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST
    
    #Check if request is json and contains all the required fields
    required_fields = ["events"] 
    if (not json_package) or (not set(required_fields).issubset(json_package)):
        error["message"] = "Invalid request. Please try again." 
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST   
    else:
        #Check if events is valid json or xml
#         LOG.debug(type(json_package))
#         LOG.debug(json_package)
#         LOG.debug(json_package["events"])
        is_json = controller.is_json(json_package["events"])
        
        if (not is_json):
            error["message"] = "Invalid request. Please format your gameevent as json." 
            error["code"] = 400
            return jsonify(error=error), status.HTTP_400_BAD_REQUEST
        
        if (not controller.is_uuid_valid(sessionid)):
            error["message"] = "Sessionid not found" 
            error["code"] = 404
            return jsonify(error=error), status.HTTP_404_NOT_FOUND
            
        try:
            ########################
            # Success
            ########################
            
            #Record the event         
            events = controller.record_gameevent(sessionid, auth_token, json_package["events"])
            
            num_results = len(events)
            #sessions_response = [session.as_dict() for session in sessions] 
            events_response = simplejson.dumps([event.as_hateoas() for event in events], indent=2)
                           
            response = make_response(events_response, status.HTTP_201_CREATED)
            response.headers["X-Total-Count"] = num_results
            response.headers["Content-Type"] = "application/json"
            
            return response

           
        except AuthenticationFailed as e:
            error["message"] = "Could not authenticate. Please check your token and try again." 
            error["code"] = 401
            #LOG.warning("Authentication failure when trying to record game event.")
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED
        
        except (NotFound) as e:
            error["message"] = "SessionID not in the database. If you believe this is an error, contact the developers." 
            error["code"] = 404
            return jsonify(error=error), status.HTTP_404_NOT_FOUND
        
        except NotAcceptable as e:
            error["message"] = e.args 
            error["code"] = 400
            return jsonify(error=error), status.HTTP_400_BAD_REQUEST  
        
        except Exception as e:
            LOG.error(e.args, exc_info=True)
            error["message"] = "Internal error. Please try again."
            error["code"] = 500
            return jsonify(error=error), status.HTTP_500_INTERNAL_SERVER_ERROR
Exemple #4
0
def commit_event(sessionid):
    '''
    Submits a new event related to the given sessionid. Client must be authorized
    to write to the session.
    
    :param string sessionid: 
    :reqheader X-AUTH-TOKEN: A valid token obtained from :http:get:`/token`
    :<jsonarr string events: list of JSON game events
    :status 201: Event created successfully
    :status 400: Not JSON object or missing parameters
    :status 401: Token not authorized to write to session
    :status 404: Sessionid not found
    :responseheader Content-Type: application/json
    :responseheader X-Total-Count: the total number of results created
    :>jsonarr string id: Internal id of the created client
    :>jsonarr string gameevent: JSON representation of the event
    :>jsonarr string _links: Link to the resource and related entities (if any)
    '''

    json_package = False
    error = {}
    try:
        json_package = request.json
    except JSONDecodeError as e:
        error["message"] = "Invalid request, not valid JSON. Please try again."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST

    auth_token = request.headers.get('X-AUTH-TOKEN', None)

    if not auth_token:
        error["message"] = "Missing header ['X-AUTH-TOKEN']."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST

    #Check if request is json and contains all the required fields
    required_fields = ["events"]
    if (not json_package) or (not set(required_fields).issubset(json_package)):
        error["message"] = "Invalid request. Please try again."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST
    else:
        #Check if events is valid json or xml
        #         LOG.debug(type(json_package))
        #         LOG.debug(json_package)
        #         LOG.debug(json_package["events"])
        is_json = controller.is_json(json_package["events"])

        if (not is_json):
            error[
                "message"] = "Invalid request. Please format your gameevent as json."
            error["code"] = 400
            return jsonify(error=error), status.HTTP_400_BAD_REQUEST

        if (not controller.is_uuid_valid(sessionid)):
            error["message"] = "Sessionid not found"
            error["code"] = 404
            return jsonify(error=error), status.HTTP_404_NOT_FOUND

        try:
            ########################
            # Success
            ########################

            #Record the event
            events = controller.record_gameevent(sessionid, auth_token,
                                                 json_package["events"])

            num_results = len(events)
            #sessions_response = [session.as_dict() for session in sessions]
            events_response = simplejson.dumps(
                [event.as_hateoas() for event in events], indent=2)

            response = make_response(events_response, status.HTTP_201_CREATED)
            response.headers["X-Total-Count"] = num_results
            response.headers["Content-Type"] = "application/json"

            return response

        except AuthenticationFailed as e:
            error[
                "message"] = "Could not authenticate. Please check your token and try again."
            error["code"] = 401
            #LOG.warning("Authentication failure when trying to record game event.")
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

        except (NotFound) as e:
            error[
                "message"] = "SessionID not in the database. If you believe this is an error, contact the developers."
            error["code"] = 404
            return jsonify(error=error), status.HTTP_404_NOT_FOUND

        except NotAcceptable as e:
            error["message"] = e.args
            error["code"] = 400
            return jsonify(error=error), status.HTTP_400_BAD_REQUEST

        except Exception as e:
            LOG.error(e.args, exc_info=True)
            error["message"] = "Internal error. Please try again."
            error["code"] = 500
            return jsonify(error=error), status.HTTP_500_INTERNAL_SERVER_ERROR