Skip to content

Commit

Permalink
Implement authentication middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
Lekuruu committed Oct 11, 2024
1 parent e55bf3f commit d3c4786
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
12 changes: 6 additions & 6 deletions hnet/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,10 @@ func handleUserRelationshipRemove(stream *common.IOStream, player *Player) error
}

func init() {
Handlers[CLIENT_LOGIN] = handleLogin
Handlers[CLIENT_LOGIN_RECONNECT] = handleReconnect
Handlers[CLIENT_CHANGE_STATUS] = handleStatusChange
Handlers[CLIENT_REQUEST_STATS] = handleRequestStats
Handlers[CLIENT_RELATIONSHIP_ADD] = handleUserRelationshipAdd
Handlers[CLIENT_RELATIONSHIP_REMOVE] = handleUserRelationshipRemove
Handlers[CLIENT_LOGIN] = ensureUnauthenticated(handleLogin)
Handlers[CLIENT_LOGIN_RECONNECT] = ensureUnauthenticated(handleReconnect)
Handlers[CLIENT_CHANGE_STATUS] = ensureAuthentication(handleStatusChange)
Handlers[CLIENT_REQUEST_STATS] = ensureAuthentication(handleRequestStats)
Handlers[CLIENT_RELATIONSHIP_ADD] = ensureAuthentication(handleUserRelationshipAdd)
Handlers[CLIENT_RELATIONSHIP_REMOVE] = ensureAuthentication(handleUserRelationshipRemove)
}
29 changes: 29 additions & 0 deletions hnet/middlewares.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package hnet

import (
"fmt"

"github.com/hexis-revival/hexagon/common"
)

func ensureAuthentication(handler func(*common.IOStream, *Player) error) func(*common.IOStream, *Player) error {
return func(stream *common.IOStream, player *Player) error {
if !player.IsAuthenticated() {
player.CloseConnection()
return fmt.Errorf("unauthenticated player")
}

return handler(stream, player)
}
}

func ensureUnauthenticated(handler func(*common.IOStream, *Player) error) func(*common.IOStream, *Player) error {
return func(stream *common.IOStream, player *Player) error {
if player.IsAuthenticated() {
player.CloseConnection()
return fmt.Errorf("already authenticated")
}

return handler(stream, player)
}
}
4 changes: 4 additions & 0 deletions hnet/player.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ func (player *Player) SendPacket(packetId uint32, packet Serializable) error {
return player.SendPacketData(packetId, stream.Get())
}

func (player *Player) IsAuthenticated() bool {
return player.Info.Id != 0 || player.Info.Name != ""
}

func (player *Player) OnLoginSuccess(responsePassword string, userObject *common.User) error {
otherUser := player.Server.Players.ByID(uint32(userObject.Id))

Expand Down

0 comments on commit d3c4786

Please sign in to comment.