async def refresh_token(self, raw_data): try: data = self.validate_data(raw_data) access_token = extract_and_decode_token(self.app, data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) except (InvalidTokenError, InvalidSignatureError) as exc: return Response.from_error(TOKEN_ERROR, str(exc)) user_id = access_token.get('user_id', None) user = await self.get_user_by_id(user_id) if not user: return Response.from_error(NOT_FOUND_ERROR, "User wasn't found.") refresh_token = data['refresh_token'].strip() key = get_redis_key_by_user(self.app, user.username) existing_refresh_token = await get_refresh_token_from_redis( self.app.redis, key) if existing_refresh_token != refresh_token: return Response.from_error( TOKEN_ERROR, "Specified an invalid `refresh_token`.") secret = self.app.config["JWT_SECRET_KEY"] algorithm = self.app.config["JWT_ALGORITHM"] payload = build_payload(self.app, extra_data={"user_id": str(user.pk)}) new_access_token = generate_access_token(payload, secret, algorithm) response = { self.app.config["JWT_ACCESS_TOKEN_FIELD_NAME"]: new_access_token } return Response.with_content(response)
def generate_response(self, raw_data): data = json.loads(raw_data.strip()) if 'name' not in data.keys() and 'version' not in data.keys(): return Response.from_error(VALIDATION_ERROR, self.ERROR_DESCRIPTION) return Response.with_content("OK")
def verify_token(self, raw_data): try: data = self.validate_data(raw_data) extract_and_decode_token(self.app, data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) except (InvalidTokenError, InvalidSignatureError) as exc: return Response.from_error(TOKEN_ERROR, str(exc)) return Response.with_content({"is_valid": True})
async def register_game_server(self, raw_data): try: data = await self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) object_id = ObjectId(data['id']) if 'id' in data.keys() else ObjectId() await self.game_server_document.collection.replace_one( {'_id': object_id}, replacement=data, upsert=True ) return Response.with_content({'id': str(object_id)})
async def update_player_statistic(self, raw_data): try: document, data = await self.validate_data(raw_data) document._data._data.update(data) await document.commit() except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) except ValueError: return Response.from_error(NOT_FOUND_ERROR, self.PLAYER_NOT_FOUND_ERROR) return Response.with_content(document.dump())
async def init_player_statistic(self, raw_data): try: data = await self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) await self.player_statistic_document.collection.replace_one( {'player_id': data['player_id']}, replacement=data, upsert=True) document = await self.player_statistic_document.find_one( {'player_id': data['player_id']}) return Response.with_content(document.dump())
async def retrieve_player_statistic(self, raw_data): try: data = await self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) document = await self.player_statistic_document.find_one( {'player_id': data['player_id']}) if document is None: return Response.from_error(NOT_FOUND_ERROR, self.PLAYER_NOT_FOUND_ERROR) return Response.with_content(document.dump())
async def process_request(self, channel, body, envelope, properties): try: data = self.validate_data(body) game_mode = self.app.game_modes[data["game-mode"]] player = data["new-player"] grouped_players = data["grouped-players"] response = { "content": self.seed_player(game_mode, player, grouped_players) } except ValidationError as exc: response = Response.from_error(VALIDATION_ERROR, exc.normalized_messages()).data response["event-name"] = properties.correlation_id if properties.reply_to: await channel.publish(json.dumps(response), exchange_name=self.RESPONSE_EXCHANGE_NAME, routing_key=properties.reply_to, properties={ 'content_type': self.CONTENT_TYPE, 'delivery_mode': 2, 'correlation_id': properties.correlation_id }, mandatory=True) await channel.basic_client_ack(delivery_tag=envelope.delivery_tag)
async def generate_token(self, raw_data): try: data = self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) user = await self.user_document.find_one( {"username": data["username"]}) if not user or (user and not user.verify_password(data["password"])): return Response.from_error( NOT_FOUND_ERROR, "User wasn't found or specified an invalid password.") payload = build_payload(self.app, extra_data={"user_id": str(user.pk)}) response = await generate_token_pair(self.app, payload, user.username) return Response.with_content(response)
async def get_user_profile(self, raw_data): try: token = self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) except InvalidTokenError as exc: return Response.from_error(TOKEN_ERROR, str(exc)) user_id = token.get('user_id', None) user = await self.user_document.find_one({"_id": ObjectId(user_id)}) if not user: return Response.from_error(NOT_FOUND_ERROR, "User was not found.") serializer = self.schema() serialized_user = serializer.dump(user).data serialized_user['permissions'] = await self.collect_user_permissions(user) return Response.with_content(serialized_user)
async def register_game_client(self, raw_data): try: data = await self.validate_data(raw_data) await self.validate_username_for_uniqueness(data["username"]) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) user_groups = await self.group_document.collection \ .find({"name": self.DEFAULT_GROUP_NAME}) \ .collation({"locale": "en", "strength": 2}) \ .to_list(1) data['groups'] = [group['_id'] for group in user_groups] user = self.user_document(**data) await user.commit() serializer = self.schema() return Response.with_content(serializer.dump(user).data)
async def register_microservice(self, raw_data): try: data = await self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) old_microservice = await self.microservice_document.find_one( {'name': data['name']}) old_permissions = [obj.pk for obj in old_microservice.permissions ] if old_microservice else [] # NOQA new_permissions = data['permissions'][:] await self.microservice_document.collection.replace_one( {'name': data['name']}, replacement=data, upsert=True) self.app.loop.create_task( self.update_groups(old_permissions, new_permissions)) return Response.with_content("OK")
async def get_game_server(self, raw_data): try: data = await self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) pipeline = [{ '$match': { '$and': [{ 'available_slots': { '$gte': data['required-slots'] } }, { "game_mode": data['game-mode'] }] } }, { '$sample': { 'size': 1 } }, { '$addFields': { "available_slots": { "$subtract": ["$available_slots", data['required-slots']] } } }] result = await self.game_server_document.collection.aggregate( pipeline).to_list(1) if result: document_updated_data = result[0] document_id = document_updated_data.pop('_id') await self.game_server_document.collection.update_one( {'_id': document_id}, {'$set': document_updated_data}) serializer = self.schema() document = serializer.dump(document_updated_data).data else: document = None return Response.with_content(document)
async def update_game_server(self, raw_data): try: data = await self.validate_data(raw_data) except ValidationError as exc: return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) document_id = ObjectId(data['id']) document = await self.game_server_document.find_one( {'_id': document_id}) if not document: return Response.from_error( NOT_FOUND_ERROR, "The requested game server was not found.") document.available_slots += data['freed_slots'] await document.commit() serializer = self.response_schema() return Response.with_content(serializer.dump(document).data)
def test_with_content_class_method(data, event_name): response = Response.with_content(data, event_name) assert isinstance(response, Response) assert isinstance(response.data, dict) assert Response.CONTENT_FIELD_NAME in response.data.keys() assert response.data[Response.CONTENT_FIELD_NAME] == data assert Response.EVENT_FIELD_NAME in response.data.keys() assert response.data[Response.EVENT_FIELD_NAME] == event_name
def test_from_error_class_method(error_type, message, event_name): response = Response.from_error(error_type, message, event_name) assert isinstance(response, Response) assert isinstance(response.data, dict) assert Response.EVENT_FIELD_NAME in response.data.keys() assert response.data[Response.EVENT_FIELD_NAME] == event_name assert Response.ERROR_FIELD_NAME in response.data.keys() assert Response.ERROR_TYPE_FIELD_NAME in response.data[ Response.ERROR_FIELD_NAME].keys() assert response.data[Response.ERROR_FIELD_NAME][ Response.ERROR_TYPE_FIELD_NAME] == error_type assert Response.ERROR_DETAILS_FIELD_NAME in response.data[ Response.ERROR_FIELD_NAME].keys() assert response.data[Response.ERROR_FIELD_NAME][ Response.ERROR_DETAILS_FIELD_NAME] == message
def test_from_error_with_a_message_without_the_period_in_the_end( error_type, message, event_name): response = Response.from_error(error_type, message, event_name) assert isinstance(response, Response) assert isinstance(response.data, dict) assert Response.EVENT_FIELD_NAME in response.data.keys() assert response.data[Response.EVENT_FIELD_NAME] == event_name assert Response.ERROR_FIELD_NAME in response.data.keys() assert Response.ERROR_TYPE_FIELD_NAME in response.data[ Response.ERROR_FIELD_NAME].keys() assert response.data[Response.ERROR_FIELD_NAME][ Response.ERROR_TYPE_FIELD_NAME] == error_type assert Response.ERROR_DETAILS_FIELD_NAME in response.data[ Response.ERROR_FIELD_NAME].keys() assert response.data[Response.ERROR_FIELD_NAME][ Response.ERROR_DETAILS_FIELD_NAME].endswith('.') # NOQA assert response.data[Response.ERROR_FIELD_NAME][ Response.ERROR_DETAILS_FIELD_NAME] == "{}.".format(message) # NOQA