forked from mattermost/mattermost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket_router.go
104 lines (81 loc) · 2.57 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
99
100
101
102
103
104
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
l4g "github.com/alecthomas/log4go"
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/utils"
"net/http"
)
type webSocketHandler interface {
ServeWebSocket(*WebConn, *model.WebSocketRequest)
}
type WebSocketRouter struct {
handlers map[string]webSocketHandler
}
func NewWebSocketRouter() *WebSocketRouter {
router := &WebSocketRouter{}
router.handlers = make(map[string]webSocketHandler)
return router
}
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 := GetSession(token)
if err != nil {
conn.WebSocket.Close()
} else {
go func() {
SetStatusOnline(session.UserId, session.Id, false)
UpdateLastActivityAtIfNeeded(*session)
}()
conn.SetSession(session)
conn.SetSessionToken(session.Token)
conn.UserId = session.UserId
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
}
var handler webSocketHandler
if h, ok := wr.handlers[r.Action]; !ok {
err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_action.app_error", nil, "", http.StatusInternalServerError)
ReturnWebSocketError(conn, r, err)
return
} else {
handler = h
}
handler.ServeWebSocket(conn, r)
}
func ReturnWebSocketError(conn *WebConn, r *model.WebSocketRequest, err *model.AppError) {
l4g.Error(utils.T("api.web_socket_router.log.error"), r.Seq, conn.UserId, err.SystemMessage(utils.T), err.DetailedError)
err.DetailedError = ""
errorResp := model.NewWebSocketError(r.Seq, err)
conn.Send <- errorResp
}