73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package game
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/binary"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"net"
|
|
"server/core"
|
|
"server/packet"
|
|
)
|
|
|
|
var (
|
|
Clients = NewManager()
|
|
LoginSuccess = []byte{0}
|
|
LoginFailure = []byte{1}
|
|
)
|
|
|
|
// Login checks the account credentials and gives a network peer access to an account.
|
|
func Login(data []byte, address *net.UDPAddr, server *core.Server) error {
|
|
var loginRequest [2]string
|
|
err := json.Unmarshal(data, &loginRequest)
|
|
|
|
if err != nil {
|
|
server.Send(packet.Login, LoginFailure, address)
|
|
return err
|
|
}
|
|
|
|
username := loginRequest[0]
|
|
password := loginRequest[1]
|
|
|
|
if password != "password" {
|
|
server.Send(packet.Login, LoginFailure, address)
|
|
return errors.New("login failure")
|
|
}
|
|
|
|
randomBytes := make([]byte, 32)
|
|
_, err = rand.Read(randomBytes)
|
|
|
|
if err != nil {
|
|
server.Send(packet.Login, LoginFailure, address)
|
|
return err
|
|
}
|
|
|
|
client := Clients.Get(address)
|
|
client.KeepAlive()
|
|
client.authToken = base64.StdEncoding.EncodeToString(randomBytes)
|
|
client.player.Name = username
|
|
client.player.Position.X = 5.0
|
|
playerState := []byte(client.player.Name + "\u0000")
|
|
playerState = appendVector3(playerState, client.player.Position)
|
|
|
|
server.Send(packet.Login, append(LoginSuccess, []byte(client.authToken)...), address)
|
|
server.Send(packet.PlayerState, playerState, address)
|
|
|
|
fmt.Printf("%s logged in.\n", username)
|
|
return nil
|
|
}
|
|
|
|
func appendVector3(data []byte, vector Vector3) []byte {
|
|
bits := math.Float32bits(vector.X)
|
|
data = binary.LittleEndian.AppendUint32(data, bits)
|
|
|
|
bits = math.Float32bits(vector.Y)
|
|
data = binary.LittleEndian.AppendUint32(data, bits)
|
|
|
|
bits = math.Float32bits(vector.Z)
|
|
return binary.LittleEndian.AppendUint32(data, bits)
|
|
}
|