Add connected/disconnected messages
This commit is contained in:
parent
34bf58d5b1
commit
66d7cd7193
25
sam/websocket/outgoing/connection.go
Normal file
25
sam/websocket/outgoing/connection.go
Normal file
@ -0,0 +1,25 @@
|
||||
package outgoing
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type (
|
||||
Connected struct {
|
||||
// Who did connect?
|
||||
UserID string `json:"uid"`
|
||||
}
|
||||
|
||||
Disconnected struct {
|
||||
// Who did disconnect?
|
||||
UserID string `json:"uid"`
|
||||
}
|
||||
)
|
||||
|
||||
func (p *Connected) EncodeMessage() ([]byte, error) {
|
||||
return json.Marshal(Payload{Connected: p})
|
||||
}
|
||||
|
||||
func (p *Disconnected) EncodeMessage() ([]byte, error) {
|
||||
return json.Marshal(Payload{Disconnected: p})
|
||||
}
|
||||
@ -4,6 +4,9 @@ type (
|
||||
Payload struct {
|
||||
*Error `json:"error,omitempty"`
|
||||
|
||||
*Connected `json:"conn,omitempty"`
|
||||
*Disconnected `json:"disc,omitempty"`
|
||||
|
||||
*Message `json:"m,omitempty"`
|
||||
*MessageDelete `json:"md,omitempty"`
|
||||
*MessageUpdate `json:"mu,omitempty"`
|
||||
|
||||
@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"github.com/crusttech/crust/auth"
|
||||
"github.com/crusttech/crust/sam/types"
|
||||
"github.com/crusttech/crust/sam/websocket/outgoing"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/titpetric/factory/resputil"
|
||||
@ -42,7 +43,8 @@ func (ws Websocket) Open(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
// Disallow all unauthorized!
|
||||
if !auth.GetIdentityFromContext(ctx).Valid() {
|
||||
identity := auth.GetIdentityFromContext(ctx)
|
||||
if !identity.Valid() {
|
||||
resputil.JSON(w, errors.New("Unauthorized"))
|
||||
return
|
||||
}
|
||||
@ -60,7 +62,11 @@ func (ws Websocket) Open(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
session := store.Save(Session{}.New(r.Context(), conn))
|
||||
|
||||
session.sendToAll(&outgoing.Connected{UserID: uint64toa(identity.GetID())})
|
||||
|
||||
if err := session.Handle(); err != nil {
|
||||
// @todo: log error, because at this point we can't really write it to w
|
||||
}
|
||||
|
||||
session.sendToAll(&outgoing.Disconnected{UserID: uint64toa(identity.GetID())})
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user