async def login(message, client, broadcast): request = LoginRequest() request.ParseFromString(message.serialized_message) response = LoginResponse() with AccountService() as service: try: account = service.get(request.username, request.password) except (AccountNotFoundError, InvalidPasswordError): response.success = False response.error_message = 'Invalid credentials' else: response.success = True client.username = account.username account.logged_in = True if response.success: with PlayerService() as service: account = service.session.merge(account) for character in account.characters: service.remove(character.id) await client.send(Message( message_type=MessageType.login_response, message=response))
async def create_character(message, client, server): info = CreateCharacterRequest() info.ParseFromString(message.serialized_message) character = Character(account_username=client.username, name=info.name, body_color=info.body_color, shirt_color=info.shirt_color, legs_color=info.legs_color, last_x=300, last_y=300, velocity_x=0, velocity_y=0, last_position_update=datetime.now()) response = CreateCharacterResponse() with AccountService() as service: character_id = service.add_character(client.username, character) response.success = True response.character_id = character_id response.x = character.last_x response.y = character.last_y await client.send( Message(message_type=MessageType.create_character_response, message=response))
async def characters_request(message, client, broadcast): response = CharactersResponse() with AccountService() as service: characters = service.get_characters(client.username) for character in characters: character_info = response.characters.add() character_info.character_id = character.id character_info.name = character.name character_info.color = character.color character_info.x = character.last_x character_info.y = character.last_y await client.send( Message(message_type=MessageType.characters_response, message=response))
async def register_account(message, client, broadcast): request = RegisterRequest() request.ParseFromString(message.serialized_message) response = RegisterResponse() with AccountService() as service: try: service.create(request.username, request.password) except AccountAlreadyExistsError: response.success = False response.error_message = 'Username already in use' else: response.success = True await client.send( Message(message_type=MessageType.register_response, message=response))