forked from mattermost/mattermost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket_router.go
98 lines (76 loc) · 2.48 KB
/
websocket_router.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
"fmt"
"net/http"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
)
type webSocketHandler interface {
ServeWebSocket(*WebConn, *model.WebSocketRequest)
}
type WebSocketRouter struct {
app *App
handlers map[string]webSocketHandler
}
func (wr *WebSocketRouter) Handle(action string, handler webSocketHandler) {
wr.handlers[action] = handler
}
func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) {
if r.Action == "" {
err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest)
ReturnWebSocketError(conn, r, err)
return
}
if r.Seq <= 0 {
err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_seq.app_error", nil, "", http.StatusBadRequest)
ReturnWebSocketError(conn, r, err)
return
}
if r.Action == model.WEBSOCKET_AUTHENTICATION_CHALLENGE {
if conn.GetSessionToken() != "" {
return
}
token, ok := r.Data["token"].(string)
if !ok {
conn.WebSocket.Close()
return
}
session, err := wr.app.GetSession(token)
if err != nil {
conn.WebSocket.Close()
return
}
wr.app.Srv.Go(func() {
wr.app.SetStatusOnline(session.UserId, false)
wr.app.UpdateLastActivityAtIfNeeded(*session)
})
conn.SetSession(session)
conn.SetSessionToken(session.Token)
conn.UserId = session.UserId
wr.app.HubRegister(conn)
resp := model.NewWebSocketResponse(model.STATUS_OK, r.Seq, nil)
conn.Send <- resp
return
}
if !conn.IsAuthenticated() {
err := model.NewAppError("ServeWebSocket", "api.web_socket_router.not_authenticated.app_error", nil, "", http.StatusUnauthorized)
ReturnWebSocketError(conn, r, err)
return
}
handler, ok := wr.handlers[r.Action]
if !ok {
err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_action.app_error", nil, "", http.StatusInternalServerError)
ReturnWebSocketError(conn, r, err)
return
}
handler.ServeWebSocket(conn, r)
}
func ReturnWebSocketError(conn *WebConn, r *model.WebSocketRequest, err *model.AppError) {
mlog.Error(fmt.Sprintf("websocket routing error: seq=%v uid=%v %v [details: %v]", r.Seq, conn.UserId, err.SystemMessage(utils.T), err.DetailedError))
err.DetailedError = ""
errorResp := model.NewWebSocketError(r.Seq, err)
conn.Send <- errorResp
}