Split client and server
This commit is contained in:
65
server/handler/Login.gd
Normal file
65
server/handler/Login.gd
Normal file
@ -0,0 +1,65 @@
|
||||
extends PacketHandler
|
||||
|
||||
enum {
|
||||
SUCCESS = 0,
|
||||
FAIL = 1,
|
||||
}
|
||||
|
||||
## Player scene instantiated for each client.
|
||||
@export var player_scene: PackedScene
|
||||
|
||||
func _ready():
|
||||
%Server.set_handler(Packet.LOGIN, self)
|
||||
|
||||
func handle_packet(data: PackedByteArray, peer: PacketPeer):
|
||||
var client = %Server.peer_to_client(peer)
|
||||
|
||||
if client.is_logged_in():
|
||||
return
|
||||
|
||||
var data_string = data.get_string_from_utf8()
|
||||
var login_request = JSON.parse_string(data_string)
|
||||
|
||||
if login_request.size() < 2:
|
||||
login_fail(peer)
|
||||
return
|
||||
|
||||
var username = login_request[0]
|
||||
var password = login_request[1]
|
||||
var account = %Database.get_account(username)
|
||||
|
||||
if account == null || account.password != password:
|
||||
login_fail(peer)
|
||||
return
|
||||
|
||||
client.auth_token = generate_auth_token()
|
||||
client.account = account
|
||||
spawn_player(client)
|
||||
login_success(peer, client.auth_token)
|
||||
|
||||
func spawn_player(client: Client):
|
||||
var player := player_scene.instantiate()
|
||||
player.client = client
|
||||
player.server = %Server
|
||||
player.name = client.address
|
||||
client.player = player
|
||||
%Players.add_child(player)
|
||||
|
||||
func generate_auth_token() -> String:
|
||||
var crypto = Crypto.new()
|
||||
var buffer = crypto.generate_random_bytes(32)
|
||||
return Marshalls.raw_to_base64(buffer)
|
||||
|
||||
func login_success(peer: PacketPeer, auth_token: String):
|
||||
var buffer := StreamPeerBuffer.new()
|
||||
buffer.put_8(Packet.LOGIN)
|
||||
buffer.put_8(SUCCESS)
|
||||
buffer.put_data(auth_token.to_ascii_buffer())
|
||||
peer.put_packet(buffer.data_array)
|
||||
|
||||
func login_fail(peer: PacketPeer):
|
||||
var buffer := StreamPeerBuffer.new()
|
||||
buffer.put_8(Packet.LOGIN)
|
||||
buffer.put_8(FAIL)
|
||||
peer.put_packet(buffer.data_array)
|
||||
|
13
server/handler/Ping.gd
Normal file
13
server/handler/Ping.gd
Normal file
@ -0,0 +1,13 @@
|
||||
extends PacketHandler
|
||||
|
||||
func _ready():
|
||||
%Server.set_handler(Packet.PING, self)
|
||||
|
||||
func handle_packet(data: PackedByteArray, peer: PacketPeer):
|
||||
var buffer := StreamPeerBuffer.new()
|
||||
buffer.put_8(Packet.PING)
|
||||
|
||||
if data.size() > 0:
|
||||
buffer.put_8(data[0])
|
||||
|
||||
peer.put_packet(buffer.data_array)
|
Reference in New Issue
Block a user