66 lines
2.1 KiB
Go
66 lines
2.1 KiB
Go
package tcp
|
|
|
|
import (
|
|
"context"
|
|
|
|
"spark-server/internal/pkg/errs"
|
|
"spark-server/internal/pkg/i18n"
|
|
"spark-server/internal/transport/tcp/protocol"
|
|
"spark-server/internal/transport/tcp/session"
|
|
)
|
|
|
|
func (s *Server) registerDefaultHandlers() {
|
|
s.router.Register(protocol.CmdAuth, s.handleAuth)
|
|
s.router.Register(protocol.CmdGenerateMsgID, s.handleGenerateMsgID)
|
|
s.router.Register(protocol.CmdSendMessage, s.handleSendMessage)
|
|
s.router.Register(protocol.CmdRecallMessage, s.handleRecallMessage)
|
|
s.router.Register(protocol.CmdDeleteMessage, s.handleDeleteMessage)
|
|
s.router.Register(protocol.CmdSyncInbox, s.handleSyncInbox)
|
|
s.router.Register(protocol.CmdSyncMessages, s.handleSyncMessages)
|
|
}
|
|
|
|
func (s *Server) handleAuth(ctx context.Context, conn *session.Conn, frame protocol.Frame) (*protocol.Frame, error) {
|
|
if s.auth == nil {
|
|
return nil, errs.ErrUnauthorized
|
|
}
|
|
req, err := protocol.DecodeAuthRequest(frame.Body)
|
|
if err != nil {
|
|
return nil, errs.ErrInvalidArgument
|
|
}
|
|
conn.SetLanguage(i18n.Parse(req.Language).String())
|
|
principal, err := s.auth.Authenticate(ctx, req.Token)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if req.DeviceID != 0 && req.DeviceID != principal.DeviceID {
|
|
return nil, errs.ErrUnauthorized
|
|
}
|
|
conn.Authenticate(principal.UserID, principal.DeviceID)
|
|
if err := s.sessions.Bind(conn); err != nil {
|
|
return nil, err
|
|
}
|
|
conn.Activate()
|
|
body := protocol.EncodeOK(conn.RequestID(), protocol.AuthResponse{UserID: principal.UserID, DeviceID: principal.DeviceID})
|
|
return &protocol.Frame{
|
|
Version: protocol.CurrentVersion, Command: protocol.CmdAuth,
|
|
RequestID: frame.RequestID, SequenceID: frame.SequenceID, Body: body,
|
|
}, nil
|
|
}
|
|
|
|
func (s *Server) handleGenerateMsgID(_ context.Context, conn *session.Conn, frame protocol.Frame) (*protocol.Frame, error) {
|
|
if s.ids == nil {
|
|
return nil, errs.ErrInternal
|
|
}
|
|
if !conn.Authenticated() {
|
|
return nil, errs.ErrUnauthorized
|
|
}
|
|
id, err := s.ids.NextMsgID()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &protocol.Frame{
|
|
Version: protocol.CurrentVersion, Command: protocol.CmdGenerateMsgID,
|
|
RequestID: frame.RequestID, SequenceID: frame.SequenceID, Body: protocol.EncodeMsgID(conn.RequestID(), id),
|
|
}, nil
|
|
}
|